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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
532f84b7768c2f7bdff56ab53d8755cf340b92d2 | C++ | ChopsII/neural_net_cpp | /src/assets/neuron.cpp | UTF-8 | 516 | 2.6875 | 3 | [] | no_license | #include "synapse.h"
#include "neuron.h"
Neuron::Neuron(float init_output_value, float init_threshold)
: Soma(init_threshold)
{
output_value = init_output_value;
}
void Neuron::add_synapse(Synapse& new_synapse)
{
all_synapses.emplace_back(new_synapse);
}
void Neuron::set_output_value()
{
float incoming_values = add_incoming_values();
float activation_result = activate(incoming_values);
output_value = activation_result;
}
float Neuron::get_output_value()
{
return output_value;
}
| true |
20bf50d617dee36f6e2a9f21e75686a1ab3c81e1 | C++ | khvysofq/vscp | /src/vscp/net/vscpserver.cpp | UTF-8 | 2,678 | 2.546875 | 3 | [] | no_license | // Vision Zenith System Communication Protocol (Project)
#include "vscp/net/vscpserver.h"
namespace vscp {
VscpServer::VscpServer(boost::asio::io_service& io_service,
BaseSessionManager *session_manager,
const std::string server_address,
uint16 server_port)
:io_service_(io_service),
session_manager_(session_manager),
server_address_(server_address),
server_port_(server_port),
endpoint_(server_address.empty() ?
(boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), server_port_)) :
boost::asio::ip::tcp::endpoint(boost::asio::ip::address().from_string(
server_address_), server_port_)),
is_stop_server_(false){
}
bool VscpServer::StartServer(){
if (SetStartServer()){
LOG(ERROR) << "The server is run, you can't start again";
return false;
}
try{
acceptor_.reset(new boost::asio::ip::tcp::acceptor(
io_service_, endpoint_));
}
catch (std::exception& e){
LOG(ERROR) << "bind address getting an error " << e.what();
return false;
}
io_service_.post(boost::bind(
&VscpServer::StartAccept, shared_from_this()));
return true;
}
bool VscpServer::StopServer(){
if (SetStopServer()){
LOG(ERROR) << "The server is not run, you can't stop it";
return false;
}
io_service_.post(
boost::bind(&VscpServer::HandleStopAccept, shared_from_this()));
return true;
}
void VscpServer::StartAccept(){
// Add session
BaseSession::SessionPtr new_session =
session_manager_->CreateServerSession(io_service_);
acceptor_->async_accept(new_session->Socket(),
boost::bind(&VscpServer::HandleAccept, shared_from_this(), new_session,
boost::asio::placeholders::error));
}
void VscpServer::HandleAccept(BaseSession::SessionPtr new_session,
const boost::system::error_code& err){
if (err){
LOG(WARNING) << "Accpet new connect get an error :" << err;
return;
}
static int count = 1;
std::cout << count++ << "\t";
// Make sure, the ServerSession::InitSession is non-blocking
new_session->InitServerSession();
StartAccept();
}
void VscpServer::HandleStopAccept(){
if (is_stop_server_){
LOG(ERROR) << "The server flags is not stop state";
return;
}
try{
// Cancel or close, should test
// see http://www.boost.org/doc/libs/1_52_0/doc/html/boost_asio/reference/basic_socket/cancel/overload1.html
if (acceptor_->is_open()){
acceptor_->close();
}
}
catch (std::exception& e){
LOG(ERROR) << "Close acceptor getting an exception " << e.what();
}
}
}; // namespace vscp | true |
2a5ecbeb49c058f67d8550619acaf82ef886ec71 | C++ | zhushiqi123/ios- | /C++语言程序设计 郑莉 第四版(课件、课后答案、例题源代码)/C++语言程序设计案例的源代码和目录/10852C++案例教程源代码/case03/3_4.cpp | GB18030 | 409 | 3.40625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int sgn(double x) //źsgn()䷵ֵΪint
{ if (x>0) return(1); //س1
if (x<0) return(-1); //س2
return(0); //س3
}
int main()
{ double x;
for (int i=0;i<=2;i++)
{ cout<<"Input x="; cin>>x;
cout<<"sgn("<<x<<")="<<sgn(x)<<endl;
}
return 0;
}
| true |
f18c203dfb8aeaada6d378c0ad62e7fd9a8cffa9 | C++ | besSveta/otuscpp11 | /bulkasync.h | UTF-8 | 1,989 | 3.046875 | 3 | [] | no_license | /*
* bulkmt.h
*
* Created on: 30 июн. 2019 г.
* Author: sveta
*/
#pragma once
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <chrono>
#include <ctime>
#include <sys/stat.h>
#include <sys/types.h>
#include<vector>
class BulkInfo {
std::string bulkString;
int commandCount;
std::string recieveTime;
bool outputed;
bool written;
public:
BulkInfo(std::string bulkStr, int commandCnt, std::string rTime) :
bulkString(bulkStr), commandCount(commandCnt), recieveTime(rTime), outputed(
false), written(false) {
}
std::string GetBulkString();
int GetCommandCount();
std::string GetTime();
bool GetOutputed();
void SetOutputed(bool val);
bool GetWritten() ;
void SetWritten(bool val);
};
class CommandProcessor;
using sclock = std::chrono::system_clock;
// сохраняет команды и выполняет их при необходимости.
class CommandCollector {
std::stringstream bulkString;
std::string recieveTime;
size_t commandsCount;
friend CommandProcessor;
void Clear();
public:
CommandCollector();
size_t size();
void AddCommand(std::string command, std::string time);
// Выполнить команды и записать их в файл;
BulkInfo Process() ;
};
enum class State {
Processed, Finish, WaitComand,
};
// получает команду и решает, что делать: выполнять или копить.
class CommandProcessor {
const size_t N;
CommandCollector commandCollector;
int openCount;
int closeCount;
const std::string openBrace = "{";
const std::string closeBrace = "}";
void CallProcessor() {
if (commandCollector.size() > 0) {
bulks.push_back(commandCollector.Process());
processorState = State::Processed;
}
}
State processorState;
public:
CommandProcessor(size_t n);
std::vector<BulkInfo> bulks;
size_t GetBulkSize();
void SetState(State st);
State GetState();
void ProcessCommand(std::string command) ;
};
| true |
32fd2c3d3a0b18c490c65fa0127f03d00a774be6 | C++ | indranilm256/Compiler-project | /src/type_check.h | UTF-8 | 1,111 | 2.78125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <cstring>
#include <unordered_map>
#include <map>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
bool isInt (string type);
bool isSignedInt (string type);
bool isFloat (string type);
bool isSignedFloat (string type);
class type_check
{
public:
static char* primary(char* identifier);
static char* constant(int nType);
static char* postfix(string type, int prodNum);
static char* argument(string type1, string type2);
static char* unary(string op, string type);
static char* multiplicative(string type1, string type2, char op);
static char* additive(string type1, string type2, char op);
static char* shift(string type1,string type2);
static char* relational(string type1,string type2,char * op);
static char * equality(string type1,string type2);
static char * bitwise(string type1,string type2);
static char* conditional(string type1,string type2);
static char* valid_assignment(string type1,string type2);
static char* assignment(string type1,string type2,char* op);
};
| true |
c0f1dfddbf601a4efe670bc4063b4376ac21a89b | C++ | Hannna/robocupsslclient | / robocupsslclient/additional.h | UTF-8 | 6,968 | 2.53125 | 3 | [] | no_license | #ifndef ADDITIONAL_H_
#define ADDITIONAL_H_
#include <string>
#include <iostream>
#include <vector>
#include <map>
#include <sstream>
#include <math.h>
#include <sys/time.h>
#include <strings.h>
#include <list>
#include "boost/tuple/tuple.hpp"
#include "Vector2d/Vector2D.h"
#include "RotationMatrix/RotationMatrix.h"
#include <boost/math/special_functions/fpclassify.hpp>
#include <libxml/tree.h>
#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>
//dokladnosc polozenia robota
//lub okreslania czy robot jest u celu itp
#define LOCATION_PRECISION 0.01
#define ROTATION_PRECISION 0.01
#include <cmath>
#include <limits>
bool equealDouble(const double & a, const double & b);
enum goalArea{
top,
bottom
};
/**
* @mainpage
* @author Kamil Muszyński, Maciej Gąbka
*
* @ref poprawki_gazebo @n
* @ref skladnia_plik_swiat
*/
/**
* @page poprawki_gazebo Poprawki wprowadzone do Gazebo
*
* Model.cc
* - funkcja reset - odkomentowano linie dotyczące zerowania prędkości
* - funkcja setPose - dodano zerowanie prędkości (Model.cc -> setPose, wywolywane w World.cc)
*
* World.cc
* - dodane obsługi rządania get_all_poses - powoduje ono zapis pozycji wszystkich modeli podanych w model_name
* simulationData do pliku /tmp/gazebo_poses.txt. Plik ten jest następnie odczytywany przez videoserver. W dużym stopniu
* przyspiesza to pracę z symulatorem (nie potrzeba pojedynczo odpytywać o każdy z modeli).
*/
const int TEAM_SIZE = 3;
class Pose;
class RotationMatrix;
typedef std::map<std::string,Pose >::iterator PositionsIt;
/**
* typ do przechowywania informacji o polozeniu i rotacji robota
*/
class Pose: public boost::tuple<double,double,double>{
public:
Pose():boost::tuple<double,double,double>(){
;
}
Pose(double x,double y,double rot):boost::tuple<double,double,double>(x,y,rot){
;
}
Pose(Vector2D v,double rot):boost::tuple<double,double,double>(v.x,v.y,rot){
;
}
const Pose operator-(const Pose & pose) const {
Pose p(this->get<0>()-pose.get<0>(),
this->get<1>()-pose.get<1>(),
this->get<2>()-pose.get<2>() );
return p;
}
const Pose operator-=(const Pose &pose){
this->get<0>()-=pose.get<0>();
this->get<1>()-=pose.get<1>();
this->get<2>()-=pose.get<2>();
return *this;
}
const Pose operator*=(const double a){
this->get<0>()*=a;
this->get<1>()*=a;
this->get<2>()*=a;
return *this;
}
const Pose operator*(const double a){
return Pose( this->get<0>()*a,
this->get<1>()*a,
this->get<2>()*a );
}
const Pose operator+(const Pose a) const{
return Pose( this->get<0>()+a.get<0>(),
this->get<1>()+a.get<1>(),
this->get<2>()+a.get<2>() );
}
const Pose operator+(const Vector2D v) const{
return Pose( this->get<0>()+v.x,
this->get<1>()+v.y, this->get<2>() );
}
bool operator==(const Pose a){
if( !equealDouble(this->get<0>() , a.get<0>() ) )
return false;
if( !equealDouble(this->get<1>() , a.get<1>() ) )
return false;
if( !equealDouble(this->get<2>() , a.get<2>() ) )
return false;
return true;
}
Vector2D getPosition()const {
return Vector2D(this->get<0>(),this->get<1>());
}
/*@brief transformuje biezace polozenie robota do ukl obroconego o rm i przesunietego o distance
*
*/
Pose transform(const Vector2D& distance,const RotationMatrix & rm) const ;
Pose translation(const Vector2D& distance) const ;
//odleglosc w sensie euklidesowym
double distance(const Pose &p) const {
return sqrt( pow(this->get<0>()-p.get<0>(),2) + pow(this->get<1>()-p.get<1>(),2) );
}
friend std::ostream& operator<<(std::ostream& os,const Pose& pose);
};
class Region{
public:
friend std::ostream& operator<<(std::ostream& os,const Region& region);
Region(const Vector2D lbc,const Vector2D ruc);
Vector2D getMiddle();
virtual ~Region();
private:
Region();
const Vector2D lbc;
const Vector2D ruc;
};
class StraightLine{
public:
friend std::ostream& operator<<(std::ostream& os,const StraightLine& line);
StraightLine(const Vector2D p1,const Vector2D p2);
Vector2D getPoint1(){
return p1;
}
Vector2D getPoint2(){
return p2;
}
double distFromPoint( const Vector2D p1 );
double getA() const {
return A;
}
double getB() const {
return B;
}
double getC() const {
return C;
}
Vector2D getP1() const {
return p1;
}
Vector2D getP2() const {
return p2;
}
double angleToOX( ){
Vector2D w( this->B, -1.0*this->A );
return w.angleTo( Vector2D(1.0,0.0) );
}
double angleToOY( ){
Vector2D w( this->B, -1.0*this->A );
return w.angleTo( Vector2D(0.0,1.0) );
}
double incline(){
if(fabs(this->A) < 0.01)
return 0;
if(fabs(this->B) < 0.01)
return M_PI/2.0;
return atan(-this->A/this->B);
//return atan2(-this->A,this->B);
//return atan2(this->B,-this->A);
//return atan2()
}
virtual ~StraightLine();
private:
StraightLine();
double A,B,C;
const Vector2D p1;
const Vector2D p2;
};
typedef std::vector<std::string> strvec;
///@brief Funkcja signum
double sgn(double d);
///@brief Konwertuje zadany kąt w radianach do przedziału -PI...PI
///@return kąt w radianach z przedziału -M_PI..+M_PI
double convertAnglePI(double angle);
///@brief Konwertuje zadany kąt w radianach do przedziału 0..2PI
///@return kąt w radianach z przedziału 0..+2*M_PI
double convertAngle2PI(double angle);
//oblicza jaka rotacje musi miec robot aby byc skierowanym na cel
double calculateProperAngleToTarget(const Pose &currRobotPose,const Pose &targetPose );
//oblicza kat o jaki trzeba sie obrocic do celu
double calculateAngleToTarget( const Pose &currRobotPose,const Pose &targetPose );
/*
Pose transformCoordinatesToRobot(currRobotPose){
currRobotPose=(*currGameState).getRobotPos( robot->getRobotID() );
robotRotation = currRobotPose.get<2>();
rm = RotationMatrix(robotRotation);
t = nextRobotPose.transform( currRobotPose.getPosition() , rm);
}
*/
template <class T>
double euclideanNorm(T t1, T t2 ){
return sqrt( pow(t1-t2,2 ) );
}
template <>
double euclideanNorm<Vector2D>(Vector2D t1, Vector2D t2 );
/** @author Kamil Muszyński
*
* @brief klasa zawierająca nazwy wszystkich modeli gazebo znajdujących się na planszy
* */
/*
class Names{
public:
static strvec & getNames();
~Names();
private:
static strvec names_list;
Names();
};
*/
/**
* function to convert strings to sth else
* i.e int, unsigned int
*/
template <class T>
bool from_string(T& t,
const std::string& s,
std::ios_base& (*f)(std::ios_base&))
{
std::istringstream iss(s);
return !(iss >> f >> t).fail();
}
enum what{start_measure, stop_measure};
double measureTime(what what_,struct timespec * startTime);
//int xpathTest(const char* filename, const xmlChar* xpathExpr);
//struct timeval measureTime(what what_,struct timeval * startTime);
std::list<std::string> getRobotNames(const char* filename, const xmlChar* xpathExpr);
#endif /*ADDITIONAL_H_*/
| true |
8990afbc818601d602c2e1333fb967902d7cd0a6 | C++ | jamalbouizem/Deus-Ex-Machina | /DeusExMachina/DeusExMachina/FileCSV.cpp | UTF-8 | 698 | 2.59375 | 3 | [] | no_license | #include "FileCSV.hpp"
using namespace DEM::Core;
FileCSV::FileCSV(std::string path)
: File(path)
{
separator = ';';
loadDatas();
}
FileCSV::~FileCSV()
{
}
Resource& FileCSV::loadDatas()
{
File::load();
datas.clear();
m_reader.open(m_path.c_str(), std::ios::in);
if (m_reader)
{
std::strstream stream;
std::string line;
while (std::getline(m_reader, line))
{
stream << line;
std::vector<std::string> dataLine = StringUtility::Split(line, separator);
if (line.substr(0, 2) != "//" && line.substr(0, 1) != "#")
{
datas.emplace_back(dataLine);
}
else
{
comments.emplace_back(line);
}
}
stream << '\0';
m_reader.close();
}
return *this;
} | true |
4b33eeb8a1d1a7b03e13085ce02ca6f3c5fdf3d0 | C++ | Elbagast/TF2_Mod_Builder | /sak/outliner_model.hpp | UTF-8 | 7,937 | 2.53125 | 3 | [] | no_license | #ifndef SAK_OUTLINER_MODEL_HPP
#define SAK_OUTLINER_MODEL_HPP
#ifndef SAK_OUTLINER_MODEL_FWD_HPP
#include "outliner_model_fwd.hpp"
#endif
#ifndef INCLUDE_STD_MEMORY
#define INCLUDE_STD_MEMORY
#include <memory>
#endif
#ifndef INCLUDE_STD_VECTOR
#define INCLUDE_STD_VECTOR
#include <vector>
#endif
#ifndef INCLUDE_QT_QABSTRACTITEMMODEL
#define INCLUDE_QT_QABSTRACTITEMMODEL
#include <QAbstractItemModel>
#endif
class QAbstractItemView;
namespace sak
{
class Abstract_Outliner_Item;
//---------------------------------------------------------------------------
// Outliner_Model
//---------------------------------------------------------------------------
// A specialised model with only one column. Create a sublclass of Abstract_Outliner_Item
// and give it to this class in order to use it. Outliner_Model relies entirely
// on the public interface of Abstract_Outliner_Item
class Outliner_Model :
public QAbstractItemModel
{
Q_OBJECT
public:
// Special 6
//============================================================
// Construct without an associated root item. The model will function but be empty.
explicit Outliner_Model(QObject* a_parent = nullptr);
// Construct with an associated root item. The model will function using this root.
explicit Outliner_Model(Abstract_Outliner_Item* a_root, QObject* a_parent = nullptr);
~Outliner_Model() override;
// Virtual Overrides
//============================================================
// Read functions
//----------------------------------------
// Get the flags for the Outliner_Item at a given QModelIndex.
Qt::ItemFlags flags(QModelIndex const& a_index) const override;
// Get the data for the Outliner_Item at a given QModelIndex.
QVariant data(QModelIndex const& a_index, int a_role) const override;
// Get the header data for a given section and orientation
//QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
// Write functions
//----------------------------------------
// Set the data at a given index with value, using role
bool setData(QModelIndex const& a_index, QVariant const& a_value, int a_role = Qt::EditRole) override;
//bool setHeaderData ( int section, Qt::Orientation orientation, QVariant const& value, int role = Qt::EditRole ) override;
// these are the inbuilt functions for this, but it isn't clear how they would be used in this case...
//bool insertRows(int row, int count, QModelIndex const& parent = QModelIndex() ) override;
//bool removeRows(int row, int count, QModelIndex const& parent = QModelIndex() ) override;
//bool moveRows(QModelIndex const& a_source_parent, int a_source_row, int a_count, QModelIndex const& a_destination_parent, int a_destination_child) override;
// Indexing
//----------------------------------------
// The number of rows (children) the Outliner_Item at a given QModelIndex has.
int rowCount(QModelIndex const& a_parent = QModelIndex()) const override;
// Always returns 1
int columnCount(QModelIndex const& a_parent = QModelIndex()) const override;
// Get the index of the item at the given position
QModelIndex index(int a_row, int a_column, QModelIndex const& a_parent = QModelIndex()) const override;
// Get the index of the parent of the item at a given index
QModelIndex parent(QModelIndex const& a_index) const override;
// Custom Access
//============================================================
// Does the model have any data to show? i.e. is there a root item?
bool is_active() const;
// Access the root item. The root is not owned by Outliner_Model.
Abstract_Outliner_Item* get_root() const;
// Replace the root item and refresh the model in all views. The old
// root is not deleted. The new root is not owned by Outliner_Model.
void set_root(Abstract_Outliner_Item* a_root);
// Make an index from an item, mostly so that Outliner_Item can make an index of itself without being a friend
QModelIndex create_index_from_item(Abstract_Outliner_Item* item) const;
// call QAbstractItemView->edit on this item
//void callEditInView(QAbstractItemView* view, Outliner_Item* item);
//void callEditInView(QAbstractItemView* view, QModelIndex const& index);
// Update Calls
//============================================================
// Functions to tell the model to emit change signals
void data_changed(QModelIndex const& a_top_left, QModelIndex const& a_bottom_right, QVector<int> const& a_roles = QVector<int>());
// Helper classes
//============================================================
// Providing access to these signals without implementing the actions.
friend class Outliner_Rows_Mover;
friend class Outliner_Rows_Inserter;
friend class Outliner_Rows_Remover;
Outliner_Rows_Mover make_rows_mover(QModelIndex const& a_source_parent, int a_source_row, int a_source_last, QModelIndex const& a_destination_parent, int a_destination_child);
Outliner_Rows_Inserter make_rows_inserter(int a_row, int a_last, QModelIndex const& a_parent = QModelIndex());
Outliner_Rows_Remover make_rows_remover(int a_row, int a_last, QModelIndex const& a_parent = QModelIndex());
Outliner_Rows_Mover make_row_mover(QModelIndex const& a_source_parent, int a_source_row, QModelIndex const& a_destination_parent, int a_destination_child);
Outliner_Rows_Inserter make_row_inserter(int a_row, QModelIndex const& a_parent = QModelIndex());
Outliner_Rows_Remover make_row_remover(int a_row, QModelIndex const& a_parent = QModelIndex());
signals:
void signal_editor_requested(Abstract_Outliner_Item* a_item);
void signal_unsaved_edits(bool a_state);
private:
// Data Members
//============================================================
Abstract_Outliner_Item* m_root;
};
// Helper classes
//============================================================
// Providing access to these signals without implementing the actions.
//---------------------------------------------------------------------------
// Outliner_Rows_Mover
//---------------------------------------------------------------------------
class Outliner_Rows_Mover
{
private:
friend class Outliner_Model;
Outliner_Rows_Mover(Outliner_Model* a_model,
QModelIndex const& a_source_parent,
int a_source_row,
int a_source_last,
QModelIndex const& a_destination_parent,
int a_destination_child);
public:
~Outliner_Rows_Mover();
private:
Outliner_Model* m_model;
};
//---------------------------------------------------------------------------
// Outliner_Rows_Inserter
//---------------------------------------------------------------------------
class Outliner_Rows_Inserter
{
private:
friend class Outliner_Model;
Outliner_Rows_Inserter(Outliner_Model* a_model,
int a_row, int a_last,
QModelIndex const& a_parent = QModelIndex());
public:
~Outliner_Rows_Inserter();
private:
Outliner_Model* m_model;
};
//---------------------------------------------------------------------------
// Outliner_Rows_Remover
//---------------------------------------------------------------------------
class Outliner_Rows_Remover
{
private:
friend class Outliner_Model;
Outliner_Rows_Remover(Outliner_Model* a_model,
int a_row,
int a_last,
QModelIndex const& a_parent = QModelIndex());
public:
~Outliner_Rows_Remover();
private:
Outliner_Model* m_model;
};
} // namespace sak
#endif // SAK_OUTLINER_MODEL_HPP
| true |
e4a88c5f3586a9006da06af64b5e914d983cd53f | C++ | valhassan/simple-programs | /practice/tempconversion.cpp | UTF-8 | 652 | 3.71875 | 4 | [] | no_license | #include<stdio.h>
float C_Fah(float);
float F_Cel(float);
void main()
{
char ty;
float cel, fah, Fa, Ce;
printf("THIS PROGRAM CONVERTS TEMP. FROM CELSIUS TO FAHRENHEIT & VICE VERSA\n");
printf("INDICATE CONVERTION TYPE: ENTER F or f FOR FAHRENHEIT:");
scanf("%c", &ty);
if(ty=='F'||ty=='f'){
printf("\nEnter Temp. in Celsius:");
scanf("%f", &cel);
Fa=C_Fah(cel);
printf("\nTemp. in Fahrenheit=%.2f", Fa);
}
else{
printf("\nEnter Temp. in Fahrenheit:");
scanf("%f", &fah);
Ce=F_Cel(fah);
printf("\nTemp. in Celsius=%.2f\n", Ce);
}
}
float C_Fah(float c)
{
float a;
a=(9*c+32)/5;
return(a);
}
float F_Cel(float f)
{
float b;
b= 5*(f-32)/9;
return(b);
}
| true |
5dc08e9e103e27c41958fa97ace4af4f292b6dae | C++ | renatomb/engComp | /programacaoC/TRAB1UNID/TRAB5.CPP | ISO-8859-1 | 1,189 | 3.234375 | 3 | [] | no_license | /*---------------------------------
UNP - Universidade Potiguar
Curso de Engenharia de Computacao - 1 Ano
Disciplina Programacao Cientifica - 1 Unidade
Professor: Marcelo Mariano
Aluno: RENATO MONTEIRO BATISTA
Trabalho de C++ - Questo 05
---------------------------------*/
#include <iostream.h>
void main() {
float banco[30][5];
for (int i=0; i<30; i++) {
cout << "Informe o numero da conta: ";
cin >> banco[i][0];
cout << "Informe o saldo anterior: ";
cin >> banco[i][1];
{
char oper;
cout << "Informe a operacao D = Debito, C = Credito: ";
cin >> oper;
cout << "Informe o valor da operacao: ";
cin >> banco[i][2];
if (oper == 'C' || oper == 'c') banco[i][3]=banco[i][1]+banco[i][2];
else {
if (oper == 'D' || oper == 'd') banco[i][3]=banco[i][1]-banco[i][2];
}
}
if (banco[i][3] <0) banco[i][4]=-1;
else banco[i][4]=0;
}
cout << "\nCorrentistas com saldo positivo:\n";
int count=0;
for (i=0; i<30; i++) {
if (banco[i][4] == 0) {
cout << "\n* " << banco[i][0];
if (banco[i][3] >= 1000 && banco[i][3] <= 10000) count++;
}
}
cout << "\nTotal de correntistas com saldo entre R$ 1.000,00 e R$ 10.000,00: " << count;
} | true |
5553fa4c95b9e99984430093d1b0f86f50c0773a | C++ | vster/CryptSecNetBook | /Lecture05/p163/p163.cpp | UTF-8 | 743 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <stdint.h>
#define byte unsigned char
using namespace std;
// typedef unsigned char byte;
typedef unsigned short u16bit;
typedef unsigned int u32bit;
typedef uint64_t u64bit;
typedef signed int s32bit;
byte f( byte k )
{
return ( k * k );
}
void bin_output ( byte x )
{
int arr[8];
int bitlen = 8 * sizeof ( byte );
for ( int i = 0; i < bitlen; i++ )
{
arr[i] = x&0x1;
x >>= 1;
}
for ( int i = bitlen-1; i >= 0; i-- )
cout << arr[i];
}
int main()
{
byte P = 0x7;
byte K = 0x3;
// cout << hex << P << endl;
bin_output ( P );
cout << endl;
byte C = P ^ f ( K );
bin_output ( C );
cout << endl;
// cout << hex << C << endl;
byte D = C ^ f ( K );
bin_output ( D );
cout << endl;
}
| true |
326f32e615aa8b396f8db65fa934139907e0ef3e | C++ | okmechak/SandBox | /Patterns/Creational.cpp | UTF-8 | 2,226 | 3.25 | 3 | [] | no_license | #include "Creational.h"
#include <iostream>
using namespace std;
/*!
Example from refactoring guru
full documentation see here: https://refactoring.guru/uk/design-patterns/factory-method
*/
namespace FabricMethod
{
namespace ProductCreator
{
void ConcreteProductA::doStuff()
{
cout << "Doing stuff of Product A." << endl;
}
void ConcreteProductB::doStuff()
{
cout << "Doing stuff of Product B." << endl;
}
void Creator::SomeOperation()
{
auto concreteProduct = createProduct();
concreteProduct->doStuff();
delete concreteProduct;
}
Product* ConcreteCreatorA::createProduct()
{
return (Product*)new ConcreteProductA();
}
Product* ConcreteCreatorB::createProduct()
{
return (Product*)new ConcreteProductB();
}
void ExampleOfUse()
{
Creator* creator = (Creator*)new ConcreteCreatorA;
creator->SomeOperation();
//TODO what if exceptions was thrown?
delete creator;
creator = (Creator*)new ConcreteCreatorB;
creator->SomeOperation();
//TODO what if exceptions was thrown?
delete creator;
}
}
namespace ButtonDialog
{
void Button::OnClick(Dialog * dlg)
{
cout << "Button clicked." << endl;
//TODO
//How to pass member as function pointer??
dlg->closeDialog();
}
void Button::render()
{
cout << "Windows button render." << endl;
}
void WebButton::render()
{
cout << "Web button render." << endl;
}
void WindwosButton::render()
{
cout << "Web button render." << endl;
}
void Dialog::closeDialog()
{
cout << "Dialog closed." << endl;
}
void Dialog::render()
{
cout << "Dialog render." << endl;
auto button = renderButton();
button->OnClick(this);
button->render();
delete button;
}
Button* WindowsDialog::renderButton()
{
return (Button*)new WindwosButton;
}
Button* WebDialog::renderButton()
{
return (Button*)new WebButton;
}
void ExampleOfUse()
{
Dialog* dialog;
if (true)
dialog = (Dialog*)new WindowsDialog;
else if (false)
dialog = (Dialog*)new WebDialog;
else
throw;
dialog->render();
//TODO what if exceptions was thrown by render() function?
delete dialog;
};
}
} | true |
bf150113fb13171ec9b05ef5c8fea4c27ce07dcd | C++ | krishnan1159/Contest | /hackerrank/oct13/angry_children_2.cpp | UTF-8 | 1,058 | 2.765625 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
std::ios_base::sync_with_stdio(false);
int n,k,x,i,minAns = 0,ans=0,addFactor = 0,subFactor = 0;
vector<int> packets;
cin>>n>>k;
for(i=0;i<n;i++)
{
cin>>x;
packets.push_back(x);
}
std::sort(packets.begin(),packets.end(),greater<int>());
/* Now the Values in packets are sorted in decreasing order */
vector<int> sum(n+2,0);
for(i=1;i<n;i++)
sum[i] = sum[i-1] + packets[i-1];
for(i=1;i<k;i++)
{
addFactor = sum[i] - i*packets[i];
ans += addFactor;
}
minAns = ans;
for(i=k;i<n;i++)
{
subFactor = packets[i-k] * (k-1) - (sum[i]-sum[i-k+1]);
addFactor = (sum[i] - sum[i-k+1]) - packets[i]*(k-1);
cout<<addFactor<<" "<<subFactor<<endl;
ans = ans + addFactor - subFactor;
minAns = (ans < minAns) ? ans : minAns;
}
return 0;
}
| true |
47b1683cee2af75c63bce9a4fe70555ac2fd0d1d | C++ | maximesong/voici | /src/PreviewCanvas.cpp | UTF-8 | 1,135 | 2.71875 | 3 | [] | no_license | #include "PreviewCanvas.h"
#include <iostream>
using namespace std;
PreviewCanvas::PreviewCanvas(QWidget *parent)
:QLabel(parent)
{
standard_width = 250;
standard_height = 200;
setMinimumSize(standard_width, standard_height);
}
void PreviewCanvas::drawImage(const ImageFamily &imageCore)
{
QImage image = imageCore.getCurrentImage();
drawImage(image);
}
void PreviewCanvas::drawImage(const QImage &image)
{
double widthScaledRate = double(standard_width) / image.width();
double heightScaledRate = double(standard_height) / image.height();
double scaledRate = qMin(widthScaledRate, heightScaledRate);
QImage scaledImage = image.scaled (image.width() * scaledRate,
image.height() * scaledRate,
Qt::IgnoreAspectRatio,
Qt::FastTransformation);
QPixmap pixmap = QPixmap::fromImage(scaledImage);
setPixmap(pixmap);
}
void PreviewCanvas::setStandardSize(int width, int height)
{
standard_width = width;
standard_height = height;
}
void PreviewCanvas::setStandardWidth(int width)
{
standard_width = width;
}
void PreviewCanvas::setStandardHeight(int height)
{
standard_height = height;
}
| true |
3c92068621e0763d9d4067fa8762ceb237d6f88a | C++ | chipolux/coding-math | /cpp-sdl2/ep02.cpp | UTF-8 | 1,014 | 2.640625 | 3 | [] | no_license | #include <SDL2/SDL.h>
#include <SDL2/SDL2_gfxPrimitives.h>
#include <iostream>
#include "helpers.h"
const int WIDTH = 1280;
const int HEIGHT = 720;
SDL_Window* WINDOW;
SDL_Renderer* RENDERER;
void loop();
int main(int argc, char* args[])
{
if (init(WINDOW, RENDERER, "Coding Math - Ep. 2", WIDTH, HEIGHT))
{
loop();
}
close(WINDOW);
return 0;
}
void loop()
{
bool quit = false;
SDL_Event e;
double angle;
int x;
int y;
while (!quit)
{
while (SDL_PollEvent(&e) != 0)
{
quit = is_quit(e);
}
SDL_SetRenderDrawColor(RENDERER, 0x33, 0x33, 0x33, 0xff);
SDL_RenderClear(RENDERER);
angle = 0.00;
while (angle < (3.14 * 2))
{
x = angle * 200;
y = (sin(angle) * 200) + (HEIGHT / 2);
rectangleColor(RENDERER, x, y, x + 5, y + 5, 0xff0000ff);
angle += 0.01;
}
SDL_RenderPresent(RENDERER);
SDL_Delay(15);
}
}
| true |
da903e9a77421c9cad78e7e2488b2cc66ade023f | C++ | RaoulMarz/ImagePipeline | /src/stringframework.cpp | UTF-8 | 1,751 | 2.96875 | 3 | [] | no_license | #include <boost/tokenizer.hpp>
#include <iostream>
#include <memory>
#include <vector>
#include <string>
#include <sstream>
#include "stringframework.h"
using namespace std;
std::unique_ptr<std::vector<std::string>> stringframework::getTokensOnDelimiter(std::string input, std::string delimiter) {
std::unique_ptr<std::vector<std::string>> result = make_unique<std::vector<std::string>>();
typedef boost::tokenizer<boost::char_separator<char>> tokenizer;
boost::char_separator<char> sep{/*" "*/delimiter.c_str()};
tokenizer tok{input, sep};
stringstream ss;
for (const auto &t : tok) {
ss.clear();
ss << t;
string strtokenout;
ss >> strtokenout;
result->push_back(strtokenout);
//std::cout << t << '\n';
}
return result;
}
std::string stringframework::replacetextinwords(std::string input, std::string delimiter, std::string matchpattern, std::string replacepattern) {
std::string res = input;
if ( (input.length() > 0) && (matchpattern.length() > 0) ) {
std::unique_ptr<std::vector<std::string>> wordComponents = stringframework::getTokensOnDelimiter(input, delimiter);
if (wordComponents != nullptr) {
for (auto& wordx : *wordComponents) {
//optional<string> replacevalue = replaceText(wordx, matchpattern, replacepattern);
}
}
}
return res;
}
int stringframework::matchStringInVector(std::string input, std::vector<std::string>& matchlist, int offset) {
int res = -1;
if ( (offset >= 0) && (matchlist.size() > 0) ) {
int idxrun = 0;
for (auto& item : matchlist) {
if (input.compare(item) == 0)
return idxrun + offset;
idxrun++;
}
}
}
| true |
a17be03ba54aea4c183faf0c3d03e85b9914cf3f | C++ | dubshfjh/LeetCode | /37.cpp | UTF-8 | 5,847 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
using namespace std;
//采用回溯法,结合36中的行访问数组,列已访问数组和9宫格已访问数组
class Solution {
public:
vector<vector<char>> temp_board;
void solveSudoku(vector<vector<char>>& board) {
int row,col,num,size_1,size_2,board_num,total_board;
size_1=board.size();
size_2=board[0].size();
vector<int> temp(10,0);
vector<vector<int>> row_visit(size_1,temp);
vector<vector<int>> col_visit(size_2,temp);
total_board=(size_1/3*size_2/3);//3行3列:1个;3行6列:2个;6行3列:2个....
vector<vector<int>> board_visit(total_board,temp);
for(row=0;row<size_1;row++){
for(col=0;col<size_2;col++){
if(board[row][col]>='0' && board[row][col]<='9'){
num=board[row][col]-'0';
row_visit[row][num]=1;
col_visit[col][num]=1;
board_num=(row/3*size_2/3)+col/3;
board_visit[board_num][num]=1;
}
}
}
fillboard(0,0,board,row_visit,col_visit,board_visit);
board.clear();//清洗原棋盘,这很重要
for(int i=0;i<temp_board.size();i++){
board.push_back(temp_board[i]);
}
//board.assign(temp_board.begin(),temp_board.end());
}
void fillboard(int row,int col,vector<vector<char>>& board,vector<vector<int>>& row_visit,vector<vector<int>>& col_visit,vector<vector<int>>& board_visit){
int size_1,size_2;
vector<int> valid;
size_1=board.size();
size_2=board[0].size();
//cout<<row<<",,,"<<col<<endl;
if(row==size_1&&col==0){//当递归运行到第row+1行第0列时,递归终止,记录当前棋盘
temp_board.clear();
for(int i=0;i<size_1;i++){
temp_board.push_back(board[i]);
for(int j=0;j<size_2;j++){
cout<<board[i][j];
}
cout<<endl;
}
return;
}
if(board[row][col]=='.'){//只对当前尚未填数字的空格分析
valid=valid_num(row,col,board,row_visit,col_visit,board_visit);//获取当前空格的可填数
if(valid.size()>0){
for(int i=0;i<valid.size();i++){
board[row][col]=valid[i]+'0';
//cout<<board[row][col]<<endl;
if(col==size_2-1){//如果为本行的最后一个格子,则下次填写第row+1行的第0个格子
fillboard(row+1,0,board,row_visit,col_visit,board_visit);
}
else{//无需换到下一行时,直接填写第col+1个格子
fillboard(row,col+1,board,row_visit,col_visit,board_visit);
}
}
board[row][col]='.';//回溯到上一个格子时,将当前格子的数字重置为空
return;
}
else{//如果本格子无可填数,则直接回溯!!!
//cout<<"lalalalalalalalalalallllllllllllllllllllll"<<endl;
return;
}
}
else if(board[row][col]>='0'&&board[row][col]<='9'){//如果当前格子并不为空(即初始board在本格子已经填写了数字),则直接填写下一个格子
if(col==size_2-1){//之前脑残了,根本没对非空格字分析,直接GG
fillboard(row+1,0,board,row_visit,col_visit,board_visit);
}
else{
fillboard(row,col+1,board,row_visit,col_visit,board_visit);
}
}
}
vector<int> valid_num(int row,int col,vector<vector<char>>& board,vector<vector<int>>& row_visit,vector<vector<int>>& col_visit,vector<vector<int>>& board_visit){
int i,j,num,size_1,size_2,board_num,row_limit,col_limit;
vector<int> res;
//cout<<row<<",,,"<<col<<endl;
size_1=board.size();
size_2=board[0].size();
board_num=(row/3)*(size_2/3)+col/3;
//cout<<board_num<<endl;
vector<int> temp(10,0);//因为每次分析同一个格子的可填数时,在它之前的格子中的数字是动态变化的,
//所以每次都需要更新行已访问数字、列已访问数字和9宫格已访问数字
//直接row_visit[row]=temp也行
row_visit[row].assign(temp.begin(),temp.end());
col_visit[col].assign(temp.begin(),temp.end());
board_visit[board_num].assign(temp.begin(),temp.end());
for(i=0;i<size_2;i++){//更新第row行的访问数据
if(board[row][i]>='0' && board[row][i]<='9'){
num=board[row][i]-'0';
row_visit[row][num]=1;
}
}
// for(i=0;i<row_visit[row].size();i++){
// if(!row_visit[row][i]){
// cout<<i<<"..row..";
// }
// }
// cout<<endl;
for(i=0;i<size_1;i++){//更新第col列的访问数据
if(board[i][col]>='0' && board[i][col]<='9'){
num=board[i][col]-'0';
col_visit[col][num]=1;
}
}
// for(i=0;i<col_visit[col].size();i++){
// if(!col_visit[col][i]){
// cout<<i<<"..col..";
// }
// }
// cout<<endl;
row_limit=(row/3)*3;//当前9宫格行范围:row_limit -- row_limit+2
col_limit=(col/3)*3;//当前9宫格列范围:col_limit -- col_limit+2
for(i=row_limit;i<row_limit+3;i++){//更新board[row][col]所属九宫格的访问数据
for(j=col_limit;j<col_limit+3;j++){
if(board[i][j]>='0' && board[i][j]<='9'){
num=board[i][j]-'0';
board_visit[board_num][num]=1;
}
}
}
// for(i=0;i<board_visit[board_num].size();i++){
// if(!board_visit[board_num][i]){
// cout<<i<<",,,";
// }
// }
// cout<<endl;
for(int i=1;i<=9;i++){
if(!row_visit[row][i] && !col_visit[col][i] &&!board_visit[board_num][i]){
//cout<<i;
res.push_back(i);
}
}
//cout<<endl;
return res;
}
}; | true |
0c11947796767328182faa06f854c9705f3013d2 | C++ | Striz-lab/c-3sem | /12/1.cpp | UTF-8 | 1,635 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <set>
using namespace std;
bool is_DAG(int node_index, const vector<set<int>> &graph, vector<bool> used){
used[node_index] = true;
for (auto i : graph[node_index]){
if (used[i])
return false;
bool check = is_DAG(i, graph, used);
if (!check) return false;
}
return true;
}
void dfs(int node_index, vector<set<int>> graph, vector<bool> &used, vector<int> &ans){
used[node_index] = true;
for (auto i : graph[node_index])
if (!used[i]) dfs(i, graph, used, ans);
ans.push_back (node_index);
}
void topological_sort(vector<set<int>> graph, vector<bool> &used, vector<int> &ans){
for (int i = 0; i < used.size(); i++)
used[i] = false;
ans.clear();
for (int i = 0; i < graph.size(); i++){
if (!used[i])
dfs(i, graph, used, ans);
}
for (int i = 0; i < graph.size(); i ++)
cout << ans[graph.size() - 1 - i] << " ";
}
int main(){
int n, m;
cin >> n >> m;
vector<set<int>> graph (n);
for (int i = 0; i < n; i++) graph[i] = {};
vector<bool> used (n, false);
int a, b;
for (int i = 0; i < m; i++){
cin >> a >> b;
graph[a].insert(b);
}
bool is_it_Dag = true;
for (int i = 0; i < n; i++){
if (is_DAG(i, graph, used) == false){
is_it_Dag = false;
break;
}
}
vector<int> ans;
if (is_it_Dag == false)
cout << "NO";
else
topological_sort(graph, used, ans);
return 0;
}
| true |
7a8bdfa61be36d8864822a2a5f312d79827d3479 | C++ | drakesargent/Cpp-samples | /Programming II/CISS242_ADE_7.1/CISS242_ADE_7.1/mainProgram.cpp | UTF-8 | 1,281 | 3.71875 | 4 | [] | no_license | #include <iostream>
#include <iomanip>
#include "Payroll.h"
using namespace std;
//using a constant for the number of employee payroll objects
const int numEmps = 7;
int main()
{
//declare payroll array with constant
Payroll employees[numEmps];
//loop through the employee array
for (int i = 0; i < numEmps; i++)
{
//declare hours variable
double hours;
//set payrate
employees[i].setHourlyPayRate(7.59);
//request number of hours from user
cout << "Enter the number of hours worked for Employee " << i + 1 << ": ";
cin >> hours;
//validate that hours entered are <= 60
bool valid = false;
while (!valid)
{
if (hours > 60)
{
cout << "Hours invalid. Enter a value <60 : " << endl;
cin >> hours;
}
else
{
valid = true;
}
}
//set hours worked
employees[i].setHoursWorked(hours);
//set gross pay
employees[i].calcGrossPay(hours, employees[i].getHoursWorked());
}
cout << endl;
//loop through each employee
for (int i = 0; i < numEmps; i++)
{
//print out the amount earned gross this week
cout << "Employee " << i + 1 << " has earned $";
cout << fixed << setprecision(2) << showpoint << employees[i].getGrossPay();
cout << " gross for this week." << endl;
}
system("pause");
return 0;
}
| true |
69207de2a46c672f524c90107ef97feb1539aaf8 | C++ | pieisland/BaekJoon | /cpp/dp/9252. LCS2*(210104).cpp | UTF-8 | 1,746 | 3.21875 | 3 | [] | no_license | #include<cstdio>
#include<stdio.h>
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<cstring>
#include<queue>
using namespace std;
/*
이 문제는 책을 보고 풀었다.
인덱스가 너무 헷갈리는 부부인 것 같다.
이전 값을 비교하기 위해 -1을 쓰기 때문에
lcs는 1부터 시작하지만
string 값은 0부터 시작하니까 -1 뺴주면서 하는 식.
lcs 마지막 값이 lcs의 길이가 되고
출력을 하기 위해서는 lcs에 저장된 값을 탐색하면서
인덱스 값 바꾸면서 확인해나간다.
이런 비슷한 문제가.. 어디 더 있을텐데.
*/
string s1, s2;
int lcs[1001][1001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> s1;
cin >> s2;
int n = s1.length();
int m = s2.length();
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
//인덱스가 서로 달라서 헷갈리지요....
if (s1[i - 1] == s2[j - 1]) {
lcs[i][j] = lcs[i - 1][j - 1] + 1;
}
else {
lcs[i][j] = max(lcs[i - 1][j], lcs[i][j - 1]);
}
}
}
int lcslen = lcs[n][m];
cout << lcslen << '\n';
int i = n, j = m;
int len = lcslen;
vector<char> ans;
//lcs 배열은 이동 방향을 정해줄 뿐
//확인 하는 건 문자열에서 확인하면 됩니다.
while (i > 0 && j > 0) {
if (s1[i-1]==s2[j-1]) {
//cout << s1[i - 1];
ans.push_back(s1[i - 1]);//둘 중 뭘 넣어도 상관 없지.
i -= 1;
j -= 1;
len -= 1;
}
else {
//더 큰 부분으로 이동..
if (lcs[i - 1][j] > lcs[i][j - 1])
i -= 1;
else
j -= 1;
}
}
//반대로 출력해주면 된다.
for (int i = 0; i < lcslen; i++) {
cout << ans[lcslen - 1 - i];
}
cout << endl;
return 0;
}
| true |
5fb3232fb4f5897653eeca601ee4605c6be6dd11 | C++ | LiineKasak/AlgoLab2020 | /09-advanced-flows/potw-fleetrace.cpp | UTF-8 | 3,627 | 3.03125 | 3 | [] | no_license | /*
Finding the maximum sum of spactacle coefficients on a pair selection, given
coefficents for each pair. The tricky part is that we do not necessarily have
to have maximum matching, just maximize the coefficents.
Implementation: max flow min cost.
Initial solution was with binary search on the number on pairs (max flow size),
trying to find the maximal sum of coefficents (min cost).
However, we can assure that we get the best cost by adding an extra edge from
all boats to the sink with 0 coefficent (max cost 50). This way we always have
the same max flow and find the min cost with just one flow graph.
*/
#include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/successive_shortest_path_nonnegative_weights.hpp>
#include <boost/graph/find_flow_cost.hpp>
typedef boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> traits;
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property,
boost::property<boost::edge_capacity_t, long,
boost::property<boost::edge_residual_capacity_t, long,
boost::property<boost::edge_reverse_t, traits::edge_descriptor,
boost::property <boost::edge_weight_t, long>>>>> graph;
typedef boost::graph_traits<graph>::edge_descriptor edge_desc;
typedef boost::graph_traits<graph>::out_edge_iterator out_edge_it;
using namespace std;
class edge_adder {
graph &G;
public:
explicit edge_adder(graph &G) : G(G) {}
void add_edge(int from, int to, long capacity, long cost) {
auto c_map = boost::get(boost::edge_capacity, G);
auto r_map = boost::get(boost::edge_reverse, G);
auto w_map = boost::get(boost::edge_weight, G);
const edge_desc e = boost::add_edge(from, to, G).first;
const edge_desc rev_e = boost::add_edge(to, from, G).first;
c_map[e] = capacity;
c_map[rev_e] = 0; // reverse edge has no capacity!
r_map[e] = rev_e;
r_map[rev_e] = e;
w_map[e] = cost;
w_map[rev_e] = -cost;
}
};
void solve() {
int nr_boats, nr_sailors, nr_pairs;
cin >> nr_boats >> nr_sailors >> nr_pairs;
// vertex indices
int source = 0, sink = nr_boats + nr_sailors + 1;
auto boat_v = [](int i) { return i + 1; };
auto sailor_v = [&](int i) { return nr_boats + i + 1; };
graph G(nr_boats + nr_sailors + 2);
edge_adder adder(G);
for (int i = 0; i < nr_boats; i++) {
adder.add_edge(source, boat_v(i), 1, 0);
// NB! extra edge from every boat to sink
// to avoid binary search on the flow size
// give the highest cost so will be only used if necessary
adder.add_edge(boat_v(i), sink, 1, 50);
}
for (int i = 0; i < nr_sailors; i++) adder.add_edge(sailor_v(i), sink, 1, 0);
for (int i = 0; i < nr_pairs; i++) {
int boat, sailor, coefficient;
cin >> boat >> sailor >> coefficient;
// max coefficient is 50 and goal is to max, but use min cost
int cost = 50 - coefficient;
adder.add_edge(boat_v(boat), sailor_v(sailor), 1, cost);
}
// calculate cost
boost::successive_shortest_path_nonnegative_weights(G, source, sink);
int cost = boost::find_flow_cost(G);
// calculate flow
auto c_map = boost::get(boost::edge_capacity, G);
auto rc_map = boost::get(boost::edge_residual_capacity, G);
int flow = 0;
out_edge_it e, eend;
for (boost::tie(e, eend) = boost::out_edges(boost::vertex(source, G), G);
e != eend; ++e)
flow += c_map[*e] - rc_map[*e];
int real_cost = flow * 50 - cost;
cout << real_cost << endl;
}
int main() {
ios_base::sync_with_stdio(false);
int t;
cin >> t;
while (t--) solve();
return 0;
} | true |
5b9445ed7c55a7b7bc8a3ce0743406a3350defeb | C++ | rv404674/CPcodes | /spoj/bfs/primepath.cpp | UTF-8 | 1,520 | 3 | 3 | [] | no_license | ///important question to do on bfs
//http://spoj-solutions.blogspot.in/2014/08/ppath-prime-path.html
#include<iostream>
#include<queue>
#include<string.h>
using namespace std;
bool prime[10009];
//true indicates not prime
void segsieve(){
memset(prime,false,sizeof(prime));
int i;
for(i=2;i*i<=10009;i++)
{
if(!prime[i])
for(int j=i*i;j<=10009;j+=i)
prime[j]=true;
}
}
int contonum(int *a){
int sum=0;
for(int i=0;i<4;i++)
sum=sum*10+a[i];
return sum;
}
void contoarr(int x,int *a){
int k;
k=3;
while(x){
a[k--]=x%10;
x/=10;
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
segsieve();
int t,x,y,num,i,j,n,a[4];
int dist[10009];
cin>>t;
while(t--){
cin>>x>>y;
memset(dist,-1,sizeof(dist));
dist[x]=0;
queue <int> q;
q.push(x);
while(!q.empty()){
num=q.front();
q.pop();
for(i=3;i>=0;i--)
{
contoarr(num,a);
for(j=0;j<=9;j++)
{
a[i]=j;
n=contonum(a);
if(!prime[n] && dist[n]==-1 && n>=1000){
dist[n]=dist[num]+1;
q.push(n);}
}
}
}
/// use these form of comments
dist[y]==-1?cout<<"Impossible\n":cout<<dist[y]<<endl;
}
return 0;
}
| true |
96af97cbc80777d56a5d7ae9deea31dcb0769358 | C++ | mojoe12/UVa | /haybales.cpp | UTF-8 | 1,872 | 3.015625 | 3 | [] | no_license | /*#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <map>
/*
ID: josephh2
PROG: haybales
LANG: C++11
using namespace std;
int main(int argc, char *argv[]) {
ifstream fin ("haybales.in"); ofstream fout ("haybales.out");
int n, q;
fin >> n >> q;
vector<int> hays (n);
for (int i = 0; i < n; i++) {
fin >> hays[i];
}
sort(hays.begin(), hays.end());
const int counter = 50;
map<int, double> positions;
int previous = 0;
for (int i = 0; i < n; i++) {
for (int j = previous; i > 0 && j < hays[i]; j += counter) {
positions.insert(pair<int, double> (j, i - .5));
}
positions.insert(pair<int, double> (hays[i], i));
previous = 1 + hays[i];
}
for (int i = 0; i < q; i++) {
int a, b;
fin >> a >> b;
int lowindex = 0;
if (a < hays[0]) lowindex = 0;
else if (a > hays[n-1]) lowindex = n;
else {
for (int j = 0; j <= counter; j++) {
if (positions.count(a-j)) {
lowindex = ceil(positions[a-j]);
break;
}
}
}
int highindex = 0;
if (b < hays[0]) highindex = -1;
else if (b > hays[n-1]) highindex = n-1;
else {
for (int j = 0; j <= counter; j++) {
if (positions.count(b+j)) {
highindex = floor(positions[b+j]);
break;
}
}
}
fout << 1 + highindex - lowindex << endl;
}
}*/
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
/*
ID: josephh2
PROG: haybales
LANG: C++11
*/
using namespace std;
int main() {
ifstream fin ("haybales.in"); ofstream fout ("haybales.out");
int n, q;
fin >> n >> q;
vector<int> hays (n);
for (int i = 0; i < n; i++) fin >> hays[i];
sort(hays.begin(), hays.end());
for (int i = 0; i < q; i++) {
int a, b;
fin >> a >> b;
int num = 0;
for (int j = 0; j < n; j++) {
if (hays[j] > b) break;
if (hays[j] >= a) num++;
}
fout << num << endl;
}
} | true |
ec52bebc4d8afc8d441a20ab99b7ecad7ae1623c | C++ | hongquan/MVerbiste | /gui/conjugation.h | UTF-8 | 5,048 | 2.59375 | 3 | [] | no_license | /* $Id: conjugation.h,v 1.12 2011/01/08 19:07:36 sarrazip Exp $
conjugation.h - Generic conjugation interface
verbiste - French conjugation system
Copyright (C) 2003-2006 Pierre Sarrazin <http://sarrazip.com/>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.
*/
#ifndef _H_conjugation
#define _H_conjugation
#include <verbiste/FrenchVerbDictionary.h>
#include <vector>
#include <string>
#include <QtCore/QVector>
#include <QtCore/QString>
typedef std::vector<std::string> VS;
typedef std::vector<VS> VVS;
typedef std::vector<VVS> VVVS;
#ifndef QT_NO_DEBUG
#include <QtCore/QElapsedTimer>
#include <QtCore/QDebug>
#endif
/** Obtains the conjugation of the given infinitive.
@param fvd verb dictionary from which to obtain
the conjugation
@param infinitive UTF-8 string containing the infinitive form
of the verb to conjugate (e.g., "manger")
@param tname conjugation template name to use (e.g., "aim:er")
@param dest structure into which the conjugated is written
@param includePronouns put pronouns before conjugated verbs in the
modes where pronouns are used
*/
void getConjugation(const verbiste::FrenchVerbDictionary &fvd,
const std::string &infinitive,
const std::string &tname,
VVVS &dest,
bool includePronouns = false);
/** Get the tense name for a certain cell of the conjugation table.
The conjugation table is a 4x4 grid and 11 of the 16 cells are
used by the tenses to be displayed.
@param row row number (0..3)
@param col column number (0..3)
@param isItalian language used (true for Italian, false for French)
@returns an internationalized (and possibly abbreviated) name
(in UTF-8) for the tense that goes in the cell
designated by row and col;
the returned string is empty if no tense (in the
language used) goes in the designated cell
*/
std::string getTenseNameForTableCell(int row, int col, bool isItalian);
/** Composes the text of the conjugation in a certain tense.
The words of this conjugation that match a certain user text
are marked specially.
@param tense structure that represents a certain
tense of a certain verb
@param lowerCaseUTF8UserText conjugated verb as entered by the
user, but converted to lower-case,
and assumed to be in UTF-8
@param openMark ASCII string to be used before verbs
that match lowerCaseUTF8UserText
(e.g., "<b>")
@param closeMark ASCII string to be used after verbs
that match lowerCaseUTF8UserText
(e.g., "</b>")
@returns a UTF-8 string containing several
lines of text, each line being
separated by a newline ('\n')
character; the string does not end
the last line with a newline however;
e.g., "aie\nayons\nayez"
*/
std::string createTableCellText(verbiste::FrenchVerbDictionary &fvd,
const VVS &tense,
const std::string &lowerCaseUTF8UserText,
const std::string &openMark,
const std::string &closeMark);
/**
* Qt version of createTableCellText() above.
* Return a vertor of QStrings, which are conjugations.
**/
QVector<QString> qgetConjugates(verbiste::FrenchVerbDictionary &fvd,
const VVS &tense,
const std::string &lowerCaseUTF8UserText,
const std::string &openMark,
const std::string &closeMark);
#endif /* _H_conjugation */
| true |
db9e7cda20916bef51a555409a79100ba176d9cc | C++ | agul/contest-tasks | /TCO20_1B_medium.cpp | UTF-8 | 1,228 | 2.875 | 3 | [] | no_license | #include "base/header.hpp"
class EllysWhatDidYouGet {
public:
int getCount(int N) {
sums = std::vector<int>(300000, 0);
for (int i = 0; i < sums.size(); ++i) {
int cur = i;
int sum = 0;
while (cur > 0) {
sum += cur % 10;
cur /= 10;
}
sums[i] = sum;
}
int ans = 0;
for (int x = 1; x <= 50; ++x) {
for (int y = 1; y <= 50; ++y) {
for (int z = 1; z <= 50; ++z) {
int cur_ans = -1;
bool ok = true;
bool first = true;
for (int i = 1; i <= N; ++i) {
int cur = (i * x + y) * z;
if (first) {
cur_ans = sums[cur];
first = false;
}
ok &= (cur_ans == sums[cur]);
}
if (ok) {
++ans;
}
}
}
}
return ans;
}
std::vector<int> sums;
};
class TCO20_1B_medium {
public:
void solve(std::istream& in, std::ostream& out) {
// out << "Case #" << ++test_id_ << ": ";
int n;
in >> n;
EllysWhatDidYouGet solution;
out << solution.getCount(n) << std::endl;
}
bool check(std::string input, std::string expected_output, std::string actual_output) {
return true;
}
static constexpr size_t kGeneratedTestsCount = 0;
static void generate_test(std::ostream& test) {}
private:
size_t test_id_ = 0;
};
| true |
68dd5252bcc4b893522c71e268b405538a521a97 | C++ | xopoww/raytrace | /src/body.cpp | UTF-8 | 864 | 3 | 3 | [] | no_license | #include "body.hpp"
#include <cmath>
Sphere::Sphere(const coord_t _radius, const Vector3 &_center):
radius(_radius), center(_center)
{}
std::pair<Ray, Ray> Sphere::intersect(const Ray &ray) const
{
coord_t
a = std::pow(ray.direction.length(), 2),
b = 2 * (ray.origin - this->center).dot(ray.direction),
c = std::pow((ray.origin - this->center).length(), 2) - std::pow(this->radius, 2);
auto roots = solve_quadratic(a, b, c);
Vector3 i1 = ray.advance(roots.first), i2 = ray.advance(roots.second);
return {
{i1, i1 - this->center},
{i2, this->center - i2}
};
}
bool Sphere::is_in(const Vector3 &point) const
{
return (point - this->center).length() <= this->radius;
}
Body::Body(std::shared_ptr<Object> _obj, std::shared_ptr<Material> _material):
obj(_obj), material(_material)
{}
| true |
5e77924f063b1b979a6e105576f0fc134edcabcc | C++ | janadr/FYS3150 | /prosjekt3/kode/extractData.cpp | UTF-8 | 585 | 2.625 | 3 | [] | no_license | #include "extractData.hpp"
// denne funksjonen henter ut initielle verdier fra body051018.dat fra NASA
Planet extract(string filename, int i){
ifstream inf(filename);
for (int j=0; j<i; ++j){
string strInput;
getline(inf, strInput);
}
string name, mass, x, y, z, vx, vy, vz;
inf >> name; inf >> mass;
inf >> x; inf >> y; inf >> z,
inf >> vx; inf >> vy; inf >> vz;
Coordinate initPos(stod(x),stod(y),stod(z));
Coordinate initVel(stod(vx),stod(vy),stod(vz));
Planet planet(name, stod(mass)/2e30, initPos, initVel*365.25);
inf.close();
return planet;
}
| true |
3878939428a13feec7bdc847d0f5b66dea863d1e | C++ | nwni/ioform | /main.cpp | UTF-8 | 4,586 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include <cmath>
using namespace std;
class cFormulas
{
public:
// float Sumatoria(float l, float m, float s)
// {
// float lam = l;
// float mi = m;
// float ser = s;
//
// float sum = 0, PO=0;
//
// for(int n = 0; n <= ser-1; n++)
// {
// sum = sum + (pow((lam/mi),n)/1);
// }
//
// PO = 1/(sum+(pow((lam/mi),ser)/2)*((1/(1-(lam/(ser*mi))))));
// cout<<"PO: "<<PO<<endl;
// }
float FPo(float l, float m, int s)
{
float lam = l;
float mi = m;
int ser = s;
float sum = 0, PO=0;
for(int loop = 0; loop <= ser-1; loop++)
{
//cout<<"*****VALOR SUM: "<<sum<<"****VALOR LOOP: "<<loop<<endl;
sum = sum + ((pow((lam/mi),loop))/(Factorial(loop)));
cout<<"*****VALOR SUM: "<<sum<<"****VALOR LOOP: "<<loop<<"///POW FUN: "<<pow((lam/mi),loop)<<endl;
}
PO = 1/(sum+((pow((lam/mi),ser)/Factorial(ser))*((1/(1-(lam/(ser*mi)))))));
cout<<"PO: "<<PO<<endl;
return PO;
}
int Factorial(int num)
{
int numC = num;
if(numC == 0)
{
return 1;
}
else if(numC == 1)
{
return 1;
}
else
{
return numC * Factorial(numC - 1);
}
}
float FLS(float l, float m, float s, float vPO)
{
float lam = l;
float mi = m;
float serv = s;
float Po = vPO;
float LS = 0;
LS = ((lam * mi * (pow((lam/mi), serv)) * Po) / ((Factorial(serv - 1)) * (pow(((serv * mi) - lam), 2)))) + (lam/mi);
cout<<LS<<endl;
return LS;
}
float FWS(float ls, float l)
{
float vls = ls;
float lam = l;
float WS = 0;
WS = (vls/lam);
cout<<WS<<endl;
return WS;
}
float FLq(float l, float m, float s, float po)
{
float lam = l;
float mi = m;
float serv = s;
float vPo = po;
float LQ = 0;
LQ = vPo * ((pow((lam/mi), (serv + 1))) / (Factorial((serv - 1)) * (pow((serv - (lam/mi)), 2))));
cout<<LQ<<endl;
return LQ;
}
float FWq(float lq, float l)
{
float Lq = lq;
float lam = l;
float Wq = 0;
Wq = (Lq/lam);
cout<<Wq<<endl;
return Wq;
}
float FCT(float lq, float cw, float s, float cs)
{
float Lq = lq;
float Cw = cw;
float serv = s;
float Cs = cs;
float CT = 0;
CT = (Lq * Cw) + (serv * Cs);
cout<<CT<<endl;
return CT;
}
};
int main()
{
cFormulas obj;
float l, m, vPO, ls, Lq, Wq, Cw, Cs;
int opcSw, opc, s;
do
{
cout<<"IO Unidad 4."<<endl;
cout<<" 1.- Probabilidad de que ningun cliente se encuentre en el Sistema(PO)"<<endl;
cout<<" 2.- Numero promedio de Unidades en el Sistema(LS)."<<endl;
cout<<" 3.- Tiempo promedio en el que una unidad este dentro del sistema(WS)"<<endl;
cout<<" 4.- Numero de Clientes en la Fila(Lq)"<<endl;
cout<<" 5.- Tiempo de Espera en la Fila(Wq)"<<endl;
cout<<" 6.- Costo Total(CT)"<<endl;
cout<<" Opcion Deseada: ";
cin>>opcSw;
switch(opcSw)
{
case 1:
cout << "Po" << endl;
cout<<"Valor de 'Lambda': ";
cin>>l;
cout<<"Valor de 'M': ";
cin>>m;
cout<<"Cantidad de Servidores: ";
cin>>s;
vPO = obj.FPo(l, m, s);
//obj.Factorial(s);
break;
case 2:
cout<<"Calcular LS"<<endl;
ls = obj.FLS(l, m, s, vPO);
break;
case 3:
cout<<"WS"<<endl;
obj.FWS(ls, l);
break;
case 4:
cout<<"Lq"<<endl;
Lq = obj.FLq(l, m, s, vPO);
break;
case 5:
cout<<"Wq"<<endl;
obj.FWq(Lq, l);
break;
case 6:
cout<<"Ingrese el Valor de Cw: ";
cin>> Cw;
cout<<"Ingrese el Valor de Cs: ";
cin>>Cs;
obj.FCT(Lq, Cw, s, Cs);
break;
default:
break;
}
cout<<"Desea Continuar? 1/2: ";
cin>>opc;
}while(opc != 2);
return 0;
}
| true |
badf39998ff76cc42f7e4430a494e5ff32b4c1ed | C++ | KimSeungJu/ClassDesign | /Chapter12_15/Chapter12_15/Person.cpp | UHC | 297 | 3.453125 | 3 | [] | no_license | #include "Person.h"
Person::Person()
{
name = "";
age = 0;
gender = true;
}
Person::Person(string n, int a, bool g)
{
name = n;
age = a;
gender = g;
}
void Person::Print()
{
cout << "̸ : " << name <<endl;
cout << " : " << age << endl;
cout << " : " << gender << endl;
}
| true |
46e8a36913ad4840a1005eedb7c6934611307f40 | C++ | LC-CPU/WordCount | /WordCount.cpp | UTF-8 | 1,016 | 2.78125 | 3 | [] | no_license | #define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NUM 1024
void fun1()
{
FILE* fp;
int total = 0;
if ((fp = fopen("test.txt", "r")) == NULL) {
perror("the file fail to read");
getchar();
exit(1);
}
while (getc(fp)!=EOF)
{
total++;
}
printf("字符数:%d", total);
fclose(fp);
}
void fun2()
{
char buf[MAX_NUM];
FILE* fp;
int len, total = 0;
if ((fp = fopen("test.txt", "r")) == NULL) {
perror("the file fail to read");
getchar();
exit(1);
}
while (!feof(fp) && !ferror(fp))
{
fgets(buf, MAX_NUM, fp);
len = strlen(buf);
for (int i = 0; i < len; i++)
{
if ((buf[i] == ' ' && buf[i + 1] != ' ') || (buf[i] == ',' && buf[i + 1] != ','))
{
total++;
}
}
}
printf("单词数:%d", total);
fclose(fp);
}
void fun(char a, char c)
{
if (a == '-' && c == 'c')
{
fun1();
}
else if (a == '-' && c == 'w')
{
fun2();
}
}
int main() {
char a, c;
scanf("%c %c", &a, &c);
fun(a, c);
return 0;
}
| true |
e89e784f252b64473ed965e9ad916240f18328ea | C++ | Royz2123/Navigation-Drone | /project/pid.cpp | UTF-8 | 377 | 2.71875 | 3 | [] | no_license | #include "pid.hpp"
float Pid::calc(){
return p*kp/500.0+i*ki/10000.0+d*kd/10000.0;
}
void Pid::update(float deltaTime,float delta){
//std::cout << "Delta =" << delta<< " | DeltaTime =" << deltaTime << std::endl;
p = delta;
i += deltaTime * (last+delta)/2;
d = (p-last)/deltaTime;
int maxI = 1000;
if (i > maxI) i = maxI;
else if (i < -maxI) i = -maxI;
last = p;
}
| true |
fcfe731b7b3fd4f7d5480218831101ae374e0a07 | C++ | woodw221/CS320_Assignment2 | /Tokenizer.hpp | UTF-8 | 233 | 2.546875 | 3 | [] | no_license | #include <string>
#include <vector>
#include <iostream>
class Tokenizer
{
private:
std::vector<std::string> tokenized;
int isTokInt(char *tok);
int isQuit(char *stop);
public:
std::vector<std::string>* GetTokens();
};
| true |
5e6a9413b947019695adb41c8cd1044e6f40886d | C++ | DenitsaS/UP-2016-2017 | /homework1task1/homeworktask1.cpp | UTF-8 | 590 | 3.46875 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
int main()
{
int a, b, c, d, e;
cout << "Enter five real numbers:\n";
cin >> a >> b >> c >> d >> e;
cout << "The biggest number is ";
if ((a >= b) && (a >= c) && (a >= d) && (a >= e) )
cout << a;
else if ( b >= a && b >= c && b >= d && b >= e)
cout << b;
else if ( c >= a && c >= b && c >= d && c >= e)
cout << c;
else if ( d >= a && d >= b && d >= e && d >= c)
cout << d;
else if ( e >= a && e >=b && e >= c && e >= d)
cout << e;
return 0;
}
| true |
f7b3d40376bac9291cada61f6496300c6de28f0c | C++ | liuli4016/pfSkel | /Normalize/normalize.cpp | UTF-8 | 2,968 | 2.875 | 3 | [] | no_license | #include "common.h"
bool NormalizeVolume(
unsigned char **vol, int *L, int *M, int *N, // original volume and dimension
int sphereDiameter = 100, // sphere enclosing the object after normalization
int boundingBoxDistance = 1 // distance from sphere to the bounding box
) {
int newL, newM, newN;
int newIdx, oldIdx, newSlSize, oldSlSize, oldSize;
int i, j, k;
int minX, minY, minZ, maxX, maxY, maxZ;
int crtDiam;
float ratio, invRatio;
unsigned char *newVol;
int dL, dM, dN;
newL = 0;
newM = 0;
newN = 0;
// find the actual extent of the object
if(!GetVolExtent(*vol, *L, *M, *N,
&minX, &maxX, &minY, &maxY, &minZ, &maxZ))
{
printf("Error: unable to get volume extent.\n");
return false;
}
// the diameter of the sphere currently enclosing the object is the biggest
// of the 3 extents
crtDiam = maxX - minX + 1;
if(crtDiam < (maxY - minY + 1)) {
crtDiam = maxY - minY + 1;
}
if(crtDiam < (maxZ - minZ + 1)) {
crtDiam = maxZ - minZ + 1;
}
// the ratio newDiameter / oldDiameter will be the scaling factor applied to
// the object
// scaling is applied uniformly in all 3 directions
ratio = (float) sphereDiameter / (float) crtDiam;
// compute the size of the new volume
newL = ((int)((maxX - minX + 1) * ratio)) +
boundingBoxDistance + boundingBoxDistance;
newM = ((int)((maxY - minY + 1) * ratio)) +
boundingBoxDistance + boundingBoxDistance;
newN = ((int)((maxZ - minZ + 1) * ratio)) +
boundingBoxDistance + boundingBoxDistance;
// allocate space for the new volume
if((newVol = new unsigned char[newL * newM * newN]) == NULL) {
printf("Normalize: error allocating memory for the new volume !");
return false;
}
memset(newVol, 0, newL * newM * newN);
// scan the new volume, inverse transform every voxel to the original volume
// and copy the value from the original
newSlSize = newL * newM;
oldSlSize = (*L)*(*M);
oldSize = (*L)*(*M)*(*N);
// inverse transform scale ratio
invRatio = 1.00 / ratio;
// newIdx = 0;
for(k = 0; k < (newN); k++) {
for(j = 0; j < (newM); j++) {
for(i = 0; i < (newL); i++) {
newIdx = k*newSlSize + j*newL + i;
oldIdx =
((((int)round((k-boundingBoxDistance)*invRatio))+minZ)*oldSlSize) +
((((int)round((j-boundingBoxDistance) * invRatio)) + minY) * (*L)) +
((((int)round((i-boundingBoxDistance) * invRatio)) + minX));
if((oldIdx < 0) || (oldIdx >= oldSize)) {
PrintErrorMessage("Normalize: index is out of bounds !");
}
else {
newVol[newIdx] = (*vol)[oldIdx];
}
}
}
}
// delete the old volume
delete [] (*vol);
// set vol to point to the new volume
(*vol) = newVol;
*L = newL;
*M = newM;
*N = newN;
// just to be safe, check the volume padding
if(!CheckVolumePadding(*vol, *L, *M, *N, boundingBoxDistance)) {
return PadVolume(vol, L, M, N, boundingBoxDistance,&dL, &dM, &dN);
}
return true;
}
| true |
403526b8818890ead874644fe15f0c1808f2f6b7 | C++ | ivankreso/random-forest | /random_forest/random_tree.h | UTF-8 | 3,088 | 2.765625 | 3 | [] | no_license | #ifndef RANDOM_TREE_H_
#define RANDOM_TREE_H_
#include <vector>
#include <memory>
#include <random>
#include "params.h"
#include "split.h"
#include "objective_function.h"
#include "forest_helper.h"
namespace forest {
struct Node {
Node(const DataBase& data, const std::vector<size_t>& sample_indices) {
samples = sample_indices;
depth = 0;
entropy = data.CalculateEntropy(samples);
}
Node(const DataBase& data, const std::shared_ptr<Node>& parent_node,
std::vector<size_t>& sample_indices) : parent(parent_node) {
samples = std::move(sample_indices);
depth = parent_node->depth + 1;
entropy = data.CalculateEntropy(samples);
}
inline
//void DeclareLeaf(const std::vector<size_t>& labels) {
void DeclareLeaf(const DataBase& data) {
is_leaf = true;
//UpdateClassDistribution(labels);
UpdateClassDistribution(data);
}
inline
//void UpdateClassDistribution(const DataBase& data, const std::vector<size_t>& labels) {
void UpdateClassDistribution(const DataBase& data) {
class_distribution = data.GetClassDistribution(samples);
}
SplitType Split(const DataBase& data, size_t sample) {
return splitter_->Split(data, sample);
}
//bool is_leaf() const {
// return is_leaf_;
//}
//std::vector<size_t>& samples() {
// return samples_;
//}
//private:
std::vector<size_t> samples;
std::weak_ptr<Node> parent;
std::shared_ptr<Node> left = nullptr;
std::shared_ptr<Node> right = nullptr;
// This function contains the feature filter
std::shared_ptr<SplitBase> splitter_;
// This value stores the threshold used for splitting
double entropy;
// Depth of the node
size_t depth;
bool is_leaf = false;
// Class distribution (we use them only in leaf nodes)
std::vector<double> class_distribution;
// This function contains the splitting criteria
//std::shared_ptr<SplitterBase> splitter_;
};
class RandomTree {
public:
//RandomTree(size_t tree_id, TreeParams& params, std::shared_ptr<SplitSamplerBase> split_sampler);
RandomTree(size_t tree_id, TreeParams& params, std::shared_ptr<SplitSamplerBase>& split_sampler);
//bool Grow();
bool Grow(const DataBase& data);
bool StopSplitting(const Node& node);
std::vector<double> Predict(const DataBase& data, size_t sample_num) const;
std::vector<std::shared_ptr<Node>> CollectLeafs() const {
return CollectSubtreeLeafs(root_);
}
std::vector<size_t> SampleTrainingSubset();
int tree_id() const {
return tree_id_;
}
private:
//void UpdateClassDistributions(const DataBase& data, const std::vector<size_t>& train_subset);
std::vector<std::shared_ptr<Node>> CollectSubtreeLeafs(
const std::shared_ptr<Node> subtree) const;
std::shared_ptr<Node> root_;
int tree_id_;
TreeParams params_;
//std::shared_ptr<SplitSamplerBase> split_sampler_;
std::shared_ptr<SplitSamplerBase>& split_sampler_;
//std::vector<double> class_distribution_full_;
//std::vector<double> class_distribution_subset_;
std::vector<size_t> train_subset_;
};
} // namespace forest
#endif // RANDOM_FOREST_H
| true |
a724dc0d9ef6370469543be594eb04d0c11f54ca | C++ | atifdelibasic/Algoritmi_i_strukture_podataka | /SelectionSort.cpp | UTF-8 | 539 | 3.046875 | 3 | [] | no_license | #include <iostream>
using namespace std;
void SelectionSort(int niz[], int n) {
for (int i = 0; i < n-1; i++)
{
int minI = i;
for (int j = i+1; j < n; j++)
{
if (niz[j] < niz[minI])
minI = j;
}
if (minI != i) {
swap(niz[minI], niz[i]);
}
}
}
void Ispis(int niz[], int n) {
for (int i = 0; i < n; i++)
{
cout << niz[i] << " ";
}
cout << endl;
}
void main() {
int niz[] = { 1,23,11,9,32,105,2 };
int vel = sizeof(niz) / sizeof(niz[0]);
SelectionSort(niz, vel);
Ispis(niz, vel);
system("pause>0");
} | true |
d3624662f833cdf87c7d85768fa31acd805ac3e9 | C++ | uesp/tes4lib | /common/obfile.h | UTF-8 | 6,002 | 2.96875 | 3 | [
"MIT"
] | permissive | /*===========================================================================
*
* File: ObFile.H
* Author: Dave Humphrey (uesp@sympatico.ca)
* Created On: April 5, 2006
*
* Contains the definition for the CObFile class, a very simple class
* encapsulating file access.
*
*=========================================================================*/
#ifndef __OBFILE_H
#define __OBFILE_H
/*===========================================================================
*
* Begin Required Includes
*
*=========================================================================*/
#include "sstring.h"
#include "oberrorhandler.h"
/*===========================================================================
* End of Required Includes
*=========================================================================*/
/*===========================================================================
*
* Begin Class CObFile Definition
*
* Encapsulates very basic file access operations (open, read, write).
* Other file classes will be derived from this.
*
*=========================================================================*/
class CObFile {
/*---------- Begin Protected Class Members --------------------*/
protected:
FILE* m_pFile; /* File handle for file operations */
CSString m_Filename; /* The currently open file */
dword m_LineCount; /* Used with ReadLine() */
/*---------- Begin Protected Class Methods --------------------*/
protected:
/*---------- Begin Public Class Methods -----------------------*/
public:
/* Class Constructors/Destructors */
CObFile();
virtual ~CObFile();
virtual void Destroy (void);
/* Clear file errors */
virtual void ClearErrors (void) { clearerr(m_pFile); }
/* Close a currently open file */
virtual void Close (void);
/* Get class members */
virtual const SSCHAR* GetFilename (void) const { return (m_Filename); }
/* Get the file size */
virtual bool GetFileSize (int& Size);
virtual bool GetFileSize64 (int64& Size);
virtual int GetFileSize (void);
virtual int64 GetFileSize64 (void);
/* Get class members */
virtual dword GetLineCount (void) { return (m_LineCount); }
/* Check class states */
virtual bool IsOpen (void) const;
virtual bool IsEOF (void) const { return (feof(m_pFile) != 0); }
virtual bool HasError (void) const { return (ferror(m_pFile) != 0); }
/* Attempt to open a file for input or output */
virtual bool Open (const SSCHAR* pFilename, const SSCHAR* pFileMode);
virtual bool Printf (const SSCHAR* pString, ...);
virtual bool VPrintf (const SSCHAR* pString, va_list Args);
/* Read a raw buffer of bytes */
virtual bool Read (void* pBuffer, const int Size);
virtual bool Read (void* pBuffer, const int Size, dword& InputBytes);
/* Input a line of text from a text file */
virtual bool ReadLine (CSString& Buffer);
/* Shortcut to reading basic types */
virtual bool ReadByte (byte& Value) { return Read(&Value, sizeof(byte)); }
virtual bool ReadWord (word& Value) { return Read(&Value, sizeof(word)); }
virtual bool ReadDWord (dword& Value) { return Read(&Value, sizeof(dword)); }
virtual bool ReadDWord64 (dword64& Value) { return Read(&Value, sizeof(dword64)); }
virtual bool ReadFloat (float& Value) { return Read(&Value, sizeof(float)); }
virtual bool ReadDouble (double& Value) { return Read(&Value, sizeof(double)); }
/* Set the file position from start of file */
virtual bool Seek (const int Offset);
virtual bool SeekCur (const int Offset);
virtual bool Seek64 (const int64 Offset);
/* Get the current file position */
virtual bool Tell (int& Offset);
virtual bool Tell64 (int64& Offset);
virtual int Tell (void) { return ftell(m_pFile); }
virtual int64 Tell64 (void);
/* Write a raw buffer of bytes */
virtual bool Write (const void* pBuffer, const int Size);
/* Shortcut to writing basic types */
virtual bool WriteByte (const byte Value) { return Write(&Value, sizeof(byte)); }
virtual bool WriteWord (const word Value) { return Write(&Value, sizeof(word)); }
virtual bool WriteDWord (const dword Value) { return Write(&Value, sizeof(dword)); }
virtual bool WriteDWord64 (const dword64 Value) { return Write(&Value, sizeof(dword64)); }
virtual bool WriteFloat (const float Value) { return Write(&Value, sizeof(float)); }
virtual bool WriteDouble (const double Value) { return Write(&Value, sizeof(double)); }
};
/*===========================================================================
* End of Class CObFile Definition
*=========================================================================*/
/*===========================================================================
*
* Begin File Related Functions
*
*=========================================================================*/
/* Checks is a file exists */
bool ObFileExists (const SSCHAR* pFilename);
/* Checks a file extension */
bool ObCheckExtension (const SSCHAR* pFilename, const SSCHAR* pExt);
bool MakePathEx (const SSCHAR* pPath);
SSCHAR* TerminatePath (SSCHAR* pPath);
const SSCHAR* TerminatePath (CSString& Path);
bool FileExists (const SSCHAR* pFilename);
int64 GetFileSize (const char* pFilename);
bool GetFileSize (int64& FileSize, const char* pFilename);
bool GetFileInfo (const char* pFilename, int64& Filesize, dword64& Filetime);
/*===========================================================================
* End of File Related Functions
*=========================================================================*/
#endif
/*===========================================================================
* End of File ObFile.H
*=========================================================================*/
| true |
e6d6e87c6a71cc8ca91e3d250957f14f4228882a | C++ | ShepherdZFJ/PAT_AdvancedLevel | /PAT/PATA1068.cpp | UTF-8 | 1,118 | 2.6875 | 3 | [] | no_license | /*
* @Author: MeiYing
* @Date: 2019-08-28 20:18:16
* @Last Modified by: MeiYing
* @Last Modified time: 2019-08-28 21:16:52
*/
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int n,m;
vector<int>v,ans,value;
bool flag;
void DFS(int index,int sum)
{
if(sum==m && ans.size()==0)
{
ans=v;
flag=true;
return;
}
if(index==n ||sum>m) return ;
if(!flag)
{
v.push_back(value[index]);
DFS(index+1,sum+value[index]);
v.pop_back();
DFS(index+1,sum);
}
}
int main()
{
int a;
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++)
{
scanf("%d",&a);
value.push_back(a);
}
sort(value.begin(),value.end());
DFS(0,0);
if(ans.size()==0)
{
printf("No Solution");
}
else
{
for(int i=0;i<ans.size();i++)
{
if(i<ans.size()-1)
{
printf("%d ",ans[i]);
}
else
{
printf("%d",ans[i]);
}
}
}
return 0;
} | true |
a88580024f824b5e76fdc139626593b9bba83142 | C++ | jaguar-paw33/CODE_AAI | /6.Data Structures/2.Stack/4.check_redundant_brackets.cpp | UTF-8 | 1,982 | 4.15625 | 4 | [] | no_license | /*
For a given expression in the form of a string, find if there exist any redundant brackets or not. It is given that the expression contains only rounded brackets or parenthesis and the input expression will always be balanced.
A pair of the bracket is said to be redundant when a sub-expression is surrounded by unnecessary or needless brackets.
Example:
Expression: (a+b)+c
Since there are no needless brackets, hence, the output must be 'false'.
Expression: ((a+b))
The expression can be reduced to (a+b). Hence the expression has redundant brackets and the output will be 'true'.
Note:
You will not get a partial score for this problem. You will get marks only if all the test cases are passed.
Input Format :
The first and the only line of input contains a string expression, without any spaces in between.
Output Format :
The first and the only line of output will print either 'true' or 'false'(without the quotes) denoting whether the input expression contains redundant brackets or not.
Note:
You are not required to print the expected result. It has already been taken care of.
Constraints:
0 <= N <= 10^6
Where N is the length of the expression.
Time Limit: 1 second
Sample Input 1:
a+(b)+c
Sample Output 1:
true
Explanation:
The expression can be reduced to a+b+c. Hence, the brackets are redundant.
Sample Input 2:
(a+b)
Sample Output 2:
false
*/
#include<bits/stdc++.h>
using namespace std;
bool check_redundant(string & s) {
stack<char> st;
for (int i = 0; i < s.size(); i++) {
if (s[i] >= 'a' && s[i] <= 'z')
continue;
if (!st.empty()) {
int count = 0;
if (s[i] == ')') {
while (!st.empty() && st.top() != '(') {
count++;
st.pop();
}
if (!st.empty())
st.pop();
if (!count)
return true;
} else {
st.push(s[i]);
}
} else {
st.push(s[i]);
}
}
return false;
}
int main() {
string s;
cin >> s;
cout << (check_redundant(s) ? "true" : "false") << endl;
return 0;
}
| true |
56a8af97d7a7ab645da15e581f295b18b3c47757 | C++ | Diegores14/CompetitiveProgramming | /ICPCArchive/4219 - Bora Bora/solution.cpp | UTF-8 | 2,855 | 2.625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
vector< pair<int, char> > deck(300);
pair<int, char> topmost;
vector<int> cards;
int var = 1, k = 0, turn = 0;
void rules(map< pair<int, char>, int > &hand) {
if(topmost.first == 12) {
var *= -1;
return;
}
if(topmost.first == 7) {
hand[deck[k++]]++;
hand[deck[k++]]++;
cards[turn] += 2;
turn += var;
return;
}
if(topmost.first == 1) {
hand[deck[k++]]++;
turn += var;
cards[turn]++;
return;
}
if(topmost.first == 11) {
turn += var;
return;
}
}
void sol(map < pair<int, char> , int> &hand) {
pair<int, char> temp = make_pair(-1, 'a');
for(int i=13; i>=0; i--) {
pair<int, char> aux = make_pair(i, topmost.second);
if(hand[aux] != 0) {
temp = aux;
break;
}
}
if( temp.first > topmost.first ) {
hand[temp]--;
cards[turn]--;
topmost = temp;
return;
}
for(char i: {'S', 'H', 'D', 'C'}) {
pair<int, char> aux = make_pair(topmost.first, i);
if(hand[aux] != 0) {
temp = aux;
break;
}
}
if(temp.first != -1) {
topmost = temp;
hand[temp]--;
cards[turn]--;
} else {
temp = deck[k++];
if(temp.first == topmost.first || temp.second == topmost.second) {
topmost = temp;
} else {
hand[temp]++;
cards[turn]++;
}
}
}
bool isEmpty(map < pair<int, char> , int> &hand ) {
for(auto &i: hand) {
if(i.second != 0) {
return false;
}
}
return true;
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(NULL);
int p, m, n;
while(cin >> p >> m >> n, p || n || m) {
k = 0; turn = 0, var = 1;
cards.assign(p, m);
map< pair<int, char>, int > hands[p];
for(int i=0; i<n; i++) {
cin >> deck[i].first >> deck[i].second;
}
for(int i=0; i<p; i++) {
for(int j=0; j<m; j++) {
hands[i][deck[k++]]++;
}
}
topmost = deck[k++];
while(true) {
if(turn < 0) {
turn += p;
}
rules(hands[turn]);
//cout << topmost.first << topmost.second << turn << ' ' << var << '\n';
if(turn < 0) {
turn += p;
}
turn %= p;
sol(hands[turn]);
//cout << topmost.first << topmost.second << turn << ' ' << var << '\n';
if(isEmpty(hands[turn])) {
cout << turn + 1 << '\n';
break;
}
turn = (turn + var + p)%p;
//cout << "turn " << turn << '\n';
}
}
return 0;
} | true |
510bce57e563bca3179cdadc1b430f86a4a8b3d7 | C++ | gik0geck0/WSNInterface | /echo_mote/hello_timer.ino | UTF-8 | 330 | 2.9375 | 3 | [
"MIT"
] | permissive |
void setup() {
Serial.begin(57600);
Serial.setTimeout(5);
}
char inbuf[1024];
void loop() {
// Wait for an incoming value, then send it back. Expected that everything ends in \r
int readin = Serial.readBytesUntil('\r', inbuf, 1024);
if (readin > 0) {
Serial.write((uint8_t*) inbuf, readin);
Serial.println("");
}
}
| true |
a5537463f566f55b6e70a1bbe0515819043626c8 | C++ | shenfei/real_root_isolation | /var_orders/var_orders.cpp | UTF-8 | 360 | 2.90625 | 3 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
int main()
{
string line;
do{
getline(cin,line);
}while (line.find("The order") == string::npos);
while (getline(cin,line))
{
if (line.find('=') != string::npos)
break;
cout << line.substr(1) <<endl;
}
return 0;
}
| true |
20865ca248bfdf21e1b4d1ee521ae4000af59c72 | C++ | stevencoding/jobduoj | /JD1533(AC).cpp | UTF-8 | 601 | 3.03125 | 3 | [] | no_license | #include <algorithm>
#include <cstdio>
#include <vector>
using namespace std;
int LIS(vector<int> &a)
{
int n = a.size();
if (n < 2) {
return n;
}
vector<int> s;
int i;
int j;
s.push_back(a[0]);
for (i = 1; i < n; ++i) {
if (a[i] > s.back()) {
s.push_back(a[i]);
continue;
}
j = lower_bound(s.begin(), s.end(), a[i]) - s.begin();
s[j] = a[i];
}
j = s.size();
s.clear();
return j;
}
int main()
{
vector<int> a;
int n, i;
while (scanf("%d", &n) == 1) {
a.resize(n);
for (i = 0; i < n; ++i) {
scanf("%d", &a[i]);
}
printf("%d\n", LIS(a));
}
return 0;
} | true |
61e4a1c6208162c4f29b1ee0d0f9a8374f0ac88b | C++ | soltree12/EffectiveCPPStudy | /35_AlternativesToVirtual/GameCharacter_TR1Func.h | UHC | 2,582 | 3.65625 | 4 | [] | no_license | /*
tr1::function
ȯ, Ű ȣȯ ɼ ̴ (ñ״ó ȣȯǴ Լȣ⼺ ü)
ex) ȯ int ƴ int ٲ ִ Ÿ Լ ȣȯǵ .
*/
#pragma once
#include <functional>
class GameCharacter; //
int defaultHealthCalc(const GameCharacter& gc);
short calcHealth(const GameCharacter& gc); // üġ ԼԴϴ. ȯ Ÿ int ƴ κп ָ!
/* üġ Լ ü Ŭ */
struct HealthCalculator {
int operator()(const GameCharacter& gc) const;
};
class GameLevel {
public:
float health(const GameCharacter&) const; // üġ 꿡 ԼԴϴ. ȯ Ÿ int ƴ κп ָϼ
};
class GameCharacter {
public:
/*
HealthCalcFunc Լȣ⼺ üμ, GameCharacter ȣȯ ̵ ѰܹƼ ȣ
int ȣȯǴ Ÿ ü ȯմϴ.
*/
typedef std::function<int (const GameCharacter&)> HealthCalcFunc; // funtcion ø νϽȭ Ϳ typedef Ÿ
explicit GameCharacter(int newHealth, HealthCalcFunc hcf = defaultHealthCalc) : theHealth(newHealth), healthFunc(hcf) {} // ڿ Լ ѱ
int getHealth() const { return theHealth; }
int healthFunction() const
{
return healthFunc(*this);
}
private:
HealthCalcFunc healthFunc;
int theHealth;
};
class EvilBadGuy :public GameCharacter {
public:
explicit EvilBadGuy(int newHealth, HealthCalcFunc hcf = defaultHealthCalc) : GameCharacter(newHealth, hcf) {}
};
// üġ 꿡 ⺻ ˰ Լ(ü Ƽ ȯѴٰ )
int defaultHealthCalc(const GameCharacter& gc) {
if (gc.getHealth() >= 5) return gc.getHealth() - 5;
else return 0;
}
// ٸ üġ Լ
short calcHealth(const GameCharacter& gc){
if (gc.getHealth() >= 10) return gc.getHealth() - 10;
else return 0;
}
int HealthCalculator::operator()(const GameCharacter& gc) const {
if (gc.getHealth() >= 100) return gc.getHealth() - 100;
else return 0;
}
int loseHealthQuickly(const GameCharacter& gc) {
if (gc.getHealth() >= 100) return gc.getHealth() - 100;
else return 0;
}
float GameLevel::health(const GameCharacter& gc) const {
if (gc.getHealth() >= 1) return gc.getHealth() - 1;
else return 0;
} | true |
f51c86f78c7eea190b39b97300d9c7e54caf6d96 | C++ | davison0487/Checker-Bot | /Game.hpp | UTF-8 | 1,277 | 2.578125 | 3 | [] | no_license | //
// Game.hpp
// Checkers
//
// Created by rick gessner on 2/22/21.
// Copyright © 2021 rick gessner. All rights reserved.
//
#ifndef Game_hpp
#define Game_hpp
#include "Player.hpp"
#include "Piece.hpp"
#include "stdio.h"
#include <iostream>
namespace ECE141 {
enum class Reasons {tbd, forfeit, badmove, eliminated,
missedJump, moved2, clockExpired};
class Game {
public:
static const size_t kBoardHeight = 8;
static const size_t kPiecesPerPlayer = 12;
static Reasons run(Player &aP1, Player &aP2, std::ostream &anOutput);
//These methods are used by player to interact with game...
virtual size_t countAvailablePieces(PieceColor aColor)=0;
virtual const Piece* const getAvailablePiece(PieceColor aColor,
int anIndex)=0;
virtual const Tile* const getTileAt(const Location &aLocation)=0;
virtual bool movePieceTo(const Piece &aPiece,
const Location &aLocation)=0;
protected:
void setKind(Piece &aPiece, PieceKind aKind);
void setTile(Piece &aPiece, Tile* aTile);
void setPiece(Tile &aTile, Piece* aPiece);
};
}
#endif /* Game_hpp */
| true |
56a87d347a79d26403319e020915a1f93d0aa5f3 | C++ | lparolari/greenhouse | /test/delay/test.cpp | UTF-8 | 1,486 | 2.84375 | 3 | [] | no_license | #include <unity.h>
#include "delay.hpp"
void delay_is_not_fired_after_creation_test()
{
greenhouse::delay::Delay<0> d1;
greenhouse::delay::Delay<3000> d2;
TEST_ASSERT_FALSE(d1.is_fired())
TEST_ASSERT_FALSE(d2.is_fired())
}
void delay_is_fired_if_forwarded_by_at_least_delayamount_test()
{
greenhouse::delay::Delay<3000> d;
d.tick(1000);
TEST_ASSERT_FALSE(d.is_fired());
d.tick(3000);
TEST_ASSERT_FALSE(d.is_fired());
d.tick(3001);
TEST_ASSERT_TRUE(d.is_fired())
}
void delay_is_fired_if_forwarded_by_at_least_delayamount_even_if_cleared_test()
{
greenhouse::delay::Delay<3000> d;
d.tick(3500);
TEST_ASSERT_TRUE(d.is_fired());
d.clear();
TEST_ASSERT_FALSE(d.is_fired());
d.tick(9000);
TEST_ASSERT_TRUE(d.is_fired());
}
void delay_clear_do_not_reset_previous_time()
{
greenhouse::delay::Delay<3000> d;
d.tick(3500);
TEST_ASSERT_TRUE(d.is_fired());
d.clear();
TEST_ASSERT_FALSE(d.is_fired());
// We do not expect `d.clear()` reset delay status such that it computes
// 4000 - 0 > 3000 and fires
d.tick(4000);
TEST_ASSERT_FALSE(d.is_fired());
}
int main()
{
UNITY_BEGIN();
RUN_TEST(delay_is_not_fired_after_creation_test);
RUN_TEST(delay_is_fired_if_forwarded_by_at_least_delayamount_test);
RUN_TEST(delay_is_fired_if_forwarded_by_at_least_delayamount_even_if_cleared_test);
RUN_TEST(delay_clear_do_not_reset_previous_time);
UNITY_END();
}
| true |
f49c178f1709aa38f9f3661ce48b359f7c2d46ea | C++ | crypps1412/KTLT-project | /control.ino | UTF-8 | 5,310 | 2.546875 | 3 | [] | no_license | #include <ESP8266WiFi.h>
#include <Servo.h>
Servo sv1,sv2,sv3,sv4;
#define SV1 2
#define SV2 0
#define SV3 4
#define SV4 5
#define PWMA 14
#define DIRA 12
#define PWMB 13
#define DIRB 15
const char* ssid = "iPhon";
const char* password = "12345678";
int Speed;
WiFiServer server(80);
void setup() {
Serial.begin(115200); //Default Baud Rate for NodeMCU
delay(10);
sv1.attach(SV1);
sv2.attach(SV2);
sv3.attach(SV3);
sv4.attach(SV4);
pinMode(PWMA, OUTPUT);
pinMode(DIRA, OUTPUT);
pinMode(PWMB, OUTPUT);
pinMode(DIRB, OUTPUT);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
sv_build(1);
sv_build(2);
sv_build(3);
sv_build(4);
}
void sv_build(int num)
{
Servo sv;
if (num == 1) sv = sv1;
if (num == 2) sv = sv2;
if (num == 3) sv = sv3;
if (num == 4) sv = sv4;
int pos;
for (pos = 0; pos <= 180; pos += 1) {
sv.write(pos);
delay(15);
}
for (pos = 180; pos >= 0; pos -= 1) {
sv.write(pos);
delay(15);
}
}
void loop() {
// put your main code here, to run repeatedly:
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
Serial.println("new client");
while(!client.available()){
delay(1);
}
String req = client.readStringUntil('\r');
Serial.println(req);
client.flush();
bool check = false;
check = check | armHandle(req);
check = check | carHandle(req);
if (check == false)
{
Serial.println("invalid request");
client.stop();
return;
}
String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\n";
s += req;
s += "</html>";
client.println(s);
client.flush();
}
int getData(String req,int Max,int Min)
{
int posGet;
String posStr;
for (posGet=Max;posGet>=Min;posGet--)
{
posStr = String(posGet);
if (req.indexOf(posStr) != -1)
{
Serial.println(req.indexOf(posStr));
return posGet;
}
}
return -1;
}
int armHandle(String req)
{
int c = getData(req,180,0);
if (c ==-1) return 0;
if (req.indexOf("Servo1") != -1)
{
sv1.write(c);
return 1;
}
if (req.indexOf("Servo2") != -1)
{
sv2.write(c);
return 1;
}
if (req.indexOf("Servo3") != -1)
{
sv3.write(c);
return 1;
}
if (req.indexOf("Servo4") != -1)
{
sv4.write(c);
return 1;
}
}
int carHandle(String req)
{
int Speed = getData(req,200,0);
if (Speed ==-1) return 0;
if (req.indexOf("goFt") != -1)
{
goT();
return 1;
}
if (req.indexOf("goFL") != -1)
{
goTT();
return 1;
}
if (req.indexOf("goFR") != -1)
{
goTP();
return 1;
}
if (req.indexOf("stop") != -1)
{
Stop();
return 1;
}
if (req.indexOf("goL") != -1)
{
goTr();
return 1;
}
if (req.indexOf("goR") != -1)
{
goP();
return 1;
}
if (req.indexOf("goBk") != -1)
{
goL();
return 1;
}
if (req.indexOf("goBL") != -1)
{
goLT();
return 1;
}
if (req.indexOf("goBR") != -1)
{
goLP();
return 1;
}
return 0;
}
void goT() {
Serial.println("Tiến " + String(Speed));
analogWrite(PWMA, Speed);
analogWrite(PWMB, Speed);
digitalWrite(DIRB, HIGH);
digitalWrite(DIRB, HIGH);
}
void goTP() {
Serial.println("Tiến phải " + String(Speed));
analogWrite(PWMA, Speed);
analogWrite(PWMB, Speed / 2);
digitalWrite(DIRA, HIGH);
digitalWrite(DIRB, HIGH);
}
void goTT() {
Serial.println("Tiến trái " + String(Speed));
analogWrite(PWMA, Speed / 2);
analogWrite(PWMB, Speed);
digitalWrite(DIRA, HIGH);
digitalWrite(DIRB, HIGH);
}
void goL() {
Serial.println("Lùi " + String(Speed));
analogWrite(PWMA, Speed);
analogWrite(PWMB, Speed);
digitalWrite(DIRA, LOW);
digitalWrite(DIRB, LOW);
}
void goLP() {
Serial.println("Lùi phải " + String(Speed));
analogWrite(PWMA, Speed);
analogWrite(PWMB, Speed / 2);
digitalWrite(DIRA, LOW);
digitalWrite(DIRB, LOW);
}
void goLT() {
Serial.println("Lùi trái " + String(Speed));
analogWrite(PWMA, Speed / 2);
analogWrite(PWMB, Speed);
digitalWrite(DIRA, LOW);
digitalWrite(DIRB, LOW);
}
void goTr() {
Serial.println("Trái " + String(Speed));
analogWrite(PWMA, Speed / 2);
analogWrite(PWMB, Speed / 2);
digitalWrite(DIRA, LOW);
digitalWrite(DIRB, HIGH);
}
void goP() {
Serial.println("Phải " + String(Speed));
analogWrite(PWMA, Speed / 2);
analogWrite(PWMB, Speed / 2);
digitalWrite(DIRA, HIGH);
digitalWrite(DIRB, LOW);
}
void Stop() {
Serial.println("Stop " + String(Speed));
analogWrite(PWMA, 0);
analogWrite(PWMB, 0);
}
| true |
59c1c98de172ad557977c927b661e486e0f03151 | C++ | jems89/Ejercicio-de-Clases-POO-Lara-Cola | /class1.h | ISO-8859-1 | 1,753 | 2.90625 | 3 | [] | no_license | #ifndef CLASS1_H_INCLUDED
#define CLASS1_H_INCLUDED
/*Llenar (float): Debe permitir aumentar la ocupacin del recipiente pero nunca por encima de su capacidad.
Vaciar(float): Debe permitir disminuir la ocupacin del recipiente pero nunca por debajo de 0.
Vaciar(): Debe vaciar por completo la ocupacin del recipiente.
Tapar(): Debe tapar la botella.
Destapar(): Debe destapar la botella.
Hacer mtodos que permitan obtener la capacidad,
la ocupacin y la disponibilidad de la botella(esto ltimo representa cunto tiene disponible an para cargar).
Al crear un objeto Botella se puede suministrar la capacidad del mismo. Si no se indica, debe ser 100 por defecto.
En cualquier caso, la ocupacin ser inicialmente de 0.
Todos los mtodos que consideren necesarios deben limitarse a que la botella se encuentre destapada.
De lo contrario, no podrn realizarse. Ejemplo: No se puede vaciar una botella tapada.
*/
#include "rlutil.h"
#include <iostream>
#include"class1.h"
#include <stdlib.h>
#include<stdio.h>
#include <cstring>
using namespace std;
class botella{
private:
float capacidad=100 ; ///100mml
bool tapa=false; ///Tiene tapa si o no?//
float CONT=0; /// tiene agua si o no?//
public: ///metodos y comportamiento
void GetActual();
void SetCapacidad(float);
void getcontenido();
float GetCapacidad();
void CargarBotella(float);
void DescargarBotella(float);
float getcapacidad();
bool TaparBotella();
bool DestaparBotella( );
void VaciarBotella();
void getEstado();
void mostrarCarga();
};
#endif // CLASS1_H_INCLUDED
| true |
32d33296ff1def685dc65309f322560321e6057d | C++ | ToeTag/adventure-world | /gamemap.h | UTF-8 | 1,107 | 2.703125 | 3 | [] | no_license | //
// GameMap.h
// AdventureWorld
//
// Created by Niclas Kempe on 2012-08-13.
// Copyright 2012 __MyCompanyName__. All rights reserved.
//
#ifndef MAP_H
#define MAP_H
#include <iostream>
#include <string>
#include "Area.h"
using namespace std;
namespace AdventureWorld
{
class GameMap
{
public:
GameMap(int, int);
~GameMap(void);
//friend GameMap operator+<>(const GameMap&, const GameMap&);
//friend GameMap operator-<>(const GameMap&, const GameMap&);
void print_areas() const;
void move_character(Character * c, Area *);
Area * find_character(Character *) const;
Area * get_area_from_coords(int row, int col) const;
void refresh_map();
void get_coords_from_area(Area * a, int & out_row, int & out_col) const;
private:
void assign_neighbours(void);
Area **areas ;
int cols;
int rows;
};
}
#endif | true |
1e70ef2750778fcf3caabeb28340b6fc91c94d32 | C++ | code-hunger/Spreadsheets-Lower | /Formula.h | UTF-8 | 1,357 | 3.21875 | 3 | [] | no_license | #pragma once
#include <memory>
#include <optional>
#include <string>
namespace formulas {
struct Context
{
virtual float at(size_t x, size_t y) const = 0;
virtual ~Context(){};
};
struct Formula
{
virtual float compute(Context const&) const = 0;
virtual ~Formula(){};
};
using FormulaPtr = std::unique_ptr<Formula>;
struct Atomic : Formula
{
const float value;
Atomic(float value) : value(value) {}
float compute(Context const&) const override { return value; }
virtual ~Atomic(){};
};
constexpr char operators[] = {'+', '-', '/', '*', '^'};
struct Binary : Formula
{
enum OP { plus, minus, multiply, divide, exp };
const OP op;
const FormulaPtr left, right;
static OP toOp(char op);
Binary(FormulaPtr left, OP op, FormulaPtr right)
: op(op), left(std::move(left)), right(std::move(right))
{
}
Binary(FormulaPtr left, char op, FormulaPtr right)
: op(toOp(op)), left(std::move(left)), right(std::move(right))
{
}
float compute(Context const&) const override;
virtual ~Binary(){};
};
struct Reference : Formula
{
size_t x, y;
float compute(Context const& c) const override { return c.at(x, y); }
Reference(std::pair<size_t, size_t> cell) : x(cell.first), y(cell.second) {}
virtual ~Reference(){};
};
std::optional<FormulaPtr> parse(std::string str);
} // namespace formulas
using Formula = formulas::Formula;
| true |
93a62b67bd91810f5c5c73e203dfe2e12032c6ae | C++ | tuxmuzon/hotel | /models/bookingviewmodel.cpp | UTF-8 | 2,542 | 2.515625 | 3 | [] | no_license | #include "bookingviewmodel.h"
BookingViewModel::BookingViewModel(QObject *parent) : QSqlQueryModel (parent)
{
headers << "bookingId" << "appartmentsId" << "personsId" << "Номер" << "Дата заезда" << "Дата выезда" << "Статус" << "Цена" << "Всего" << "Оплачено" << "Комментарий" << "Клиент";
resetFilter();
}
void BookingViewModel::updateData()
{
updateQuery();
}
void BookingViewModel::setFilterByApartment(int apartment)
{
filterApartmentIds = apartment;
updateQuery();
}
void BookingViewModel::setFilterByClient(int client)
{
filterClientIds = client;
updateQuery();
}
void BookingViewModel::updateQuery()
{
ESqlQuery query;
query.prepare(" SELECT bookings.id, apartments.id, persons_profiles.id, apartments.shortname, bookings.start_date, stop_date, "
"booking_status.shortname, cost, total, payd, bookings.comment,"
" concat_ws(' ', firstname, secondname, lastname) "
" FROM bookings"
" LEFT JOIN persons_profiles ON bookings.personsprofileid = persons_profiles.id"
" LEFT JOIN booking_status ON booking_status.id = bookings.booking_status"
" LEFT JOIN apartments ON apartment_id = apartments.id"
" WHERE CASE WHEN $1 = -1 THEN TRUE ELSE apartments.id = $1 END"
" AND CASE WHEN $2 = -1 THEN TRUE ELSE persons_profiles.id = $2 END;");
query.addBindValue(filterApartmentIds);
query.addBindValue(filterClientIds);
query.exec();
setQuery(query);
}
QVariant BookingViewModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role == Qt::DisplayRole && orientation == Qt::Orientation::Horizontal)
{
if (section < headers.size())
return headers.at(section);
}
return QSqlQueryModel::headerData(section, orientation, role);
}
void BookingViewModel::resetFilter()
{
filterApartmentIds = -1;
filterClientIds = -1;
updateData();
}
int BookingViewModel::getAppartmentId(const QModelIndex &ind)
{
QModelIndex selectedIndex = index(ind.row(), 1);
return data(selectedIndex).toInt();
}
int BookingViewModel::getBookingId(const QModelIndex &ind)
{
QModelIndex selectedIndex = index(ind.row(), 0);
return data(selectedIndex).toInt();
}
int BookingViewModel::getPersonsId(const QModelIndex &ind)
{
QModelIndex selectedIndex = index(ind.row(), 2);
return data(selectedIndex).toInt();
}
| true |
b1e573bb6afc8cc80a2e676b506f2c24e26ed415 | C++ | KrenZfer/EngineProjek2D | /graphiccoba/Graphic/ErrorHandling.cpp | UTF-8 | 478 | 2.53125 | 3 | [] | no_license | #include "ErrorHandling.h"
void EngineProject2D::ErrorHandling::fatalError(string errorString)
{
cout << errorString << endl;
cout << "Hit Enter To Quit" << endl;
int temp;
cin >> temp;
SDL_Quit();
exit(1);
}
void EngineProject2D::ErrorHandling::fatalError(string errorString, int delay)
{
cout << errorString << endl;
SDL_Delay(delay);
SDL_Quit();
exit(1);
}
void EngineProject2D::ErrorHandling::nonFatalError(string errorString)
{
cout << errorString << endl;
}
| true |
70872f2ebefd384104421e6ddddffbc1f44c371c | C++ | IliyanKafedzhiev/FacultyOfMathematicAndInformatic | /C++SDP/02.Stack/Stack/LinkedLists/Source.cpp | UTF-8 | 607 | 3.15625 | 3 | [] | no_license | #include <stack>
#include <queue>
#include <iostream>
#include "LinkedList.h"
#include "Stack.h"
using namespace std;
template class LinkedList<int>;// check for compilation errors
template class Stack<int>;// check for compilation errors
void testStack()
{
Stack<int> h;
for (int i = 0; i < 10; i++)
{
h.Push(i);
}
Stack<int> z;
z.Copy(h);
for (int i = 0; i < 10; i++)
{
cout << z.Pop() << endl;
}
}
void testListIterators()
{
LinkedList<int> s;
s.TestIterators();
}
int main()
{
try
{
testListIterators();
}
catch (exception ex)
{
cout << ex.what() << endl;
}
return 0;
} | true |
2198f71061659b4607eb37455b70fa4e19c68a8e | C++ | nikhilmohan33/Lab220 | /Lab 1 TV Jammer F17/tutorial/tutorial.ino | UTF-8 | 4,778 | 3.390625 | 3 | [] | no_license | /* Basic Arduino tutorial
18-220 S13
*/
// Declare identifiers for pins for neater/readable code.
// These variables will not change.
const int LEDA = 8; // digital pin LEDA is connected to
const int LEDB = 9; // digital pin LEDB is connected to
const int buttonA = 10; // digital pin buttonA is connected to
const int buttonB = 11; // digital pin buttonB is connected to
const int buzzer = 5; // PWM pin the buzzer is connected to
// analog pin we'll read potentiometer value from (A0)
// attach the center pin of the pot to pin A0, and the outside pins to +5V and ND
const int analogIn = 0;
// Declare variables that will change
int buttonAState = 0; // digital state of buttonA (will be 0 or 1)
int buttonBState = 0; // digital state of buttonB (will be 0 or 1)
int potValue = 0; // analog value of potentiometer (will be 0-1023)
// setup routine; runs each time the Arduino is reset
void setup() {
// declare which pins are inputs, which are outputs
pinMode(LEDA, OUTPUT); // we'll be writing values to the LED, so it's an output
pinMode(LEDB, OUTPUT); // we'll be writing values to the LED, so it's an output
pinMode(buttonA, INPUT); // we'll be reading values from the button, so it's an input
pinMode(buttonB, INPUT); // we'll be reading values from the button, so it's an input
pinMode(buzzer, OUTPUT); // we'll be writing a square wave to the buzzer, so it's an output
pinMode(analogIn, INPUT);// we'll be reading values from the analog input, so declare it as such
Serial.begin(9600); // initialize serial communication at 9600 bits per second for analogRead
}
// loop routine; runs over and over until Arduino is reset or powered off
void loop() {
/**********************************************************************
* Lighting an LED
***********************************************************************/
// Read state of buttonA
// The digitalRead function will return 0 or 1 depending on whether a
// low or high voltage is read on the buttonA pin
buttonAState = digitalRead(buttonA);
// if buttonA state is high, turn LEDA on; else, turn it off
if(buttonAState == HIGH) { // HIGH is the voltage level for logic 1; it is a pre-defined constant
digitalWrite(LEDA, HIGH); // turn the LED on by writing HIGH
}
else {
digitalWrite(LEDA, LOW); // turn the LED off by writing LOW
}
// delay three seconds
delay(3000); // units are in milliseconds
// shut the LED off
digitalWrite(LEDA, LOW);
/**********************************************************************
* Blinking an LED
***********************************************************************/
// read state of buttonB
buttonBState = digitalRead(buttonB);
// If buttonB state is high, manually blink LEDB on/off with a delay of one second.
// You could do this in other ways!
if(buttonBState == HIGH) {
digitalWrite(LEDB, HIGH); // turn the LED on by writing a HIGH voltage to the LEDB pin
delay(1000); // delay one second
digitalWrite(LEDB, LOW); // turn the LED off by writing a LOW voltage to the LEDB pin
delay(1000); // delay one second
digitalWrite(LEDB, HIGH); // turn the LED on by writing a HIGH voltage to the LEDB pin
delay(1000); // delay one second
digitalWrite(LEDB, LOW); // turn the LED off by writing a LOW voltage to the LEDB pin
delay(1000); // delay one second
digitalWrite(LEDB, HIGH); // turn the LED on by writing a HIGH voltage to the LEDB pin
delay(1000); // delay one second
digitalWrite(LEDB, LOW); // turn the LED off by writing a LOW voltage to the LEDB pin
delay(1000); // delay one second
}
else {
digitalWrite(LEDB, LOW); // write a LOW voltage to the LEDB pin
}
delay(3000); // delay three seconds
/**********************************************************************
* Sending a tone to a buzzer
***********************************************************************/
tone(buzzer,1000); // output a 5 kHz, 50% duty cycle square wave to the buzzer pin
delay(3000); // delay three seconds
noTone(buzzer); // shuts the tone off;
delay(3000); // delay three seconds
/**********************************************************************
* Reading an analog input and printing to the serial monitor
***********************************************************************/
potValue = analogRead(analogIn); // read the analog value on the proper pin
Serial.println("Potentiometer value: "); // print string to serial monitor
Serial.println(potValue); // print the value to the serial monitor
}
| true |
dafdb56d2de95f72e415f6e8d9e53efc9782e7e3 | C++ | FabriceScoupe/ProjectEuler | /115/Problem115.cc | UTF-8 | 2,315 | 3.515625 | 4 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <map>
using namespace std;
/***
NOTE: This is a more difficult version of problem 114.
A row measuring n units in length has red blocks with a minimum length of m
units placed on it, such that any two red blocks (which are allowed to be
different lengths) are separated by at least one black square.
Let the fill-count function, F(m, n), represent the number of ways that a row
can be filled.
For example, F(3, 29) = 673135 and F(3, 30) = 1089155.
That is, for m = 3, it can be seen that n = 30 is the smallest value for
which the fill-count function first exceeds one million.
In the same way, for m = 10, it can be verified that F(10, 56) = 880711
and F(10, 57) = 1148904, so n = 57 is the least value for which the fill-count
function first exceeds one million.
For m = 50, find the least value of n for which the fill-count function
first exceeds one million.
***/
// Re-using 114, making binomial a memoised function
long long binomial( int n, int k )
{
static map< pair< int,int >, long long > memo;
long long& m = memo[ pair<int,int>( n, k ) ];
if ( m > 0 ) return m;
long long bp = 1;
int ns = 1;
int nk = n - k;
int nks = 1;
int ks = 1;
while( ns < n )
{
bp *= ++ns;
if ( ( nks < nk ) && ( bp % (nks+1) == 0 ) ) bp /= ++nks;
if ( ( ks < k ) && ( bp % (ks+1) == 0 ) ) bp /= ++ks;
}
m = bp;
return bp;
}
long long F( int m, int n )
{
long long sum = 0;
for( int nr = 1; n - (m+1)*nr + 1 >= 0 ; ++nr )
{
int max_l = n - m*nr; // Available length for black
// At least enough black tiles for gaps, so min = nr - 1
for( int nb = nr-1; nb <= max_l; ++nb )
{
int avl = max_l - nb; // Available for red
int nw1 = binomial( avl+nr-1, nr-1 );
int nw2 = binomial( nb+1, nr );
sum += nw1*nw2;
}
}
return sum;
}
int main( int argc, char** argv )
{
int m = 50;
if ( argc > 1 ) m = atoi( argv[ 1 ] );
long long limit = 1000000LL;
if ( argc > 2 ) limit = atoll( argv[ 2 ] );
cout << "min(n) such as F(" << m << ", n) > " << limit << " = " << endl;
int n = m;
while( F( m, n ) <= limit ) ++n;
cout << "Answer: " << n << endl;
return 0;
}
| true |
69bc26721057c1fe2135501984b81fd4e9fe7436 | C++ | ned14/outcome | /doc/src/snippets/error_code_enums2.cpp | UTF-8 | 3,310 | 2.734375 | 3 | [
"BSL-1.0",
"Apache-2.0"
] | permissive | /* Example of Outcome used with error code enums
(C) 2017-2019 Niall Douglas <http://www.nedproductions.biz/> (3 commits)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License in the accompanying file
Licence.txt or at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file Licence.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#include "../../../include/outcome.hpp"
#include <iostream>
//! [declaration]
struct udt
{
int a{0};
explicit udt(int _a)
: a(_a)
{
}
udt() = default;
int operator*() const { return a; }
};
enum class err
{
success,
failure1,
failure2
};
// Tell the standard library that enum err is an error code enum
// by specialising the is_error_code_enum trait. See
// http://en.cppreference.com/w/cpp/error/error_code/is_error_code_enum
namespace std
{
template <> struct is_error_code_enum<err> : std::true_type
{
};
}
// We also must declare a free function make_error_code. This is
// discovered via ADL by the standard library. See
// http://en.cppreference.com/w/cpp/error/errc/make_error_code
inline std::error_code make_error_code(err c)
{
// We need to inherit from std::error_category to define
// an error code domain with the standard library for
// our strongly typed enum. See
// http://en.cppreference.com/w/cpp/error/error_category
static struct err_category : std::error_category
{
virtual const char *name() const noexcept override final { return "err_category"; };
virtual std::string message(int c) const override final
{
switch(static_cast<err>(c))
{
case err::success:
return "err::success";
case err::failure1:
return "err::failure1";
case err::failure2:
return "err::failure2";
}
return "unknown";
}
} category;
return std::error_code(static_cast<int>(c), category);
}
//! [declaration]
using namespace OUTCOME_V2_NAMESPACE;
int main()
{
//! [usage]
result<udt, err> res(err::failure1);
// What happens here? What exception type is thrown?
try
{
std::cout << *res.value() << std::endl;
}
catch(const std::exception &e)
{
std::cerr << "Exception thrown was " << e.what() << std::endl;
}
//! [usage]
return 0;
}
void test()
{
//! [usage2]
result<udt /*, std::error_code */> res(err::failure1);
// What happens here? What exception type is thrown?
try
{
std::cout << *res.value() << std::endl;
}
catch(const std::exception &e)
{
// Prints "Exception thrown was failure1", exactly the same as before
std::cerr << "Exception thrown was " << e.what() << std::endl;
}
//! [usage2]
}
//! [usage3]
result<udt> boo()
{
return err::failure1;
}
result<udt> foo()
{
OUTCOME_TRY(auto v, (boo()));
return udt{5}; // emplace construct udt with 5
}
//! [usage3]
| true |
6a6ada49e5b7237776a7a1b1d1cbc60367d21995 | C++ | BrandeisMakerLab/Robotics_ZumoAutomation | /examples/DriveShield_Simple_Example/DriveShield_Simple_Example.ino | UTF-8 | 750 | 3.0625 | 3 | [] | no_license | /*Written by Jacob Smith for Brandeis Robotics Club
contains an example program to use our Drive class.
The program is documented for a general audience.
April 2 2018
*/
//includes the header file of the library
#include <DriveShield.h>
//creates a global reference to a Drive object
DriveShield robot;
//occurs before the program enters its main loop
void setup() {
Serial.begin(9600);
//commands the robot to stop for 2 seconds
robot.stopDrive(2000);
}
//the main loop of the robot
void loop() {
//commands the robot to perform each step for half a second
robot.driveForward(500);
robot.turnRight(300);
robot.turnLeft(300);
robot.driveBackward(500);
robot.pivotLeft(300);
robot.pivotRight(300);
robot.stopDrive(500);
}
| true |
013c172aca09244886f95a12d79f7368d4dc0ae1 | C++ | harshraj22/problem_solving | /solution/leetcode/5.cpp | UTF-8 | 1,186 | 3.015625 | 3 | [] | no_license | // https://leetcode.com/problems/longest-palindromic-substring/
class Solution {
// pair of (index, length)
pair<int, int> ans; string s;
vector<vector<int>> dp;
bool recur(int left, int right) {
if (left > right)
return false;
else if (left == right) {
if (ans.second < 1)
ans = make_pair(left, 1);
return true;
}
else if (dp[left][right] != -1)
return dp[left][right];
else if (s[left] != s[right])
dp[left][right] = false;
else
dp[left][right] = (left+1 < right) ? recur(left+1, right-1): true;
recur(left+1, right); recur(left, right-1);
if (ans.second < right-left+1 && dp[left][right])
ans = make_pair(left, right-left+1);
return dp[left][right];
}
public:
string longestPalindrome(string str) {
int n = str.size(); s = str;
dp.resize(n); ans = {0, 0};
for (auto &it: dp) {
it.resize(n);
fill(it.begin(), it.end(), -1);
}
recur(0, n-1);
return s.substr(ans.first, ans.second);
}
}; | true |
c10a8dc4cdf5db01cc3477335a444e1f8201a6df | C++ | Nazmul96/C-Programming | /week1-d3/pbl17.cpp | UTF-8 | 248 | 2.828125 | 3 | [] | no_license | /* time duration: 20min
17. Given N, find X and A where N = X*2^A.
*/
#include<stdio.h>
int main()
{
int n,x,A=0;
scanf("%d",&n);
while(n%2==0){
n=n/2;
A++;
}
printf("%d %d\n",n,A);
return 0;
}
| true |
90901b9e5aececc0d2bb2d81805b390bc59c2257 | C++ | jhnaldo/problem-solving | /acmicpc/cpp/11383.cc | UTF-8 | 556 | 2.90625 | 3 | [] | no_license | #include <stdio.h>
bool check(char str[], char str2[], int size){
int i;
for (i = 0; i < size; i++){
if (str[i] != str2[i*2] || str[i] != str2[i*2+1])
return false;
}
return true;
}
int main(){
int n, m, i;
char str[10][11];
scanf("%d %d", &n, &m);
for (i = 0; i < n; i++)
scanf("%s", str[i]);
for (i = 0; i < n; i++){
char eyfa[21];
scanf("%s", eyfa);
if (!check(str[i], eyfa, m))
break;
}
printf("%sEyfa\n", (i==n?"":"Not "));
return 0;
}
| true |
f78c2a0291ef40b75deff5b7fd5cffcbed468a84 | C++ | amiravni/Baby-Busy-Board | /RightCode/classes.h | UTF-8 | 9,293 | 2.78125 | 3 | [
"MIT"
] | permissive | #include "bitmaps.h"
#include "bitmaps_8bits.h"
//////////////////////////////////////////////// VoltageDivider ////////////////////////////////////////////////
// definition of AnalogRead class
class VoltageDivider {
public:
VoltageDivider();
VoltageDivider(int _pin,float _const_R) {
analog_pin = _pin;
const_R = _const_R;
dyn_R_first = true;
}
VoltageDivider(int _pin,float _const_R,bool _dyn_R_first) {
analog_pin = _pin;
const_R = _const_R;
dyn_R_first = _dyn_R_first;
}
VoltageDivider(int _pin,float _const_R,bool _dyn_R_first, float _v_in) {
analog_pin = _pin;
const_R = _const_R;
dyn_R_first = _dyn_R_first;
v_in = _v_in;
}
void SetAvgCount(int _avgCount) {
if (_avgCount > 0) avgCount = _avgCount;
}
void GetValue_Raw() {
value = 0;
for (int idx = 0; idx < avgCount; idx++) value += (float)analogRead(analog_pin);
value /= (float)avgCount;
}
void GetValue_V() {
GetValue_Raw();
v_measured = ((float)value / 1024.0) * v_in ;
}
void GetValue_DynR() {
GetValue_V();
if (dyn_R_first) dynamic_R = const_R * ((v_in / v_measured) - 1);
else dynamic_R = const_R * (v_measured / (v_in - v_measured));
/*PRINTDEBUG(dynamic_R);
PRINTDEBUG(" , ");
PRINTDEBUG(v_measured);
PRINTDEBUG(" , ");
PRINTLNDEBUG(value);*/
}
int analog_pin;
float value;
float dynamic_R;
float const_R;
bool dyn_R_first;
float v_in = 5.0;
float v_measured;
int avgCount = 1;
};
//////////////////////////////////////////////// VoltageMapper ////////////////////////////////////////////////
// definition of voltageMapper class
class VoltageMapper : public VoltageDivider {
public:
VoltageMapper(int _pin,float _const_R,bool _dyn_R_first, float _v_in):VoltageDivider(_pin, _const_R, _dyn_R_first, _v_in){};
// _dyn_R_first is true --> v_in ---/\/\dynR/\/\---pin-----/\/\cnstR/\/\---- GND
// _dyn_R_first is false --> v_in ---/\/\cnstR/\/\---pin-----/\/\dynR/\/\---- GND
// the use of *max_val+1* instead of *max_val* is so the linear mapping will be correct.
// for example, 0-10000 to 0-2 without correction would be:
// 0-4999 --> 0
// 5000-9999 --> 1
// 10000 --> 2
// After correction:
// 0-3333 --> 0
// 3334-6666 --> 1
// 6667-10000+ --> 2
bool Map_R_to_int(int min_R, int max_R, int min_val, int max_val, bool updateValues ) {
if (updateValues) GetValue_DynR();
stateVal = map(min(max((int)dynamic_R, min_R), max_R), min_R, max_R, min_val, max_val+1);
if (stateVal == max_val+1) stateVal--;
if (stateVal == lastStateVal) return false;
if (stateVal != lastStateVal && abs(stateVal - lastStateVal) == 1 )
{
float delta = ((max_R - min_R) / (max_val+1 - min_val)) * DELTA_PCT;
if (abs(lastDynR - dynamic_R) < delta)
{
//PRINTDEBUG(lastDynR);PRINTDEBUG(" , ");PRINTDEBUG(dynamic_R);PRINTDEBUG(" , ");PRINTDEBUG(delta);PRINTDEBUG(" , ");
//PRINTLNDEBUG("Hysterezis");
return false;
//return lastStateVal;
}
}
if (updateValues) {
lastStateVal = stateVal;
lastDynR = dynamic_R;
}
return true;
//return stateVal;
}
int stateVal = 0;
int lastStateVal = -99;
float lastDynR = -9999;
};
//////////////////////////////////////////////// my_RGBmatrixPanel ////////////////////////////////////////////////
class my_RGBmatrixPanel: public RGBmatrixPanel {
public:
my_RGBmatrixPanel(int _A, int _B, int _C, int _D, int _CLK, int _LAT, int _OE, bool _sw, int _mw):RGBmatrixPanel(_A, _B, _C, _D, _CLK, _LAT, _OE, _sw, _mw){};
void paintFree(int x,int y,bool cont) {
if (!cont) {
this->fillScreen(0);
lastWidth = x;
lastHeight = y;
this->drawPixel(x, y, curr_color);
}
else {
int dx = (x - lastWidth);
int dy = (y - lastHeight);
int steps;
int dir = 1;
int x_tmp;
int y_tmp;
float a;
if (abs(dx) > abs(dy)) steps = dx;
else steps = dy;
if (steps < 0) dir = -1;
//PRINTDEBUGC(x);PRINTDEBUGC(lastWidth);PRINTDEBUGC(y);PRINTDEBUGC(lastHeight);PRINTDEBUGC(steps);PRINTLNDEBUG(dir);
for (int i = 0; i < abs(steps); i++) {
if (steps == dx) {
a = (float)dy / (float)dx;
x_tmp = lastWidth + dir*(i+1);
y_tmp = lastHeight + round( dir * (float)(i+1) * a );
}
else {
a = (float)dx / (float)dy;
y_tmp = lastHeight + dir*(i+1);
x_tmp = lastWidth + round( dir * (float)(i+1) * a );
}
//PRINTDEBUG(" ----> ");PRINTDEBUGC(a);PRINTDEBUGC(x_tmp);PRINTLNDEBUG(y_tmp);
this->drawPixel(x_tmp, y_tmp, curr_color);
}
lastWidth = x;
lastHeight = y;
}
}
// Convert a BGR 4/4/4 bitmap to RGB 5/6/5 used by Adafruit_GFX
void fixdrawRGBBitmap(int16_t x, int16_t y, uint16_t *bitmap, int16_t w, int16_t h) {
uint16_t RGB_bmp_fixed[w * h];
for (uint16_t pixel=0; pixel<w*h; pixel++) {
uint8_t r,g,b;
uint16_t color = bitmap[pixel];//pgm_read_word_far(bitmap + pixel);
//Serial.print(color, HEX);
b = (color & 0xF00) >> 8;
g = (color & 0x0F0) >> 4;
r = color & 0x00F;
b = map(b, 0, 15, 0, 31);
g = map(g, 0, 15, 0, 63);
r = map(r, 0, 15, 0, 31);
RGB_bmp_fixed[pixel] = (r << 11) + (g << 5) + b;
}
this->drawRGBBitmap(x, y, RGB_bmp_fixed, w, h);
}
void getFarImage(uint32_t ptr, int array_pos, int len) {
for( int i=0; i<len; i++) img[i] = pgm_read_word_far( ptr + 2*array_pos*len + (2 * i));
}
void display_rgbBitmap(int iconSet, uint8_t bmp_num, bool leftFlag) {
int bmx = 0;
int bmy = 0;
if (BITMAP_FLAG) {
if (leftFlag) {
switch (iconSet) {
case 0:
getFarImage(pgm_get_far_address(animals),bmp_num,RGB_BMP_SIZE_SQ);
break;
case 1:
getFarImage(pgm_get_far_address(cars),bmp_num,RGB_BMP_SIZE_SQ);
break;
case 2:
getFarImage(pgm_get_far_address(emoji),bmp_num,RGB_BMP_SIZE_SQ);
break;
case 3:
getFarImage(pgm_get_far_address(food),bmp_num,RGB_BMP_SIZE_SQ);
break;
default:
getFarImage(pgm_get_far_address(animals),bmp_num,RGB_BMP_SIZE_SQ);
break;
}
}
else {
bmx = 32;
switch (iconSet) {
case 0:
getFarImage(pgm_get_far_address(animals2),bmp_num,RGB_BMP_SIZE_SQ);
break;
case 1:
getFarImage(pgm_get_far_address(clothes),bmp_num,RGB_BMP_SIZE_SQ);
break;
case 2:
getFarImage(pgm_get_far_address(flowers),bmp_num,RGB_BMP_SIZE_SQ);
break;
case 3:
getFarImage(pgm_get_far_address(icons),bmp_num,RGB_BMP_SIZE_SQ);
break;
default:
getFarImage(pgm_get_far_address(animals2),bmp_num,RGB_BMP_SIZE_SQ);
break;
}
}
fixdrawRGBBitmap(bmx, bmy, img, RGB_BMP_SIZE, RGB_BMP_SIZE);
this->showImage();
}
}
/*
void display_bitmap(uint8_t bmp_num, uint16_t color,bool erase) {
static uint16_t bmx,bmy;
//Serial.println(bmx);
//Serial.println(bmy);
// Clear the space under the bitmap that will be drawn as
// drawing a single color pixmap does not write over pixels
// that are nul, and leaves the data that was underneath
if (erase) this->fillRect(bmx,bmy, bmx+BIN_BMP_SIZE,bmy+BIN_BMP_SIZE, this->Color333(0, 0, 0));
this->drawBitmap(bmx, bmy, my_mono_bmp[bmp_num], BIN_BMP_SIZE, BIN_BMP_SIZE, color);
bmx += BIN_BMP_SIZE;
if (bmx >= mw) bmx = 0;
if (!bmx) bmy += BIN_BMP_SIZE;
if (bmy >= mh) bmy = 0;
this->showImage();
}
*/
void printHeb(char str[], int length)
{
char ot[(int)(length*1.5)];
for(int i = 0; i<length-1; i+=2)
{
//ot = (str[i])*256+str[i+1];
ot[i] = str[i];
ot[i+1] = str[i+1];
ot[i+2] = 0;
}
this->printHebrew(ot);
}
void printHebStr(char str[]) {
uint8_t w = 0;
uint8_t b = 0;
for (w=0; str[w*2+b]!=0; w++) {
this->setTextColor(Wheel(w*2));
//Serial.println((int)str[w*2+b]);
if ((int)str[w*2+b] == 32) {
this->printHebrew(" ");
b++;
w--;
}
else printHeb(str+(w*2+b),2);
}
}
uint16_t Wheel(byte WheelPos) {
if(WheelPos < 8) {
return this->Color333(7 - WheelPos, WheelPos, 0);
} else if(WheelPos < 16) {
WheelPos -= 8;
return this->Color333(0, 7-WheelPos, WheelPos);
} else {
WheelPos -= 16;
return this->Color333(0, WheelPos, 7 - WheelPos);
}
}
int lastWidth = 0;
int lastHeight = 0;
uint16_t curr_color = this->Color444(0, 0, 0);
uint16_t img[RGB_BMP_SIZE_SQ] = { 0 };
};
| true |
c96b19faf62d4b99fb2b9410feeed847c97dcedd | C++ | EucWang/cpp_primer_plus_demo | /cppprimerplus/p12/test7/test1.cpp | UTF-8 | 1,322 | 3.6875 | 4 | [] | no_license | #include <iostream>
#include "string1.h"
using namespace std;
void test();
int main42(){
test();
// String a("wahaha");
// String b("duolemei");
// String c = a+b;
// cout << c << endl;
// String d = c.up();
// cout << d << endl;
// cout << d.low() << endl;
// cout << "count of letter a is :" << c.countOf('a') << endl;
return 0;
}
void test(){
String127 s1(" and I am a C++ Student.");
String127 s2 = "Please enter your name: ";
String127 s3;
cout << s2;
cin >> s3;
s2 = "My name is " + s3;
cout << s2 << ".\n";
s2 = s2 + s1;
s2.up();
cout << "The String127\n" << s2 << "\ncontians " << s2.has('A')
<< " 'A' characters in it.\n";
s1 = "red";
String127 rgb[3] = {
String127(s1), String127("green"), String127("blue")
};
cout << "Enter the name of a primary color for mixing light: ";
String127 ans;
bool success = false;
while(cin>>ans){
ans.low();
for(int i=0; i<3;i++) {
if(ans == rgb[i]) {
cout << "That's right!\n";
success = true;
break;
}
}
if(success) {
break;
}else {
cout << "Try again!\n";
}
}
cout << "Bye!\n";
} | true |
e4d38582c26c973b1ac14612a0d34130ca136073 | C++ | ArtemisKS/Piscine_CPP | /rush_00/Star.cpp | UTF-8 | 365 | 2.921875 | 3 | [] | no_license | #include "Star.hpp"
#include <ncurses.h>
Star::Star( void ) : AObject() {_val = '.';}
Star::~Star( void ) {}
Star::Star(Star const & src) : AObject(src.getX(), src.getY()){}
Star::Star(int x, int y) : AObject(x, y) {_val = '.';}
bool Star::move( int timeFrame ) {
if (_x >= 11)
{
if (timeFrame % 3 == 0)
_x--;
return TRUE;
}
else
return FALSE;
}
| true |
4da9ac860520410952a7bc7c24e0d80c2fa189e7 | C++ | theochp/c-antlr-compiler | /compiler/ast/unexpression.h | UTF-8 | 337 | 2.71875 | 3 | [] | no_license | #pragma once
#include "expression.h"
#include "unoperator.h"
class UnExpression : public Expression {
Expression *expr;
UnOperator op;
public:
UnExpression(UnOperator op, Expression *expr);
~UnExpression();
const Expression *getExpr() const;
const UnOperator& getOp() const;
virtual std::string print();
}; | true |
14dc5192f2bae06f7ff5c28d6d746e9b207ea6a9 | C++ | CPcoding0930/ACMPractice-C- | /LargestSubsequence/Source.cpp | UTF-8 | 830 | 3.25 | 3 | [] | no_license | #include <queue>
#include <iostream>
#include <string>
using namespace std;
char largest(string s) {
char c = 'a';
for (int i = 0; i < s.length(); i++) {
if (s.at(i) > c) {
c = s.at(i);
}
}
return c;
}
string eraseStr(string s, char c) {
for (int i = 0; i < s.length(); i++) {
if (c == s.at(i)) {
s = s.substr(i + 1, s.length());
return s;
}
}
}
string out(string s, char c) {
if (s.size() == 1 || s.size()== 0) {
return s;
}
else {
string str = eraseStr(s, largest(s));
cout << largest(s);
return out( str, largest(str));
}
}
int main() {
int numCase;
cin >> numCase;
vector<string> s(numCase);
for (int i = 0; i < numCase; i++) {
cin >> s[i];
cout<<out(s[i], largest(s[i]))<<endl;
}
return 0;
}
| true |
c5ae737a7d231ae3841161bdd33815e9b7c4a6e3 | C++ | michelebucelli/apc_project | /timer.h | UTF-8 | 835 | 2.953125 | 3 | [] | no_license | #ifndef _TIMER_H
#define _TIMER_H
#include <chrono>
#include <vector>
#include <string>
#include <sstream>
#include <iomanip>
class timer {
public:
using clock = std::chrono::high_resolution_clock;
using timePoint = std::chrono::time_point<clock>;
private:
timePoint startTime;
timePoint stopTime;
double cumulate;
public:
timer () : startTime ( clock::now() ), stopTime ( clock::now() ), cumulate( 0 ) { };
void start ( void ) { startTime = stopTime = clock::now(); };
void stop ( void ) {
stopTime = clock::now();
cumulate += getTime();
};
double getTime ( void ) const {
auto tspan = std::chrono::duration_cast<std::chrono::nanoseconds> ( stopTime - startTime );
return tspan.count() / 1000000.0;
}
double getCumulate ( void ) const { return cumulate; }
};
#endif
| true |
8158bcfa1489479e39ae96f1c2d00ca7d7302f6f | C++ | shuvokr/LeetCode_Solution | /Algorithms/projection-area-of-3d-shapes.cpp | UTF-8 | 772 | 2.703125 | 3 | [] | no_license | // https://leetcode.com/contest/weekly-contest-96/problems/projection-area-of-3d-shapes/
class Solution {
public:
int projectionArea(vector<vector<int>>& grid) {
int r = grid.size(), ar[55][55], ret = 0;
memset(ar, 0, sizeof ar);
for(int i = 0; i < r; i++)
for(int j = 0; j < r; j++) ar[i][j] = grid[i][j], ret += (bool)(grid[i][j]);
for(int i = 0; i < 51; i++)
{
int mx = 0;
for(int j = 50; j > -1; j--)
mx = max(mx, ar[j][i]);
ret += mx;
}
for(int i = 0; i < 51; i++)
{
int mx = 0;
for(int j = 50; j > -1; j--)
mx = max(mx, ar[i][j]);
ret += mx;
}
return ret;
}
};
| true |
6427a5d1eb9957b6072a5cd4ae7eceb3e4ca4d51 | C++ | cjkjackee/CPE | /pass_year/22171.cpp | GB18030 | 2,726 | 2.5625 | 3 | [] | no_license | #include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
using namespace std;
const int maxn = 50;
int L, R, C;
int Sz, Sx, Sy;
int Ez, Ex, Ey;
char maze[maxn][maxn][maxn];
int dist[maxn][maxn][maxn];
int vis[maxn][maxn][maxn];
queue<int> q;
int bfs()
{
while(!q.empty()) q.pop();
q.push(Sz); q.push(Sx); q.push(Sy);
dist[Sz][Sx][Sy] = 0;
vis[Sz][Sx][Sy] = 1; /// ʾڶ
while(!q.empty())
{
int z = q.front(); q.pop();
int x = q.front(); q.pop();
int y = q.front(); q.pop();
if(z == Ez && x == Ex && y == Ey) return dist[z][x][y];
if(z + 1 <= L && maze[z+1][x][y] != '#' && !vis[z+1][x][y])
{
q.push(z+1); q.push(x); q.push(y);
dist[z+1][x][y] = dist[z][x][y] + 1;
vis[z+1][x][y] = 1;
}
if(z - 1 >= 1 && maze[z-1][x][y] != '#' && !vis[z-1][x][y])
{
q.push(z-1); q.push(x); q.push(y);
dist[z-1][x][y] = dist[z][x][y] + 1;
vis[z-1][x][y] = 1;
}
if(x + 1 <= R && maze[z][x+1][y] != '#' && !vis[z][x+1][y])
{
q.push(z); q.push(x+1); q.push(y);
dist[z][x+1][y] = dist[z][x][y] + 1;
vis[z][x+1][y] = 1;
}
if(x - 1 >= 1 && maze[z][x-1][y] != '#' && !vis[z][x-1][y])
{
q.push(z); q.push(x-1); q.push(y);
dist[z][x-1][y] = dist[z][x][y] + 1;
vis[z][x-1][y] = 1;
}
if(y + 1 <= C && maze[z][x][y+1] != '#' && !vis[z][x][y+1])
{
q.push(z); q.push(x); q.push(y+1);
dist[z][x][y+1] = dist[z][x][y] + 1;
vis[z][x][y+1] = 1;
}
if(y - 1 >= 1 && maze[z][x][y-1] != '#' && !vis[z][x][y-1])
{
q.push(z); q.push(x); q.push(y-1);
dist[z][x][y-1] = dist[z][x][y] + 1;
vis[z][x][y-1] = 1;
}
}
return 0;
}
int main()
{
//freopen("in.txt", "r", stdin);
while(scanf("%d%d%d", &L, &R, &C) && L)
{
memset(dist, 0, sizeof(dist));
memset(vis, 0, sizeof(vis));
for(int i = 1; i <= L; i++)
for(int j = 1; j <= R; j++) {
scanf("%s", &maze[i][j][1]);
}
for(int i = 1; i <= L; i++)
for(int j = 1; j <= R; j++)
for(int k = 1; k <= C; k++)
if(maze[i][j][k] == 'S') { Sz = i; Sx = j; Sy = k; }
else if(maze[i][j][k] == 'E') { Ez = i; Ex = j; Ey = k; }
int dist = bfs();
if(dist) printf("Escaped in %d minute(s).\n", dist);
else printf("Trapped!\n");
}
return 0;
}
| true |
764d7f580d39347b15251917e8119a88de60f72b | C++ | dotnet/runtime | /src/coreclr/pal/tests/palsuite/filemapping_memmgt/MapViewOfFile/test5/mapviewoffile.cpp | UTF-8 | 2,652 | 2.53125 | 3 | [
"MIT"
] | permissive | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*=============================================================
**
** Source: MapViewOfFile.c
**
** Purpose: Negative test the MapViewOfFile API.
** Passing invalid values for the hFileMappingObject.
**
** Depends: CreatePipe,
** CreateFile,
** CreateFileMapping,
** CloseHandle.
**
**
**============================================================*/
#include <palsuite.h>
PALTEST(filemapping_memmgt_MapViewOfFile_test5_paltest_mapviewoffile_test5, "filemapping_memmgt/MapViewOfFile/test5/paltest_mapviewoffile_test5")
{
const int MAPPINGSIZE = 2048;
HANDLE hFileMapping;
LPVOID lpMapViewAddress;
HANDLE hReadPipe = NULL;
HANDLE hWritePipe = NULL;
BOOL bRetVal;
SECURITY_ATTRIBUTES lpPipeAttributes;
/* Initialize the PAL environment.
*/
if(0 != PAL_Initialize(argc, argv))
{
return FAIL;
}
/* Attempt to create a MapViewOfFile with a NULL handle.
*/
hFileMapping = NULL;
lpMapViewAddress = MapViewOfFile(
hFileMapping,
FILE_MAP_WRITE, /* access code */
0, /* high order offset */
0, /* low order offset */
MAPPINGSIZE); /* number of bytes for map */
if((NULL != lpMapViewAddress) &&
(GetLastError() != ERROR_INVALID_HANDLE))
{
Trace("ERROR:%u: Able to create a MapViewOfFile with "
"hFileMapping=0x%lx.\n",
GetLastError());
UnmapViewOfFile(lpMapViewAddress);
Fail("");
}
/* Attempt to create a MapViewOfFile with an invalid handle.
*/
hFileMapping = INVALID_HANDLE_VALUE;
lpMapViewAddress = MapViewOfFile(
hFileMapping,
FILE_MAP_WRITE, /* access code */
0, /* high order offset */
0, /* low order offset */
MAPPINGSIZE); /* number of bytes for map */
if((NULL != lpMapViewAddress) &&
(GetLastError() != ERROR_INVALID_HANDLE))
{
Trace("ERROR:%u: Able to create a MapViewOfFile with "
"hFileMapping=0x%lx.\n",
GetLastError());
UnmapViewOfFile(lpMapViewAddress);
Fail("");
}
/* Clean-up and Terminate the PAL.
*/
PAL_Terminate();
return PASS;
}
| true |
703bff9629cee0bb07c323ab4ebe1ade43d01672 | C++ | yczheng-hit/gensim | /support/libgvnc/lib/Encoder.cpp | UTF-8 | 1,157 | 2.84375 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /* This file is Copyright University of Edinburgh 2018. For license details, see LICENSE. */
#include "libgvnc/Encoder.h"
#include <stdexcept>
using namespace libgvnc;
Encoder::Encoder(const FB_PixelFormat& format, const RectangleShape& shape) : encoded_format_(format), shape_(shape)
{
}
RawEncoder::RawEncoder(const FB_PixelFormat& format, const RectangleShape& shape) : Encoder(format, shape)
{
}
std::vector<char> RawEncoder::Encode(const std::vector<uint32_t> &pixels)
{
std::vector<char> data(GetShape().Width * GetShape().Height * GetFormat().bits_per_pixel / 8);
uint32_t data_ptr = 0;
for (auto pixel_data : pixels) {
switch (GetFormat().bits_per_pixel) {
case 8:
data[data_ptr++] = pixel_data;
break;
case 16:
data[data_ptr++] = pixel_data >> 8;
data[data_ptr++] = pixel_data;
break;
case 24:
data[data_ptr++] = pixel_data >> 16;
data[data_ptr++] = pixel_data >> 8;
data[data_ptr++] = pixel_data;
break;
case 32:
*(uint32_t*) (data.data() + data_ptr) = pixel_data;
data_ptr += 4;
break;
default:
throw std::logic_error("Unknown pixel depth");
}
}
return data;
}
| true |
032e67ceb876873e2a5fe803f74040def5a1e5ef | C++ | kovinevmv/software_design_labs | /lab_1/src/containers_example.cpp | UTF-8 | 2,844 | 3.703125 | 4 | [
"MIT"
] | permissive | #include <iostream>
#include <string>
#include <vector>
#include <list>
#include <deque>
#include <map>
using std::cout;
using std::endl;
int main(int argc, char *argv[])
{
std::initializer_list<int> init = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cout << "Инициализация map значениями : {{1, 2}, {3, 4}, {5, 6}}" << endl;
auto map = std::map<int, int> {{1, 2}, {3, 4}, {5, 6}};
cout << "Итерирование по map:" << endl;
cout << "Map: ";
for (auto & it : map) {
std::cout << "(" << it.first << ":" << it.second << "}, ";
}
cout << endl;
cout << "Изменение map по ключу" << endl;
cout << "Call map[1]\n"; map[1] = 99;
cout << "Call map[3]\n"; map[3] = 99;
cout << "Map: ";
for (auto & it : map) {
std::cout << "(" << it.first << ":" << it.second << "}, ";
}
std::cout << "\n\n\nИнициализация контейнеров vector, list, deque значениями: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\n";
auto vector = std::vector<int>(init);
auto list = std::list<int>(init);
auto deque = std::deque<int>(init);
cout << "Контейнеры vector, deque имеет предоставляют досуп к любому элементу по индексу, список - нет." << endl;
cout << "vector[2] = " << vector[2] << endl;
cout << "deque[2] = " << deque[2] << endl;
cout << "list[2] = error\n\n";
cout << "Доступ к первому и последнему элементу за константное время:" << endl;
cout << "vector[0]: " << vector.front() << "; vector[size-1]: " << vector.back() << endl;
cout << "deque[0]: " << deque.front() << "; deque[size-1]: " << deque.back() << endl;
cout << "list[0]: " << list.front() << "; list[size-1]: " << list.back() << endl << endl;
cout << "Все три контейнера обладают операциями push_back, push_front" << endl;
cout << "Call deque.push_back(99)\n"; deque.push_back(99);
cout << "Call deque.push_front(99)\n"; deque.push_front(99);
cout << "Call list.push_back(99)\n"; list.push_back(99);
cout << "Call list.push_front(99)\n\n"; list.push_front(99);
cout << "Vector не позволяет добавлять элементы в начало" << endl;
cout << "Call vector.push_back(99) - error\n\n";
cout << "Итерирование идентично для всех контейнеров:" << endl;
cout << "Deque: ";
for (auto & it : deque) {
cout << it << " ";
}
cout << endl;
cout << "List: ";
for (auto & it : list) {
cout << it << " ";
}
cout << endl;
cout << "Vector: ";
for (auto & it : vector) {
cout << it << " ";
}
cout << endl;
} | true |
40601affe5fff264c8fdd73dce42b33a12049839 | C++ | TaynaraCruz/8-Puzzle-AI-Solver | /src/HillClimbing/HillClimbing.cpp | UTF-8 | 3,752 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <unordered_set>
#include "HillClimbing.h"
int get_min_Hill(std::map<int, int> Frontier){
std::pair<int, int> min = *std::min_element(Frontier.begin(), Frontier.end(), ComparatorHillClimbing());
return min.first;
}
int HillClimbing(Puzzle* puzzle, Node *State, int k){
/*Priority queue*/
std::map <int, int> Solution_space;
std::map<int, Node*> Solution_space_map;
std::unordered_set <int> Explored;
State->set_heuristic("Greedy");
State->convert_node();
Node* curr = State;
Node* neighbor = State;
int limit = 0;
while(limit <= k){
Explored.insert(curr->intg_node);
//Goal
if(puzzle->check_solution(curr->state)) {
std::cout<<"Explored states: "<<Explored.size()<<std::endl;
return curr->curr_cost;
}
/**************************Actions***********************/
Node* child1 = new Node(curr);
puzzle->move_right(child1->state,curr->state);
child1->convert_node();//convert array into integer
child1->set_heuristic("Greedy");//calculate the heuristic
curr->Add_child(child1);
Node* child2 = new Node(curr);
puzzle->move_left(child2->state,curr->state);
child2->convert_node();//convert array into integer
child2->set_heuristic("Greedy");//calculate the heuristic
curr->Add_child(child2);
Node* child3 = new Node(curr);
puzzle->move_up(child3->state,curr->state);
child3->convert_node();//convert array into integer
child3->set_heuristic("Greedy");//calculate the heuristic
curr->Add_child(child3);
Node* child4 = new Node(curr);
puzzle->move_down(child4->state,curr->state);
child4->convert_node();//convert array into integer
child4->set_heuristic("Greedy");//calculate the heuristic
curr->Add_child(child4);
/**************************Check***********************/
for(int i = 0; i < (int)curr->children.size(); i++){
auto q = Solution_space.find(curr->children[i]->intg_node);
if(Explored.find(curr->children[i]->intg_node) == Explored.end() && q == Solution_space.end()){
Solution_space[curr->children[i]->intg_node] = curr->children[i]->heuristic;
Solution_space_map[curr->children[i]->intg_node] = curr->children[i];
}
else if(q != Solution_space.end()){//if child is in frontier with a higher heuristic cost, replace it
if(Solution_space_map[q->first]->curr_cost > curr->children[i]->heuristic) {
Solution_space_map[q->first] = curr->children[i];
}
}
else delete curr->children[i];
}
int min = get_min_Hill(Solution_space);
neighbor = Solution_space_map[min];
Solution_space.erase(neighbor->intg_node);
Solution_space.erase(neighbor->intg_node);
while(neighbor->heuristic > curr->heuristic && !Solution_space.empty()){
min = get_min_Hill(Solution_space);
neighbor = Solution_space_map[min];
Solution_space.erase(neighbor->intg_node);
Solution_space.erase(neighbor->intg_node);
Explored.insert(neighbor->intg_node);
}
if(neighbor->heuristic < curr->heuristic) curr = neighbor;
else if(neighbor->heuristic == curr->heuristic){//shoulder
curr = neighbor;
limit++;
}
else{
break; //This means faliure
};
}
return -1; //This means faliure
} | true |
049d42babef4025bc4551ffb0ab5b292278f848d | C++ | hanzohasashi33/DSA | /Segment Trees/update.cpp | UTF-8 | 1,051 | 3.046875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
const int N = 1000;
int tree[2 * N];
void update(int arr[],int i,int x,int n)
{
arr[i] = x;
i = (n + i - 2)/2;
while(i > 0)
{
if(arr[tree[2*i + 1]] > arr[tree[2*i + 2]])
{
tree[i] = tree[2*i + 2];
}
else
{
tree[i] = tree[2*i + 1];
}
i = (i - 1)/2;
}
}
void build(int arr[],int n)
{
for(int i = 0;i < n;i++)
{
tree[n + i - 1] = i;
}
for(int i = n - 2;i >= 0;i--)
{
if(arr[tree[2*i + 1]] > arr[tree[2*i + 2]])
{
tree[i] = tree[2*i + 2];
}
else
{
tree[i] = tree[2*i + 1];
}
}
}
void printtree(int treearr[],int n)
{
for(int i = 0;i < n;i++)
{
printf("%d ",treearr[i]);
}
printf("\n");
}
int main()
{
int a[] = {4,1,3,2,8,12,14,16};
int n = sizeof(a)/sizeof(a[0]);
build(a,n);
printtree(tree,2 * n - 1);
update(a, 7, 13, n);
printtree(tree, 2 * n - 1);
return 0;
}
| true |
d71b0a2765369606f9bd7962dce6b7a0e758aa44 | C++ | KawOwio/GameEngine | /src/engine/Entity.h | UTF-8 | 3,966 | 3.140625 | 3 | [] | no_license | #pragma once
#ifndef _ENTITY_H_
#define _ENTITY_H_
#include <memory>
#include <vector>
namespace engine
{
class Component;
class Core;
/// ### Example of usage:
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~.cpp
/// std::shared_ptr<Entity> entityName = core->addEntity();
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class Entity
{
private:
friend class Core;
std::vector<std::shared_ptr<Component>> components;
std::weak_ptr<Core> core;
std::weak_ptr<Entity> self;
public:
/// A function that runs onTick() function of all components attatched to the entity
void tick();
/// A function that runs onDisplay() function of all components attatched to the entity
void display();
/// A shortcut function that returns the core
/// @returns std::shared_ptr<Core> core;
std::shared_ptr<Core> getCore();
/// A template function to get a specific component from an entity.
/// Pass a component name in <> that you wish to retrive.
/// @returns std::shared_ptr<T> component;
/// ### Example of usage:
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~.cpp
/// entityName->getComponent<BoxCollider>()->...;
/// std::shared_ptr<Camera> myNewCamera = oldCamera->getComponent<Camera>();
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template<typename T>
std::shared_ptr<T> getComponent()
{
for (auto it = components.begin(); it != components.end(); it++)
{
std::shared_ptr<T> rtn = std::dynamic_pointer_cast<T>(*it);
if (*it && rtn != NULL)
{
return rtn;
}
}
}
/// A template function to check if an entity has a specific component.
/// Pass a component name in <> that you wish to retrive.
/// @returns true or false depending on the components of the entity;
/// ### Example of usage:
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~.cpp
/// if(entityName->checkComponent<BoxCollider>() == true)
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template<typename T>
bool checkComponent()
{
for (auto it = components.begin(); it != components.end(); it++)
{
std::shared_ptr<T> rtn = std::dynamic_pointer_cast<T>(*it);
if (*it == rtn)
{
return true;
}
}
return false;
}
/// A template function to add a component to an entity.
/// Possible to pass up to 3 parametrs
/// @returns std::shared_ptr<T> componentName;
/// ### Example of usage:
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~.cpp
/// std::shared_ptr<Renderer> entityRenderer = entityName->addComponent();
/// std::shared_ptr<Camera> entityCamera = entityName->addComponent(rend::vec3 position, rend::vec3 rotation);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template<typename T>
std::shared_ptr<T> addComponent()
{
std::shared_ptr<T> rtn = std::make_shared<T>();
rtn->entity = self;
components.push_back(rtn);
rtn->onInit();
return rtn;
}
/// A template function to add a component with one parameter to an entity.
/// @see std::shared_ptr<T> addComponent()
template<typename T, typename A>
std::shared_ptr<T> addComponent(A _a)
{
std::shared_ptr<T> rtn = std::make_shared<T>(_a);
rtn->entity = self;
components.push_back(rtn);
rtn->onInit(_a);
return rtn;
}
/// A template function to add a component with two parameters to an entity.
/// @see std::shared_ptr<T> addComponent()
template<typename T, typename A, typename B>
std::shared_ptr<T> addComponent(A _a, B _b)
{
std::shared_ptr<T> rtn = std::make_shared<T>(_a, _b);
rtn->entity = self;
components.push_back(rtn);
rtn->onInit(_a, _b);
return rtn;
}
/// A template function to add a component with three parameters to an entity.
/// @see std::shared_ptr<T> addComponent()
template<typename T, typename A, typename B, typename C>
std::shared_ptr<T> addComponent(A _a, B b, C _c)
{
std::shared_ptr<T> rtn = std::make_shared<T>(_a, _b, _c);
rtn->entity = self;
components.push_back(rtn);
rtn->onInit(_a, _b, _c);
return rtn;
}
};
}
#endif | true |
2618f911f3a5d507c3ce91b40b06ac89eb59fba3 | C++ | evyatarh/Cpp-projects | /Transportation network/Position.cpp | UTF-8 | 1,107 | 3.25 | 3 | [] | no_license |
#include "Position.h"
/******************** c'tor method **************************/
Position::Position():x(0){}
/******************** c'tor method **************************/
Position::Position(const int &i):x(i){}
/******************** copy c'tor method **************************/
Position::Position(const Position &pos):x(pos.x){}
/******************** getX method **************************/
int Position::getX()const{ return x;}
/******************** equal method **************************/
bool Position::equal(const Position &a)const{
if((this->x==a.getX()))return true;
return false;
}
/******************** operator= method **************************/
Position& Position::operator=(Position &pos){
this->x = pos.x;
return *this;
}
/******************** equal method **************************/
bool Position::equal(const int &a)const{
if((this->x==a))return true;
return false;
}
/******************** setX method **************************/
void Position::setX(const char &i){ x=i;}
/******************** d'tor method **************************/
Position::~Position() {}
| true |
158ac0448104945e9e64e79e82d93fc17829f20d | C++ | iTXCode/Review | /Linux/process/fork/nfork.cc | UTF-8 | 294 | 2.8125 | 3 | [] | no_license | #include<iostream>
#include<unistd.h>
int main(){
pid_t pid;
int i=0;
for(i=0;i<5;i++){
pid=fork();
if(pid==0){
break;
}
}
sleep(i);
if(i<5){
printf("I'm child!,pid=%d,ppid=%d\n",getpid(),getppid());
}else{
printf("I'm father!\n");
}
return 0;
}
| true |
3261c15a9004b7ff7d953baa74048e265e0fd7b4 | C++ | rameshrajagopal/thrift-cluster | /common/request.h | UTF-8 | 484 | 2.609375 | 3 | [] | no_license | #ifndef _REQUEST_H_INCLUDED_
#define _REQUEST_H_INCLUDED_
#include <vector>
#include <request.h>
using namespace std;
class Request
{
public:
Request(int rnum, const string & r, Response & res):
num(rnum), req(r), response(res) {}
void updateResponse(int slaveId, int errnum)
{
response.update(slaveId, errnum);
}
private:
int num;
const string & req;
Response & response;
std::mutex mutex_;
};
#endif /*_REQUEST_H_INCLUDED_*/
| true |
99efb77816922510e01a15782ae21b29871e829a | C++ | marcosrodrigueza/DLRSHIP-miniproject | /Project/spacecraft.cpp | UTF-8 | 2,475 | 3.0625 | 3 | [] | no_license | #include "spacecraft.h"
SpaceCraft::SpaceCraft(int cm, float pri, int prop, string rn, string o, bool b)
{
crewMax = cm;
price = pri;
propulsion = prop;
regNum = rn;
owner = o;
av_sale = b;
}
void SpaceCraft::show()
{
//
}
void SpaceCraft::transaction(bool &create_sale)
{
string new_owner = "non-sense";
string security_copy = this->getOwner(); // we store a copy of actual owner until transaction checked
bool accepted = false;
//
create_sale = false;
cout << "Please, introduce the buyer's id: ";
cin >> new_owner; //we don't check yet!
this-> setOwner(new_owner);
accepted = this->checkSale(new_owner);
if(accepted == false)
{
this->setOwner(security_copy);
cout << "Transaction error" << endl;
}
else
{
av_sale = false;
create_sale = true;
cout << "---Done succesfully---" << endl;
}
}
bool SpaceCraft::checkSale(string check) //checks that the owner in the object equals the one introduced.
{
bool checker = false;
if(this->getOwner() == check)
{
checker = true;
}
return checker;
}
string SpaceCraft::getReg()const
{
return regNum;
}
string SpaceCraft::getOwner()const
{
return owner;
}
void SpaceCraft::setOwner(const string & newOwner)
{
owner = newOwner;
}
bool SpaceCraft::getAvailible()const
{
return av_sale;
}
void SpaceCraft::editBaseParameters()
{
float new_price = 0;
unsigned int new_crew = 0;
int new_propulsion = 0;
//
cout << " New parameters of this Spacecraft:" << endl << "(Write 0 in the ones that you don't want to change)" << endl;
cout << " $ (units): ";
cin >> new_price;
if(new_price != 0)
price = new_price;
cout << "Máximum crew -(press 0 if this is a Fighter/Destroyer): ";
cin >> new_crew;
if(new_crew != 0)
crewMax = new_crew;
cout << "////////////////////////" << endl;
cout << " 1. Warp Drive. " << endl << " 2. Trace compressor" << endl << " 3. FTL engine." << endl;
cout << " 4. Solar sails." << endl << " 5. Ion engine." << endl;
cout << "////////////////////////" << endl;
cout << "Propulsion type: ";
cin >> new_propulsion;
if(new_propulsion != 0)
propulsion = new_propulsion;
}
void SpaceCraft::editSpacecraft()
{
//void editSpacecraft()
}
void SpaceCraft::saveCraft(ofstream &output)
{
//nothing to be added
}
SpaceCraft::~SpaceCraft()
{
//
}
| true |
89ddb133b9a921646fe082e12260a413fdad0f1e | C++ | lamductan/DCTC | /visualization/graph.cpp | UTF-8 | 3,274 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include "graph.h"
#include "draw_utils.h"
/* Node */
Node::Node(long double x, long double y, long double r, long double angle, int node_type)
: x_(x), y_(y), r_(r), angle_(angle), node_type_(node_type) {}
void Node::draw(CImg<unsigned char>& img) {
x = x_*SCALE;
y = y_*SCALE;
r = r_*SCALE;
const unsigned char* color;
unsigned int node_size = RELAY_NODE_SIZE;
if (node_type_ == 4) {
color = draw_utils::RED;
node_size = SENSING_NODE_SIZE;
}
else if (node_type_ == 8) color = draw_utils::GREEN; // type1 relay
else if (node_type_ == 9) color = draw_utils::YELLOW; // type2 relay
else if (node_type_ == 10) color = draw_utils::BLUE; // type3 (short edge) relay
else if (node_type_ == 11) color = draw_utils::CYAN; // type4 relay
img.draw_circle(x, y, node_size, color);
if (node_type_ == 4) {
draw_utils::draw_sector_1(img, x, y, r, angle_, 0, color, FILL_OPACITY);
}
}
/* Graph */
Graph::Graph() {}
void Graph::set_targets(const std::vector<std::pair<long double, long double>>& targets) {targets_ = targets;}
void Graph::draw_targets(const std::vector<std::pair<long double, long double>>& targets) {
for(const std::pair<long double, long double>& target : targets) {
img_.draw_circle((target.first - diff_w)*SCALE, (target.second - diff_h)*SCALE, POINT_SIZE, draw_utils::BLACK);
}
}
void Graph::draw(const std::string& save_img_path) {
for(std::pair<Point, Point>& edge : edges_) {
draw_utils::draw_line(
img_,
edge.first.x_*SCALE, edge.first.y_*SCALE,
edge.second.x_*SCALE, edge.second.y_*SCALE,
draw_utils::BLACK, LINE_WIDTH);
}
for(Node& node : nodes_) {
node.draw(img_);
}
img_.save(save_img_path.c_str());
}
Graph Graph::load(const std::string& path) {
std::ifstream fin;
fin.open(path);
Graph graph;
long double min_x = INT_MAX;
long double max_x = 0;
long double min_y = INT_MAX;
long double max_y = 0;
fin >> graph.n_nodes_;
long double r;
for(int i = 0; i < graph.n_nodes_; ++i) {
long double x, y, angle;
int node_type;
fin >> x >> y >> r >> angle >> node_type;
min_x = std::min(min_x, x);
max_x = std::max(max_x, x);
min_y = std::min(min_y, y);
max_y = std::max(max_y, y);
Node node(x, y, r, angle, node_type);
graph.nodes_.push_back(node);
}
graph.w = max_x - min_x + r*3;
graph.h = max_y - min_y + r*3;
long double diff_w = min_x - r*1.5;
long double diff_h = min_y - r*1.5;
graph.diff_w = diff_w;
graph.diff_h = diff_h;
for(int i = 0; i < graph.n_nodes_; ++i) {
graph.nodes_[i].x_ -= diff_w;
graph.nodes_[i].y_ -= diff_h;
}
fin >> graph.m_edges_;
for(int i = 0; i < graph.m_edges_; ++i) {
Point p1, p2;
fin >> p1.x_ >> p1.y_;
fin >> p2.x_ >> p2.y_;
p1.x_ -= diff_w; p1.y_ -= diff_h;
p2.x_ -= diff_w; p2.y_ -= diff_h;
graph.edges_.push_back({p1, p2});
}
fin.close();
graph.img_ = CImg<unsigned char>(graph.w*100, graph.h*100, 1, 3);
graph.img_.fill(255);
return graph;
}
| true |
fc6212ae2163a549a72e8597e7ce592789d8fa1c | C++ | EggyJames/Leetcode | /75.cpp | UTF-8 | 619 | 3 | 3 | [] | no_license | class Solution {
public:
void sortColors(vector<int>& nums) {
int l = 0,r = nums.size()-1;
if(r == 0 || r < 0)
return;
for(int i = 0;i<=r;){
if(nums[i] == 0)
{
int temp = nums[l];
nums[l] = 0;
nums[i] = temp;
l++;
i++;
}else if(nums[i] == 2){
int temp = nums[r];
nums[r] = 2;
nums[i] = temp;
r--;
}else
i++;
if(r<l)
break;
}
}
};
| true |
a6d9b8ae4132497cf0fed3f5a476c37ec53c2337 | C++ | Essoz/CS225_ZJUI | /Midterm1 templates/kaoshi/ex6/ex6.h | UTF-8 | 1,032 | 3.15625 | 3 | [] | no_license |
#ifndef ex6_h
#define ex6_h
template<class T> class pair{
public:
pair(){
pair_t = 0;
pair_n = 0;
}
pair(T t, int n):pair_t(t), pair_n(n){}
T get_t(){
return pair_t;
}
int get_n(){
return pair_n;
}
void set_t(T t){
pair_t = t;
}
void set_n(int n){
pair_n = n;
}
void print_pairs();
private:
T pair_t;
int pair_n;
};
template<class T> class fifo
{
public:
fifo(int size = 10);
virtual ~fifo();
pair<T> &operator[](int index);
int getlength(void);
bool isempty(void);
pair<T> back(void);
pair<T> front(void);
void pushback(pair<T> value);
pair<T> popfront(void);
T pop_vip(void); //finish this function in the bottom of ex6.cpp
private:
int maxsize, minsize;
int first, last;
int numitems;
pair<T> *reprarray;
void allocate(void);
void deallocate(void);
};
#endif
| true |
e4eb2d8636430e954a38f95d4ffffd6960569942 | C++ | S-John-S/CSN-212_Tutorial-3 | /interval_tree.h | UTF-8 | 4,269 | 2.796875 | 3 | [
"MIT"
] | permissive | #ifndef E_INTERVAL_TREE
#define E_INTERVAL_TREE
#include "misc.h"
#include "TemplateStack.H"
#include <math.h>
#include <limits.h>
#include <iostream.h>
// The interval_tree.h and interval_tree.cc files contain code for
// interval trees implemented using red-black-trees as described in
// the book _Introduction_To_Algorithms_ by Cormen, Leisserson,
// and Rivest.
// CONVENTIONS:
// Function names: Each word in a function name begins with
// a capital letter. An example funcntion name is
// CreateRedTree(a,b,c). Furthermore, each function name
// should begin with a capital letter to easily distinguish
// them from variables.
//
// Variable names: Each word in a variable name begins with
// a capital letter EXCEPT the first letter of the variable
// name. For example, int newLongInt. Global variables have
// names beginning with "g". An example of a global
// variable name is gNewtonsConstant.
#ifndef MAX_INT
#define MAX_INT INT_MAX // some architechturs define INT_MAX not MAX_INT
#endif
// The Interval class is an Abstract Base Class. This means that no
// instance of the Interval class can exist. Only classes which
// inherit from the Interval class can exist. Furthermore any class
// which inherits from the Interval class must define the member
// functions GetLowPoint and GetHighPoint.
//
// The GetLowPoint should return the lowest point of the interval and
// the GetHighPoint should return the highest point of the interval.
class Interval {
public:
Interval();
virtual ~Interval();
virtual int GetLowPoint() const = 0;
virtual int GetHighPoint() const = 0;
virtual void Print() const;
};
class IntervalTreeNode {
friend class IntervalTree;
public:
void Print(IntervalTreeNode*,
IntervalTreeNode*) const;
IntervalTreeNode();
IntervalTreeNode(Interval *);
~IntervalTreeNode();
protected:
Interval * storedInterval;
int key;
int high;
int maxHigh;
int red; /* if red=0 then the node is black */
IntervalTreeNode * left;
IntervalTreeNode * right;
IntervalTreeNode * parent;
};
struct it_recursion_node {
public:
/* this structure stores the information needed when we take the */
/* right branch in searching for intervals but possibly come back */
/* and check the left branch as well. */
IntervalTreeNode * start_node;
unsigned int parentIndex;
int tryRightBranch;
} ;
class IntervalTree {
public:
IntervalTree();
~IntervalTree();
void Print() const;
Interval * DeleteNode(IntervalTreeNode *);
IntervalTreeNode * Insert(Interval *);
/*IntervalTreeNode * Search(Interval *);*/
/*this function is executed in the enumeration as multiple outputs of*/
/*overlaps in the function parameters*/
IntervalTreeNode * GetPredecessorOf(IntervalTreeNode *) const;
IntervalTreeNode * GetSuccessorOf(IntervalTreeNode *) const;
TemplateStack<void *> * Enumerate(int low, int high) ;
void CheckAssumptions() const;
protected:
/* A sentinel is used for root and for nil. These sentinels are */
/* created when ITTreeCreate is caled. root->left should always */
/* point to the node which is the root of the tree. nil points to a */
/* node which should always be black but has aribtrary children and */
/* parent and no key or info. The point of using these sentinels is so */
/* that the root and nil nodes do not require special cases in the code */
IntervalTreeNode * root;
IntervalTreeNode * nil;
void LeftRotate(IntervalTreeNode *);
void RightRotate(IntervalTreeNode *);
void TreeInsertHelp(IntervalTreeNode *);
void TreePrintHelper(IntervalTreeNode *) const;
void FixUpMaxHigh(IntervalTreeNode *);
void DeleteFixUp(IntervalTreeNode *);
void CheckMaxHighFields(IntervalTreeNode *) const;
int CheckMaxHighFieldsHelper(IntervalTreeNode * y,
const int currentHigh,
int match) const;
private:
unsigned int recursionNodeStackSize;
it_recursion_node * recursionNodeStack;
unsigned int currentParent;
unsigned int recursionNodeStackTop;
};
#endif
| true |
96a687b4dad834175259b7de0bba6e1e9a0d7c0e | C++ | tzn893/tony-render-pipeline | /Common/Drawable.h | UTF-8 | 412 | 2.6875 | 3 | [] | no_license | #pragma once
#include <vector>
#include "geometry.h"
class Drawable {
public:
virtual std::vector<int> face(int nface) = 0;
virtual int nfaces() = 0;
virtual Vec3f vert(int nvert) = 0;
virtual int nverts() = 0;
virtual ~Drawable() {}
virtual Vec2f uv(int nvert) = 0;
virtual Vec3f normal(int nvert) { return Vec3f(0, 0, 0); }
bool isWithNormal() { return withNormal; }
protected:
bool withNormal;
}; | true |
36fbe3a5722e2eec0fd51c9687b2786bc9109ae9 | C++ | methusael13/phy-ray | /phyray_lib/src/core/integrator/sampler.cpp | UTF-8 | 4,815 | 2.53125 | 3 | [
"Apache-2.0",
"BSD-2-Clause"
] | permissive | #include <core/integrator/sampler.h>
namespace phyr {
// Sampler definitions
#define RESET_OFFSETS (array1DOffset = array2DOffset = 0)
Sampler::~Sampler() {}
void Sampler::startPixel(const Point2i& pt) {
currentPixel = pt;
currentPixelSampleIndex = 0;
// Reset array offsets for next pixel sample
RESET_OFFSETS;
}
bool Sampler::startNextSample() {
RESET_OFFSETS;
return ++currentPixelSampleIndex < samplesPerPixel;
}
bool Sampler::setSampleIndex(int64_t sampleIdx) {
RESET_OFFSETS;
currentPixelSampleIndex = sampleIdx;
return currentPixelSampleIndex < samplesPerPixel;
}
void Sampler::request1DArray(int n) {
ASSERT(n == refineRequestCount(n));
samples1DArraySizes.push_back(n);
sampleArray1D.push_back(std::vector<Real>(n * samplesPerPixel));
}
void Sampler::request2DArray(int n) {
ASSERT(n == refineRequestCount(n));
samples2DArraySizes.push_back(n);
sampleArray2D.push_back(std::vector<Point2f>(n * samplesPerPixel));
}
const Real* Sampler::get1DArray(int n) {
if (array1DOffset == sampleArray1D.size())
return nullptr;
return &sampleArray1D[array1DOffset++][n * currentPixelSampleIndex];
}
const Point2f* Sampler::get2DArray(int n) {
if (array2DOffset == sampleArray2D.size())
return nullptr;
return &sampleArray2D[array2DOffset++][n * currentPixelSampleIndex];
}
CameraSample Sampler::getCameraSample(const Point2i& pRaster) {
CameraSample cs;
// Order matters, do not modify
cs.pFilm = Point2f(pRaster) + getNextSample2D();
cs.pLens = getNextSample2D();
return cs;
}
#undef RESET_OFFSETS
#define RESET_OFFSETS (current1DDimension = current2DDimension = 0)
// PixelSampler definitions
PixelSampler::PixelSampler(int64_t samplesPerPixel, int nSampledDimensions)
: Sampler(samplesPerPixel),
current1DDimension(0), current2DDimension(0) {
for (int i = 0; i < nSampledDimensions; i++) {
samples1D.push_back(std::vector<Real>(samplesPerPixel));
samples2D.push_back(std::vector<Point2f>(samplesPerPixel));
}
}
bool PixelSampler::startNextSample() {
RESET_OFFSETS;
return Sampler::startNextSample();
}
bool PixelSampler::setSampleIndex(int64_t sampleIdx) {
RESET_OFFSETS;
return Sampler::setSampleIndex(sampleIdx);
}
Real PixelSampler::getNextSample1D() {
if (current1DDimension < samples1D.size())
return samples1D[current1DDimension++][currentPixelSampleIndex];
else
return rng.uniformReal();
}
Point2f PixelSampler::getNextSample2D() {
if (current2DDimension < samples2D.size())
return samples2D[current2DDimension++][currentPixelSampleIndex];
else
return Point2f(rng.uniformReal(), rng.uniformReal());
}
#undef RESET_OFFSETS
// GlobalSampler definitions
void GlobalSampler::startPixel(const Point2i& pt) {
Sampler::startPixel(pt);
// Reset data members
dimension = 0;
intervalSampleIndex = getIndexForSample(0);
// Compute arrayEndDim
arrayEndDim = arrayStartDim + sampleArray1D.size() + 2 * sampleArray2D.size();
// Compute 1D array samples
for (size_t i = 0; i < samples1DArraySizes.size(); i++) {
int nSamples = samples1DArraySizes[i] * samplesPerPixel;
for (int j = 0; j < nSamples; j++) {
int64_t idx = getIndexForSample(j);
sampleArray1D[i][j] = sampleDimension(idx, arrayStartDim + i);
}
}
// Compute 2D array samples
int dOffset = arrayStartDim + samples1DArraySizes.size();
for (size_t i = 0; i < samples2DArraySizes.size(); i++) {
int nSamples = samples2DArraySizes[i] * samplesPerPixel;
for (int j = 0; j < nSamples; j++) {
int64_t idx = getIndexForSample(j);
sampleArray2D[i][j].x = sampleDimension(idx, dOffset);
sampleArray2D[i][j].y = sampleDimension(idx, dOffset + 1);
}
dOffset += 2;
}
}
bool GlobalSampler::startNextSample() {
dimension = 0;
intervalSampleIndex = getIndexForSample(currentPixelSampleIndex + 1);
return Sampler::startNextSample();
}
bool GlobalSampler::setSampleIndex(int64_t sampleIdx) {
dimension = 0;
intervalSampleIndex = getIndexForSample(sampleIdx);
return Sampler::setSampleIndex(sampleIdx);
}
Real GlobalSampler::getNextSample1D() {
if (dimension >= arrayStartDim && dimension < arrayEndDim)
dimension = arrayEndDim;
return sampleDimension(intervalSampleIndex, dimension++);
}
Point2f GlobalSampler::getNextSample2D() {
if (dimension + 1 >= arrayStartDim && dimension < arrayEndDim)
dimension = arrayEndDim;
Point2f sample(sampleDimension(intervalSampleIndex, dimension),
sampleDimension(intervalSampleIndex, dimension + 1));
dimension += 2;
return sample;
}
} // namespace phyr
| true |
9853303323c22c6cd7ff9ec592cd759391350da1 | C++ | sergone/C-lab-5 | /src/task3.cpp | UTF-8 | 887 | 3.171875 | 3 | [] | no_license | #include <time.h>
#include <stdlib.h>
#include <string.h>
#define COUNT_WORDS_MAX 20
#define LENGTH_WORDS_MAX 30
char *mixChars(char *in, char *out)
{
int len = 0; // length of word
while (*(in + len) != ' ' && *(in + len) != '\n' && *(in + len) != '\0')
{
*(out + len) = *(in + len);
len++;
}
char temp = 0;
int randNum = 0;
for (int j = 1; j < len - 1; j++)
{
temp = *(out + j);
randNum = j + rand() % (len - 1 - j);
*(out + j) = *(out + randNum);
*(out + randNum) = temp;
}
return out;
}
char *mixLine(char *instr, char * outstr)
{
for (int i = 0; i <= strlen(instr); i++)
{
if (*(instr + i) != ' ' && *(instr + i) != '\0' && *(instr + i) != '\n' && (i == 0 || *(instr + i - 1) == ' '))
mixChars(instr + i, outstr + i);
else if (*(instr + i) == ' ' || *(instr + i) == '\0' || *(instr + i) == '\n')
*(outstr + i) = *(instr + i);
}
return outstr;
} | true |
ee297a881a7ca93a3dd2fc35de0a826198fea156 | C++ | mariogrieco/Estructura-de-Datos | /Helpers/Templates.h | UTF-8 | 15,400 | 2.671875 | 3 | [] | no_license | #ifndef _TEMPLATES_H_
#define _TEMPLATES_H_
using namespace std;
/*
Nombres Descripción
memcpy copia n bytes entre dos áreas de memoria que no deben solaparse
memmove copia n bytes entre dos áreas de memoria; al contrario que memcpy las áreas pueden solaparse
memchr busca un valor a partir de una dirección de memoria dada y devuelve un puntero a la primera ocurrencia del valor buscado o NULL si no se encuentra
memcmp compara los n primeros caracteres de dos áreas de memoria
memset sobre escribe un área de memoria con un patrón de bytes dado
strcat añade una cadena al final de otra
strncat añade los n primeros caracteres de una cadena al final de otra
strchr localiza un carácter en una cadena, buscando desde el principio
strrchr localiza un carácter en una cadena, buscando desde el final
strcmp compara dos cadenas alfabéticamente ('a'!='A')
strncmp compara los n primeros caracteres de dos cadenas numéricamente ('a'!='A')
strcoll compara dos cadenas según la colación actual ('a'=='A')
strcpy copia una cadena en otra
strncpy copia los n primeros caracteres de una cadena en otra
strerror devuelve la cadena con el mensaje de error correspondiente al número de error dado
strlen devuelve la longitud de una cadena
strspn devuelve la posición del primer carácter de una cadena que no coincide con ninguno de los caracteres de otra cadena dada
strcspn devuelve la posición del primer carácter que coincide con alguno de los caracteres de otra cadena dada
strpbrk encuentra la primera ocurrencia de alguno de los caracteres de una cadena dada en otra
strstr busca una cadena dentro de otra
strtok parte una cadena en una secuencia de tokens
strxfrm transforma una cadena en su forma de colación (??)
strrev invierte una cadena
*/
template <class T>
int generateFromBinary(char* file_name,T **Objects,int &largo);
// template <class T>
// void reallocate(T**,int);
// template <class T>
// void reallocate(T**,int);
template <class T>
void quickSort();
template <class T>
void radixsort(T&,int);
template <class T>
void shakerSort(T&,int);
template <class T>
int bloques(T*,T,int);
template <class T,class K>
int* binaria(T,K,int);
template <class T>
void inter(T &, T &);
template <class T>
void seleccionDirecta(T&, int,bool ascendente = true);
template <class T>
void insercionDirecta(T &,int,bool ascendente = true);
template <class T>
void burbuja(T &a, int largo, bool ascendente = true);
template <class T>
class Colas_Array;
template <class T>
class Merge;
// template <class T>
// class Merge {
// private:
// fstream F1;
// fstream F2;
// fstream DATA;
// fstream RESPALDO;
// fstream SALIDA;
// T *Objects;
// int line;
// int length;
// int arralen;
// public:
// Merge(){
// }
// Merge(char *nameFile,int largo){
// DATA.open(nameFile,ios::binary | ios::out | ios::in );
// this->setlargo();
// DATA.clear();
// this->arralen = largo;
// };
// void imprimir(){
// for (size_t i = 0; i < this->arralen; i++) {
// this->Objects[i].imprimir();
// }
// }
// void open(const std::_Ios_Openmode &t){
// }
// T* getArray(){
// return this->Objects;
// }
// int getLargo(){
// return this->arralen;
// }
// void crearArray(){
// this->posicionar(0);
// int contador = 0;
// int max = 1;
// this->Objects = new T;
// while ( true ) {
// T *bufer = new T;
// DATA.read((char*)bufer,sizeof(T));
// if ( !DATA.eof() ) {
// if ( contador == max ) {
// this->Objects = (T*)(realloc((this->Objects),sizeof(T)*(max+10)));
// max=max+10;
// }
// this->Objects[contador] = *bufer;
// // this->Objects[contador].imprimir();
// contador++;
// }else{
// break;
// }
// }
// this->length = contador;
// }
// void leer(T &bufer){
// DATA.read((char*)&bufer,sizeof(T));
// }
// int setlargo(){
// this->length = 0;
// while ( true ) {
// T temp;
// DATA.read((char*)&temp,sizeof(T));
// if ( DATA.eof()) {
// this->length--;
// return 1;
// }else{
// this->length++;
// }
// }
// }
// void escribir(T &data){
// DATA.write((char*)&data,sizeof(T));
// }
// void clear(){
// DATA.clear();
// DATA.seekg(0,ios::beg);
// }
// void posicionar(int pos){
// clear();
// DATA.seekg(sizeof(T)*pos,ios::beg);
// }
// void generateFromBinary(){
// // generateFromBinary(this->Objects,this->lines);
// }
// void mesclar(){
// }
// void separar(){
// }
// void getUL(){
// T INTER;
// posicionar(length);
// leer(INTER);
// cout << INTER.nombre << endl;
// }
// void saveTObinary(){
// generateFromBinary("Cliente.dat",this->Objects,this->arralen);
// saveTObinary(this->Objects,this->arralen,"Cliente.dat");
// }
// void seleccionDirecta(){
// int menor = 0;
// int pos_T;
// int mayor = length;
// T bufer2;
// T min;
// T INTER;
// r:
// posicionar(menor);
// leer(min);
// pos_T = menor;
// for (int i = menor+1; i <= mayor; i++) {
// leer(bufer2);
// if ( min>&bufer2 ) {
// pos_T = i;
// min = bufer2;
// }
// }
// posicionar(menor);
// leer(INTER);
// posicionar(menor);
// escribir(min);
// posicionar(pos_T);
// escribir(INTER);
// menor++;
// if ( menor < mayor) {
// goto r;
// }
// }
// void shell(){
// }
// void inter(int pos1, int pos2){
// }
// void ver(int t){
// Objects[t].imprimir();
// }
// int bloques(int key){
// int pos = 0;
// int increment = sqrt(this->arralen);
// RE:
// for (int i = pos; i < this->arralen; i+=increment) {
// if ( this->Objects[i] == key ) {
// return i;
// }
// }
// pos++;
// if ( pos < ((this->arralen-1)/2)-1) {
// goto RE;
// }
// return -1;
// }
// int verBusqda(int key){
// for (int i = 0; i < this->arralen; i++) {
// if ( this->Objects[i].id == key ) {
// this->Objects[i].imprimir();
// }
// }
// }
// void verBusqdaCI(int key){
// for (int i = 0; i < this->arralen; i++) {
// if ( this->Objects[i].ced == key ) {
// this->Objects[i].imprimir();
// }
// }
// }
// ~Merge(){
// DATA.close();
// F1.close();
// F2.close();
// DATA.close();
// RESPALDO.close();
// SALIDA.close();
// }
// };
//
// template <class T,class K>
// int* secuencial(T array, K key, int length){
// int *pos_T = new int[3];
// int n = 1;
// int tam = 3;
// int numbers = 0;
// int bandera = false;
//
// if ( array[0] > key) return NULL;
// if ( array[length-1] < key) return NULL;
//
// for (int i = 0; i < length; i++) {
// if ( array[i] > key && bandera == true ){
// goto retu;
// }
// else if ( array[i] > key ){
// return NULL;
// }
// if ( array[i] == key ){
// pos_T[n] = i;
// n++;
// numbers++;
// bandera = true;
// }
// if ( n >= tam ) {
// pos_T = reallocate(pos_T,sizeof(int)*n+1);
// tam = n+1;
// }
// }
// retu:
// pos_T[0] = numbers;
// return pos_T;
//
// }
template <class T>
void hashModulo(){
}
template <class T>
void hashRaiz(){
}
template <class T>
void hashPlegamiento(){
}
template <class T>
void hasTruncamiento(){
}
template <class T>
void tablaHasH(){
}
template <class T>
void quickSort(){
}
//crearr!
// template <class T,class A,class B>
// int generateFromFile(T **Object1, char *file_name, int &l3){
// l1 = l2 = l3 = 0;
// fstream DATA(file_name,ios::in);
// DATA.clear();
// DATA.seekg(0,ios::beg);
// int tipe = 0;
// if ( DATA.fail() ) {
// cout << "error leyendo Data ";
// exit(0);
// return 0;
// }
// int contador = 0;
// int max = 1;
// (*Object1) = new T;
// (*Object2) = new B;
// (*Object3) = new A;
// while ( true ) {
// char a[256];
// int d;
// a:
// DATA.getline(a,sizeof(char)*256);
// if ( !DATA.eof() ) {
// if ( strcmp(a,"SQ2") != 0 && strcmp(a,"SQ1") != 0 ) {
// if ( contador == max && tipe == 0) {
// (*Object1) = (T*)(realloc((*Object1),sizeof(T)*(max+10)));
// max=max+10;
// }
// if ( contador == max && tipe == 1) {
// (*Object2) = (B*)(realloc((*Object2),sizeof(T)*(max+10)));
// max=max+10;
// }
// if ( contador == max && tipe == 2) {
// (*Object3) = (A*)(realloc((*Object3),sizeof(T)*(max+10)));
// max=max+10;
// }
// /* code */
// }else{
// tipe++;
// contador = 0;
// max = 1;
// goto a;
// }
// if ( tipe == 0 && strcmp(a,"SQ2") != 0 && strcmp(a,"SQ1") != 0) {
// char b[256];
// strcpy(b,nextTokenNizer(a,','));
// (*Object1)[contador].ced = atoi(b);
// strcpy(b,nextTokenNizer(a,','));
// strcpy((*Object1)[contador].nom,b);
// l1++;
// }
// if ( tipe == 1 && strcmp(a,"SQ2") != 0 && strcmp(a,"SQ1") != 0) {
// char b[256];
// strcpy(b,nextTokenNizer(a,','));
// (*Object2)[contador].id = atoi(b);
// strcpy(b,nextTokenNizer(a,','));
// strcpy((*Object2)[contador].nom,b);
// strcpy(b,nextTokenNizer(a,','));
// (*Object2)[contador].hora_am1 = atoi(b);
// strcpy(b,nextTokenNizer(a,','));
// (*Object2)[contador].hora_am2 = atoi(b);
// strcpy(b,nextTokenNizer(a,','));
// (*Object2)[contador].hora_pm1 = atoi(b);
// strcpy(b,nextTokenNizer(a,','));
// (*Object2)[contador].hora_pm2 = atoi(b);
// l2++;
// }
// if ( tipe == 2 && strcmp(a,"SQ2") != 0 && strcmp(a,"SQ1") != 0 ) {
// char b[256];
// strcpy(b,nextTokenNizer(a,','));
// (*Object3)[contador].id = atoi(b);
// strcpy(b,nextTokenNizer(a,','));
// (*Object3)[contador].ced = atoi(b);
// strcpy(b,nextTokenNizer(a,','));
// strcpy((*Object3)[contador].fecha,b);
// l3++;
// /*
// NORA EL FORMATO DE ARCHIVO NO TENIA , EN ESTE PUNTO REQUERIA
// GUARDAR EL QUE QUDA
// SI SE USA , atoi dara error!;
// */
// (*Object3)[contador].hora = atoi(a);
// }
// contador++;
// // cin.get();
// // // add method using read
// // //end
// }
// else{
// break;
// }
// }
// DATA.close();
// return 1;
// }
template <class T>
int generateFromBinary(char* file_name,T **Objects,int &largo){
fstream DATA(file_name,ios::in | ios::binary );
if ( DATA.fail() ) {
return 0;
}
int contador = 0;
int max = 1;
(*Objects) = new T;
while ( true ) {
T *bufer = new T;
DATA.read((char*)bufer,sizeof(T));
if ( !DATA.eof() ) {
if ( contador == max ) {
(*Objects) = (T*)(realloc((*Objects),sizeof(T)*(max+10)));
max=max+10;
}
(*Objects)[contador] = *bufer;
contador++;
// cin.get();
// add method using read
//end
}else{
break;
}
}
largo = contador;
DATA.close();
return 1;
}
template <class T>
int saveTObinary(T* Array, int size,char* outName){
fstream F(outName, ios::out | ios::binary );
if ( F.fail() ) {
return 0;
}
for (int i = 0; i < size; i++) {
T *bufer = new T;
F.write((char*)&Array[i],sizeof(T));
}
F.close();
return 1;
}
#endif
| true |
2eec67ef7acdd2e7d37e853a9cd6fa67ec1831e1 | C++ | panda959595/boj_algorithm | /boj_algorithm/2166.cpp | UTF-8 | 497 | 3.15625 | 3 | [] | no_license | #include <iostream>
using namespace std;
struct point {
double x, y;
};
double outer(point p1, point p2, point p3) {
return (p2.x - p1.x) * (p3.y - p1.y) - (p3.x - p1.x) * (p2.y - p1.y);
}
int main() {
int n;
cin >> n;
point arr[10005];
for (int i = 0; i < n; i++) {
cin >> arr[i].x >> arr[i].y;
}
double ans = 0;
for (int i = 1; i < n - 1; i++) {
ans += outer(arr[0], arr[i], arr[i + 1]) / 2;
}
ans = abs(ans);
cout << fixed;
cout.precision(1);
cout << ans << endl;
return 0;
} | true |
8342452b6e8df869dcade4e316154c87310322d2 | C++ | softchicken/POLSKI-SPOJ | /1909 SUMY WIELOKROTNE.cpp | UTF-8 | 471 | 2.71875 | 3 | [] | no_license | /*
POLISH SPOJ
http://pl.spoj.com/problems/KC008/
https://github.com/softchicken/
*/
#include <iostream>
using namespace std;
int main()
{
long long int numberSeries,buffer=0,bufferAll=0;
while(cin>>numberSeries)
{
if(numberSeries!=0) buffer = buffer + numberSeries;
else
{
cout<<buffer<<endl;
bufferAll = bufferAll + buffer;
buffer = 0;
}
}
cout<<bufferAll<<endl;
return 0;
}
| true |
bf722a3e96c6c5484efbebb5d8d7e9988f14f3d4 | C++ | G4m3r-2003/arduino | /lib_ard/Pin.h | UTF-8 | 522 | 2.875 | 3 | [] | no_license | #ifndef LIB_ARD_PIN
#define LIB_ARD_PIN
#include "Arduino.h"
#include "PinType.h"
namespace lib_ard
{
class Pin
{
private:
unsigned short _number;
protected:
/*funzione di appoggio usata da input e output
pins per chiamare le read di basso livello*/
unsigned short int read (PinType tipoPin) const;
public:
Pin(const unsigned short &number);
/*restituisce il numero del pin hardware di arduino*/
unsigned short int getNumber() const;
};
}
#endif
| true |
e33ab97d7bd419aed898b99ab05e079aa91d37dd | C++ | fmidev/rack | /src/drain/util/StringMapper.h | UTF-8 | 9,667 | 2.5625 | 3 | [
"MIT"
] | permissive | /*
MIT License
Copyright (c) 2017 FMI Open Development / Markus Peura, first.last@fmi.fi
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.
*/
/*
Part of Rack development has been done in the BALTRAD projects part-financed
by the European Union (European Regional Development Fund and European
Neighbourhood Partnership Instrument, Baltic Sea Region Programme 2007-2013)
*/
#ifndef STRINGMAPPER_H_
#define STRINGMAPPER_H_
#include <map>
#include <list>
#include <iterator>
#include <sstream>
#include "IosFormat.h"
#include "Log.h"
#include "RegExp.h"
#include "Sprinter.h"
#include "String.h"
#include "Variable.h"
namespace drain {
/// A helper class for StringMapper.
/** Stringlet is a std::string that is used literally or as a variable, ie. a key pointing to a map.
* When a StringMapper parses a given std::string, it splits the std::string to segments containing
* literals and variables, in turn.
* The result is stored in a list.
*/
//template<class T>
// Todo: rename VariableMapper
class Stringlet: public std::string {
public:
inline
Stringlet(const std::string & s = "", bool isVariable = false) : std::string(s), isVar(isVariable) {
};
/// Copy constructor.
Stringlet(const Stringlet & s) : std::string(s), isVar(s.isVar) {
}
inline
bool isVariable() const { return isVar; };
inline
void setVariable(bool isVariable=true) { isVar = isVariable; };
inline
void setLiteral(const std::string &s) { assign(s); isVar = false; };
// Consider!
// But has to share variable syntax ${...} with string mapper(s), which recognizes it...
// std::ostream & toStream(std::ostream & ostr, std::map<std::string, T> & environment, bool clearMissing=true){}
protected:
bool isVar;
};
inline
std::ostream & operator<<(std::ostream & ostr, const Stringlet & s) {
if (s.isVariable())
return ostr << "${" << (const std::string &) s << "}";
else
return ostr << (const std::string &) s;
}
/** Expands a std::string containing variables like "Hello, ${name}!" to a literal std::string.
* StringMapper parses a given std::string, it splits the std::string into segments containing
* literals and variables in turn.
* The result is stored in a list of Stringlet:s. The variables are provided to a StringMap
* by means of a std::map<std::string,T> .
*
* \example StringMapper-example.cpp
*/
/// A tool for expanding variables embedded in a std::string to literals.
/** The input variables are provided as a map, which is allowed to change dynamically.
* The input std::string, issued with parse(), contains the variables as "$key" or "${key}", a
* format familiar in Unix shell.
*
*/
class StringMapper : public std::list<Stringlet> {
public:
/** Constructor.
*
*/
// TODO validKeys?
StringMapper(
const std::string & format = "",
const std::string & validChars = "[a-zA-Z0-9_]+"
)
// fieldWidth(0),
// fillChar('0')
{
setValidChars(validChars);
regExp.setFlags(REG_EXTENDED);
if (!format.empty())
parse(format);
//regExp.setFlags(REG_EXTENDED); // ORDER? Should be before parse!?
};
/// Initialize with the given RegExp
StringMapper(const RegExp & regexp) : regExp(regexp) { // fieldWidth(0),
//fillChar('0'),
//((std::list<Stringlet> &)*this) = mapper;
}
/// Copy constructor copies the parsed string and the regExp
StringMapper(const StringMapper & mapper) : std::list<Stringlet>(mapper), regExp(mapper.regExp) { // Buggy: regExp(mapper.regExp) {
}
inline
StringMapper & setValidChars(const std::string & chars){
std::stringstream sstr;
sstr << "^(.*)\\$\\{(" << chars << ")\\}(.*)$";
regExp.setExpression(sstr.str());
return *this;
}
/// Converts a std::string containing variables like in "Hello, ${NAME}!" to a list of StringLet's.
/**
* The Stringlet list is internal.
* \param s - string containing variables like in "Hello, ${NAME}!"
* \param convertEscaped - convert backslash+letter segments to actual chars (\t, \n } first
*/
StringMapper & parse(const std::string &s, bool convertEscaped = false);
/// Interpret commond special chars tab '\t' and newline '\n'.
static
std::string & convertEscaped(std::string &s){
std::string s2;
drain::StringTools::replace(s, "\\t", "\t", s2);
drain::StringTools::replace(s2, "\\n", "\n", s);
return s;
}
/// Return true, if all the elements are literal.
bool isLiteral() const;
/// Output a concatenated chain of stringlets: literals as such and variables surrounded with "${" and "}"
/**
* Prints the mapper in its current state, ie. some variables may have been expanded to literals.
*
* \param ostr - output stream
*/
inline
std::ostream & toStream(std::ostream & ostr) const {
Sprinter::sequenceToStream(ostr, *this, Sprinter::emptyLayout);
return ostr;
}
IosFormat iosFormat;
/// Expands the variables in the last
/**
* \par ostr - output stream
* \par m - map containing variable values
* \par clear - if given, replace undefined variables with this char, or empty (if 0), else (-1) leave variable entry
*/
template <class T>
//std::ostream & toStream(std::ostream & ostr, const std::map<std::string,T> &m, bool keepUnknowns=false) const {
std::ostream & toStream(std::ostream & ostr, const std::map<std::string,T> &m, char replace = 0) const {
for (const Stringlet & stringlet: *this){
//const Stringlet & stringlet = *it;
if (stringlet.isVariable()){
// Find the entry in the map
typename std::map<std::string, T >::const_iterator mit = m.find(stringlet);
if (mit != m.end()){
iosFormat.copyTo(ostr);
//ostr.width(width);
//std::cerr << __FILE__ << " assign -> " << stringlet << std::endl;
//std::cerr << __FILE__ << " assign <---- " << mit->second << std::endl;
ostr << mit->second;
}
else if (replace){
//else if (keepUnknowns){ // = "recycle", add back "${variable}";
if (replace < 0)
ostr << stringlet; // is Variable -> use layout "${variable}";
else
ostr << (char)replace;
// if zero, skip silently (replace with empty string)
/*
if (replaceChar<0)
ostr << '#' << *it << '$'; // is Variable -> use layout "${variable}";
else if (replaceChar>1)
ostr << (char)replaceChar;
*/
}
else {
// Skip unknown (unfound) key
}
}
else
ostr << stringlet;
};
return ostr;
}
/// Expands the variables in the last parsed std::string to a std::string.
/**
* \par m - map containing variable values
* \par clear - if true, expand undefined variables as empty std::strings, else leave variable entry
*/
template <class T>
std::string toStr(const std::map<std::string,T> &m, int replaceChar = -1) const {
std::stringstream s;
toStream(s, m, replaceChar);
return s.str();
}
/// Expands the variables \em in StringMapper, turning expanded variables to constants.
/**
* \par m - map containing variable values
* \par clear - if true, replace undefined variables with empty std::strings.
*/
template <class T>
void expand(const std::map<std::string,T> &m, bool clear=false) {
for (StringMapper::iterator it = begin(); it != end(); it++){
if (it->isVariable()){
typename std::map<std::string, T >::const_iterator mit = m.find(*it);
//std::cerr << __FUNCTION__ << " variable: " << *it << std::endl;
if (mit != m.end()){
//insert(it, Stringlet(Variable(mit->second).toStr()));
it->setLiteral(Variable(mit->second).toStr());
//it = erase(it);
}
else if (clear)
it->setLiteral("");
//it = erase(it);
}
};
}
/// Dumps the list of StringLet's
template <class T>
std::ostream & debug(std::ostream & ostr, const std::map<std::string,T> &m ) const {
ostr << "StringMapper '"<< "', RegExp='" << regExp << "', " << size() << " segments:\n";
//StringMapper::const_iterator it;
for (StringMapper::const_iterator it = begin(); it != end(); it++){
//ostr << *it;
ostr << '\t';
if (it->isVariable()){
//ostr << "VAR: ";
typename std::map<std::string, T >::const_iterator mit = m.find(*it);
if (mit != m.end())
ostr << "\"" << mit->second << "\"";
else
ostr << *it;
}
else {
ostr << "'"<< *it << "'";
//ostr << "LIT: '" << *it << "'\n";
}
ostr << '\n';
//ostr << '\n';
}
return ostr;
}
protected:
StringMapper & parse(const std::string &s, RegExp &r);
RegExp regExp;
// | REG_NEWLINE | RE_DOT_NEWLINE); // | RE_DOT_NEWLINE); // | REG_NEWLINE | RE_DOT_NEWLINE
};
inline
std::ostream & operator<<(std::ostream & ostr, const StringMapper & strmap){
return strmap.toStream(ostr);
}
} // NAMESPACE
#endif /* STRINGMAPPER_H_ */
// Drain
| true |
d216131b2f110de4f15098272ea2c73f05f9d1a1 | C++ | tunamako/Chat-Server-and-Client | /ClientList.h | UTF-8 | 649 | 2.5625 | 3 | [] | no_license | #pragma once
#include <string>
#include <map>
#include <fstream>
#include <vector>
#include <string.h>
using namespace std;
class ClientList {
public:
void addClient(int fd);
void removeClient(int fd);
int clientCount();
int readFrom(int fd);
ClientList(int maxClients);
~ClientList(void);
private:
const int BUFSIZE=1024;
char buffer[1024];
map<int, string> clients;
int maxClients;
ofstream *logFile;
int handleMsg(int fd, string msg);
void sendFile(int fd, string filepath);
void echoMessage(int fd, string msg);
void changeName(int fd, string newName);
bool nameInUse(string aName);
string getTime();
void log(string msg);
}; | true |
3aea9bb22b7cfb8ac70aa616d1a2a9494f97fc28 | C++ | bociepka/jimp2 | /lab5/friendclass/friendclass.cpp | UTF-8 | 504 | 2.578125 | 3 | [] | no_license | //
// Created by Bartek on 27.03.2018.
//
#include "friendclass.h"
Rodzic::Rodzic(string name,string surname,int age,Dziecko * child){
imie = name;
nazwisko = surname;
wiek = age;
&dziecko = child;
}
Rodzic::~Rodzic(){};
Dziecko::Dziecko (string name, string surname, int age, string school){
imie = name;
nazwisko = surname;
wiek = age;
szkola = school;
}
Dziecko::~Dziecko(){};
void Rodzic::przepiszDoInnejSzkoly (std::string nazwa){
dziecko->szkola = nazwa;
} | true |
5dd2ba56b3546aa839c74ef6c4e2e996698e66b8 | C++ | floreaadrian/C- | /OOP/TestLab11/TestLab11/Painting.h | UTF-8 | 538 | 2.765625 | 3 | [] | no_license | //
// Painting.hpp
// TestLab11
//
// Created by Adrian-Paul Florea on 5/17/18.
// Copyright © 2018 Adrian-Paul Florea. All rights reserved.
//
#ifndef Painting_h
#define Painting_h
#include <stdio.h>
#include <string>
class Painting{
private:
std::string title;
std::string artist;
int year;
public:
Painting(const std::string& art,const std::string& t,int y);
std::string getTitle()const{return this->title;}
std::string getArtist()const{return this->artist;}
int getYear(){return this->year;}
};
#endif /* Painting_hpp */
| true |
88952949e0d23e173d5c6272dfc9b6fe04084d1d | C++ | Mldn/B-Tree | /Resursi/main.cpp | UTF-8 | 2,176 | 2.84375 | 3 | [] | no_license | #include "Niz_Filmova.h"
#include "Node.h"
#include "Redak_Indeks.h"
#include "Header.h"
using namespace std;
int main() {
int q = 1;
Niz_Filmova nf;
Redak_Indeks ri;
int r = 0;
cout << " Unesite nacin na koji zelite da unesete bazu(0 za standardni ulaz, ostalo za datoteku)\n";
cin >> q;
if (q) { nf("tmdb_movies.csv"); }
else {
int n;
cout << "Unesite broj elemenata koje zelite da unesete u bazu "; cin >> n;
nf(n);
}
q = 1;
while (q) {
cout << "IZABERITE OPCIJU MENIJA:\n";
cout << endl;
cout << "1.Ispis baze\n";
cout << "2.Kreiranje B+ stabla\n ";
cout << "3.Unos kljuceva u stablo\n";
cout << "4.Ispisi stablo\n";
cout << "5.Pretraga stabla\n";
cout << "6.Pronalazenje svih filmova iz zadatog opsega\n";
cout << "7.Pronalazenje statistike izdavanja za date godine\n";
cin >> q;
switch (q) {
case 1:
{
cout << nf; break;
}
case 2:
{
cout << "Unesite red stabla:";
cin >> r;
Redak_Indeks ri;
break;
}
case 3:
{
ri(r);
for (int i = 0; i < nf.vel; i++) {
Node::ins(nf.moviedb[i].datum / 100, ri, &(nf.moviedb[i]));
//cout << ri.root;
//cout << endl;
//cout << endl;
/*Node::traverse(ri.root);
cout << endl;
cout << endl;*/
}
//Node::traverse(ri.root);
break;
}
case 4: cout << ri.root; break;
case 5:
{
cout << "Unesite datum kljuca koji zelite da pronadjete:\n";
int dat;
cin >> dat;
bool flag = Node::find(dat, ri);
if (flag ) cout << "Kljuc je uspesno pronadjen\n";
else cout << "Kljuc nije pronadjen\n";
break;
}
case 6:
{
int max, min;
cout << "Unesite zadati opseg :";
cin >> min >> max;
if (!(Node::find(min, ri))||!(Node::find(max, ri))) {
cout << "Unesen je nevalidan datum\n";
break;
}
Node::between(min, max, ri); break;
}
case 7:
{
int br,i,s = 0,god;
cout << "Unesite broj godina za koje zelite da odradite statistiku :";
cin >> br;
for (i = 0; i < br; i++) {
cout << "Unesite godinu :"; cin >> god;
s += Node::stat(god, ri);
}
s /= br;
cout << "Statistika za date godine je:";
cout << s << endl;
}
}
}
}
//system("pause");
| true |
07fa72c00b789ebf187f0936d36fdd0a0eaa87ed | C++ | isalogi/Sistemas-Digitales-Avanzados | /Proyecto/CommunicationProtocol/lib/Protocol/protocol.h | UTF-8 | 601 | 2.859375 | 3 | [] | no_license | #ifndef protocol_h //Evita importar dos veces la libreria
#define protocol_h
#include <Arduino.h>
//Archivo primera en minuscula y la clase en mayuscula
class Protocol
{
public:
Protocol(); //Lo primero que se ejecuta cuando creo una clase
void sendData(uint8_t inpData, uint8_t pin);
void read(Stream *stream, const int timeout);
uint8_t* getOutBuffer(uint8_t data, uint8_t type, uint8_t pin);
bool compareChecksum(uint8_t inpChecksum);
uint8_t createChecksum(uint8_t *inpBuffer);
uint8_t getData(uint8_t pin);
uint8_t buffer[5];
private:
const uint8_t header = 0x7e;
};
#endif
| true |
83861811b94a39dd212644b480280d794cbabb33 | C++ | StormZillaa/1stNeuralNetwork | /ConsoleApplication4/ConsoleApplication4/Neuron.cpp | UTF-8 | 4,065 | 2.890625 | 3 | [] | no_license | #include <math.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>
#include "Text.cpp"
class neuron {
public:
int input;
int hidden;
int output;
double costInc = 0.001; //amount to increment cost by
vector<vector<double>> weights;
vector<vector<double>> bias;
vector<vector<double>> activations;
vector<vector<double>> cost;
vector<vector<double>> costW;
vector<vector<double>> costB;
vector<int> outputData;
neuron(int in, int h, int out, vector<int> outputs) {
input = in;
hidden = h;
output = out;
outputData = outputs;
srand(time(NULL));
fillWeights();
srand(time(NULL));
fillBiases();
}
void fillWeights() {
for (int y = 0; y < (input); y++) {
for (int x = 0; x < (input+hidden+output); x++) {
weights[y][x] = rand() / RAND_MAX;
}
}
weights.shrink_to_fit();
}
double sigmoid(double x) {
return 1/(1-(exp(-x)));
}
void fillBiases() {
for (int y = 0; y < (hidden); y++) {
for (int x = 0; x < (hidden+output); x++) {
bias[y][x] = rand() / RAND_MAX;
}
}
bias.shrink_to_fit();
}
void changeOutPuts(vector<int> outs) {
outputData = outs;
}
// old forward prop code that was ugly and didn't work well
/* vector<double> forwardprop(vector<double> w, vector<double> b, vector<double> lastA) {
double x = 0;
vector<double> act;
for (int y = 0; y < w.size(); y++) {
x = w[y] * lastA[y];
x = x + b[y];
act[y] = x;
}
act.shrink_to_fit();
return act;
}*/
void forwardProp(Text data) {
for (int z = 0; z < data.inInts.size(); z++) {
for (int x = 0; x < weights.size(); x++) {
for (int y = 0; y < weights[x].size(); y++) {
activations[x][y] = (weights[x][y] * data.inInts[z]) + bias[x][y];
}
}
}
}
double inverseSigmoid(double x) {
return log(1 - (1 / x));
}
vector<vector<double>> transpose(vector<double> x) {
vector<vector<double>> out;
for (int i = 0; i < x.size(); i++) {
out[i][0] = x[i];
}
return out;
}
double deltaSigmoid(double x) {
return (exp(x)) / (exp2(1 - exp(x)));
}
double multiplyVectors(vector<double> x, vector<vector<double>> y) {
int z;
for (int i = 0; i < y.size(); i++) {
z = z + (x[i]*y[i][0]);
}
return z;
}
void backProp() {
int t = 0; //stores intermediate calculation values
int r = 0;
int L = activations.size();
vector<vector<double>> temp;
vector<double> z;
vector<double> error;
//finds last layer of errors
for (int i = 0; i < activations[activations.size()].size(); i++) {
t = deltaSigmoid(activations[activations.size()][i]);
r = activations[activations.size()][i] - outputData[i];
cost[L][i] = r*t;
}
L--;
int zs = 0;
//finds rest of error layers
for (int i = 0; i =! L; L--) {
//assigns temporary values and clears extra data
temp = transpose(weights[L + 1]);
temp.shrink_to_fit();
z = activations[L];
z.shrink_to_fit();
error = cost[L];
error.shrink_to_fit();
t = multiplyVectors(error, temp);
for (int q = 0; q < activations[L].size(); q++) {
zs = deltaSigmoid(z[q]);
cost[L][q] = (t * zs);
}
temp.clear();
z.clear();
error.clear();
}
//finds errors for weights and biases
L = activations.size();
costB = cost;
for (int i = 0; i = !L; L--) {
z = activations[L - 1];
z.shrink_to_fit();
error = weights[L];
error.shrink_to_fit();
for (int q = 0; q < temp.size(); q++) {
costW[L][q] = z[q] * error[q];
}
z.clear();
error.clear();
}
applyCosts();
}
void applyCosts() {
for (int x = 0; x < weights.size(); x++) {
for (int y = 0; y < weights[x].size(); y++) {
weights[x][y] = weights[x][y] + (costW[x][y] * costInc);
}
}
for (int x = 0; x < bias.size(); x++) {
for (int y = 0; y < bias.size(); y++) {
bias[x][y] = bias[x][y] + (costB[x][y] * costInc);
}
}
}
//call to clear the neuron completely, I only use this at the end to 100% release my memory
void close() {
weights.clear();
bias.clear();
activations.clear();
cost.clear();
costW.clear();
costB.clear();
outputData.clear();
}
}; | true |
c7b28f0a162de4d0fa2a28e9777dc060db3cadb0 | C++ | sivokon/CPlusPlusEssentials | /Chapter2/2.4/lab_2_4_23(2).cpp | UTF-8 | 2,634 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <bitset>
using namespace std;
int main(void) {
unsigned short int val;
bool ispalindrome = true;
cout << "value = ";
cin >> val;
int counter = 15;
unsigned short a = 1, b = 1;
for (int i = 0; i < counter; i++) {
a = a << i;
b = b << counter;
if (((val & a) && (val & b)) || (!(val & a) && !(val & b))) {
a = 1;
b = 1;
counter--;
}
else {
ispalindrome = false;
break;
}
}
if (ispalindrome)
cout << val << " is a bitwise palindrome" << endl;
else
cout << val << " is not a bitwise palindrome" << endl;
system("pause");
return 0;
}
//a = 1; b = 1;
//a = a << 1;
//bitset<16> bitset3{ a }; // the bitset representation of 4
//cout << bitset3 << endl;
//b = b << 14;
//bitset<16> bitset4{ b }; // the bitset representation of 4
//cout << bitset4 << endl << endl;
//a = 1; b = 1;
//a = a << 2;
//bitset<16> bitset5{ a }; // the bitset representation of 4
//cout << bitset5 << endl;
//b = b << 13;
//bitset<16> bitset6{ b }; // the bitset representation of 4
//cout << bitset6 << endl << endl;
//a = 1; b = 1;
//a = a << 3;
//bitset<16> bitset7{ a }; // the bitset representation of 4
//cout << bitset7 << endl;
//b = b << 12;
//bitset<16> bitset8{ b }; // the bitset representation of 4
//cout << bitset8 << endl << endl;
//a = 1; b = 1;
//a = a << 4;
//bitset<16> bitset9{ a }; // the bitset representation of 4
//cout << bitset9 << endl;
//b = b << 11;
//bitset<16> bitset10{ b }; // the bitset representation of 4
//cout << bitset10 << endl << endl;
//a = 1; b = 1;
//a = a << 5;
//bitset<16> bitset11{ a }; // the bitset representation of 4
//cout << bitset11 << endl;
//b = b << 10;
//bitset<16> bitset12{ b }; // the bitset representation of 4
//cout << bitset12 << endl << endl;
//a = 1; b = 1;
//a = a << 6;
//bitset<16> bitset13{ a }; // the bitset representation of 4
//cout << bitset13 << endl;
//b = b << 9;
//bitset<16> bitset14{ b }; // the bitset representation of 4
//cout << bitset14 << endl << endl;
//a = 1; b = 1;
//a = a << 7;
//bitset<16> bitset15{ a }; // the bitset representation of 4
//cout << bitset15 << endl;
//b = b << 8;
//bitset<16> bitset16{ b }; // the bitset representation of 4
//cout << bitset16 << endl << endl;
//a = 1; b = 1;
//a = a << 8;
//bitset<16> bitset17{ a }; // the bitset representation of 4
//cout << bitset17 << endl;
//b = b << 7;
//bitset<16> bitset18{ b }; // the bitset representation of 4
//cout << bitset18 << endl << endl;
| true |
d0df21d7629f01f8850ed6c6dee874ffe9ca8456 | C++ | Kitsch1/BOJ | /2422_better.cpp | UTF-8 | 586 | 2.59375 | 3 | [] | no_license | #include <cstdio>
using namespace std;
bool not_good[201][201];
int main(){
int n,m;
int res = 0;
scanf("%d %d",&n,&m);
for(int i=0;i<m;i++){
int n1,n2;
scanf("%d %d",&n1,&n2);
not_good[n1][n2] = not_good[n2][n1] = true;
}
for(int i=1;i<=n-2;i++){
for(int j=i+1;j<=n-1;j++){
for(int k=j+1;k<=n;k++){
if(not_good[i][j] || not_good[j][k] || not_good[i][k]){
continue;
}
res += 1;
}
}
}
printf("%d\n",res);
return 0;
} | true |
a9af1a3552d3b347575b67c5d89a4abb980d6d4f | C++ | Reid-Ricky/LAB5 | /UtPod.cpp | UTF-8 | 7,041 | 3.21875 | 3 | [] | no_license | //UtPod.cpp
//
//UtPod program
//Reid Lindemann & Ricky Guzman 10/18/2018
//EE 312
/* Student information for project:
*
* On my honor, Reid Lindemann and Ricky Guzman, this programming project is our own work
* and I have not provided this code to any other student.
*
* Name: Reid Lindemann
* email address: lindemannreid@yahoo.com
* UTEID: rhl542
* Section 5 digit ID: 16200
*
*/
#include <iostream>
#include <ctime>
#include <cstdlib>
#include "UtPod.h"
#include "song.h"
using namespace std;
//Default constructor
// set the memory size to MAX_MEMORY
UtPod::UtPod() {
songs = NULL;
memSize = MAX_MEMORY;
}
//Constructor with size parameter
// The user of the class will pass in a size.
// If the size is invalid (greater than MAX_MEMORY or less than or equal to 0),
// set the size to MAX_MEMORY.
UtPod::UtPod(int size) {
songs = NULL;
if (size <= 0 || size > MAX_MEMORY) {
memSize = MAX_MEMORY;
} else {
memSize = size;
}
}
//FUNCTION - numSongs
// counts the number of songs in the UtPod
// returns the sum
// input parms - NONE
// output parms - Total songs
int UtPod::numSongs() {
int total = 0;
SongNode* nodePointer = songs;
while (nodePointer != NULL) {
total++;
nodePointer = nodePointer->next;
}
return total;
}
//FUNCTION - addSong
// attempts to add a new song to the UtPod
// returns 0 if successful
// returns -1 if not enough memory to add the song
// precondition: s is a valid Song
// input parms - Song to be added
// output parms - Error Code (0 or -1)
int UtPod::addSong(Song const &s) {
//calculates the future memory and branches on validity
if ((getRemainingMemory() - s.getSize()) <= NO_MEMORY) {
return NO_MEMORY;
} else {
SongNode* newNode = new SongNode;
newNode->s = s;
newNode->next = songs;
songs = newNode;
return SUCCESS;
}
}
//FUNCTION - removeSong
// attempts to remove a song from the UtPod
// removes the first instance of a song that is in the the UtPod multiple times
// returns 0 if successful
// returns -2 if not found
// input parms - Song to be removed
// output parms - Error Code (0 or -2)
int UtPod::removeSong(Song const &s) {
if (getRemainingMemory() == memSize) { //no memory
return NOT_FOUND;
} else {
bool found = false;
SongNode* prevNode = songs;
SongNode* currentNode = songs;
while (currentNode != NULL && !found) {
if (currentNode->s == s) { //song equality
SongNode* bufferNode = currentNode;
if (currentNode != prevNode) {
prevNode->next = currentNode->next;
} else { //VERY FIRST INSTANCE
songs = currentNode->next;
}
delete bufferNode;
found = true;
} else {
prevNode = currentNode;
currentNode = currentNode->next;
}
}
if (!found) {
return NOT_FOUND;
} else {
return SUCCESS;
}
}
}
//FUNCTION - shuffle
// shuffles the songs into random order by repeatedly swapping random songs
// will do nothing if there are less than two songs in the current list
// input parms - NONE
// output parms - NONE
void UtPod::shuffle() {
if (numSongs() >= 2) {
//chooses random seed by referencing the time
unsigned int currentTime = (unsigned) time(0);
srand(currentTime);
SongNode *ptr1 = NULL;
SongNode *ptr2 = NULL;
SongNode *nodePointer;
Song temp; //temporary song
//booleans dependent on whether the song has been found from the indexes
bool run1;
bool run2;
//random integers representing the indexes of the swapees
int randLength1 = 0;
int randLength2 = 0;
//index integer used to iterate through the linked list
int index;
for (int i = 0; i < 50; i++) {
run1 = true;
run2 = true;
index = 0;
nodePointer = songs;
randLength1 = (rand() % numSongs()); //index of swapees
randLength2 = (rand() % numSongs()); //index of swapees
while (run1 || run2) {
if (index == randLength1 && run1) {
ptr1 = nodePointer;
run1 = false;
}
if (index == randLength2 && run2) {
ptr2 = nodePointer;
run2 = false;
}
index++;
nodePointer = nodePointer->next;
}
//swapping sequence
temp = ptr1->s;
ptr1->s = ptr2->s;
ptr2->s = temp;
}
}
}
//FUNCTION - showSongList
// prints the current list of songs in order from first to last to standard output
// format - Title, Artist, size in MB (one song per line)
// input parms - NONE
// output parms - NONE
void UtPod::showSongList() {
if (getRemainingMemory() == memSize) { //empty list
cout << "\n";
} else {
SongNode* nodePointer = songs;
while (nodePointer != NULL) {
cout << '"' << nodePointer->s.getTitle() << '"' << " by " << nodePointer->s.getArtist() << "\n";
nodePointer = nodePointer->next;
}
}
}
//FUNCTION - sortSongList
// sorts the songs in ascending order
// will do nothing if there are less than two songs in the current list
// input parms - NONE
// output parms - NONE
void UtPod::sortSongList() {
SongNode* nodePointer; //pointer to current song
SongNode* nextPointer; //pointer to the next song
Song temp; //temporary song
if (numSongs() >= 2) { //if more than just one song in UtPod
for (int i = 0; i < numSongs(); i++) {
nodePointer = songs;
nextPointer = songs->next;
for (int j = 0; (j < numSongs() - 1); j++) {
if (nodePointer->s > nextPointer->s) {
temp = nodePointer->s;
nodePointer->s = nextPointer->s;
nextPointer->s = temp;
}
nodePointer = nodePointer->next;
nextPointer = nextPointer->next;
}
}
}
}
//FUNCTION - clearMemory
// clears all the songs from memory
// input parms - NONE
// output parms - NONE
void UtPod::clearMemory() {
SongNode *ptr = songs;
while (songs != NULL) {
ptr = songs;
songs = songs->next;
delete ptr;
}
}
//FUNCTION - getTotalMemory
// returns the total amount of memory in the UtPod
// will do nothing if there are less than two songs in the current list
// input parms - NONE
// output parms - Total memory
int UtPod::getTotalMemory() {
return memSize;
}
//FUNCTION - getRemainingMemory
// returns the amount of memory available for adding new songs
// input parms - NONE
// output parms - Available memory
int UtPod::getRemainingMemory() {
SongNode *ptr = songs;
int curr_mem_used =0;
while (ptr != NULL) {
curr_mem_used = curr_mem_used + ptr->s.getSize();
ptr = ptr->next;
}
return (memSize - curr_mem_used); //calculates the remaining memory
}
//Destructor
// clear memory and set the memory size to NO_MEMORY
UtPod::~UtPod() {
clearMemory();
memSize = NO_MEMORY;
} | true |
d623edc68233d699728d62aa5160b23ccbf9222d | C++ | admitrievsky/ay-3-8912-d4 | /arduino-sketch/ay_channel.h | UTF-8 | 821 | 2.578125 | 3 | [] | no_license | #ifndef AY_CHANNEL_H
#define AY_CHANNEL_H
#include "defines.h"
constexpr size_t FIXED_INTEGER_SIZE = 256;
union FixedPoint {
struct {
uint8_t fraction;
uint8_t integer;
} parts;
uint16_t raw = 0;
};
class Channel {
private:
FixedPoint period;
FixedPoint wave_position;
uint8_t volume = 0;
bool is_tone_enabled = false;
bool is_noise_enabled = false;
static FixedPoint tone_period_table[NUMBER_OF_NOTES];
static uint8_t volumes[];
public:
static void init_tone_period_table();
void init_tone(uint8_t tone, int16_t shift = 0);
void set_volume(uint8_t _volume);
uint8_t get_volume();
bool get_is_noise_enabled();
void enable_tone(bool _is_tone_enabled);
void enable_noise(bool _is_noise_enabled);
int8_t render();
};
#endif
| true |