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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
03bdd573b2cc1ec079c7eded883841a0deb5cbf1 | C++ | francescoriccio/Matilde | /naoqi/modules/R2module/src/task.cpp | UTF-8 | 23,943 | 2.78125 | 3 | [] | no_license | /**
* @class: Task
* This class (and related hierarchy) defines a generic task in the HQP framework.
*
* @file transform.h
* @author Claudio Delli Bovi, Chiara Picardi, Francesco Riccio
*/
#include "task.h"
#define INFO(x) std::cerr << "\033[22;34;1m" << "[Task] " << x << "\033[0m" << std::endl;
//#define TASK_DEBUG
#define POSITION_TASK_DIM 3
#define POSE_ERROR_TOLERANCE 50 /* [mm] */
/** ---------- TaskBase ---------- */
/*
* Class constructor: given a general task in the form A*x=b and the correspondent priority, directly initializes
* the class private members using their copy constructors.
*/
TaskBase::TaskBase(int _priority, const Eigen::MatrixXd& A, const soth::VectorBound& b):
boundType(b[0].getType()), priority(_priority)
{
// Matrices dimensions have to be consistent
assert( A.rows() == b.rows() );
// Initialize private members
constraint_matrix = A;
bounds = b;
#ifdef TASK_DEBUG
INFO("Task base class initalized.");
INFO("Constraint matrix:");
INFO(constraint_matrix);
INFO("Bound vector:");
INFO(bounds);
#endif
}
/*
* Overloaded version of the constructor. Takes as input the bound vector as a general Eigen::MatrixXd.
*/
TaskBase::TaskBase(int _priority, const Eigen::MatrixXd& A, const Eigen::MatrixXd& b):
boundType(soth::Bound::BOUND_DOUBLE), priority(_priority)
{
// Matrices dimensions have to be consistent
assert( A.rows() == b.rows() );
// Initialize constraint matrix
constraint_matrix = A;
// Initialize bound vector
bounds.setZero(b.rows(),1);
for(int i=0; i<b.rows(); ++i)
bounds[i] = soth::Bound(b(i,0), b(i,1));
#ifdef TASK_DEBUG
INFO("Task base class initalized.");
INFO("Constraint matrix:");
INFO(constraint_matrix);
INFO("Bound vector:");
INFO(bounds);
#endif
}
/*
* Overloaded version of the constructor. Takes as input the bound vector as a Eigen::VectorXd and the bound type.
*/
TaskBase::TaskBase(int _priority, const Eigen::MatrixXd& A, const Eigen::VectorXd& b, soth::Bound::bound_t bt):
boundType(bt), priority(_priority)
{
// Matrices dimensions have to be consistent
assert( A.rows() == b.rows() );
// Initialize constraint matrix
constraint_matrix = A;
// Initialize bound vector
bounds.setZero(b.rows(),1);
for(int i=0; i<b.rows(); ++i)
bounds[i] = soth::Bound(b(i), bt);
#ifdef TASK_DEBUG
INFO("Task base class initalized.");
INFO("Constraint matrix:");
INFO(constraint_matrix);
INFO("Bound vector:");
INFO(bounds);
#endif
}
/*
* Class copy constructor.
*/
TaskBase::TaskBase(const TaskBase& tb)
{
constraint_matrix = tb.constraint_matrix;
bounds = tb.bounds;
boundType = tb.boundType;
priority = tb.priority;
#ifdef TASK_DEBUG
INFO("Task base class initalized.");
INFO("Constraint matrix:");
INFO(constraint_matrix);
INFO("Bound vector:");
INFO(bounds);
#endif
}
/*
* Setter that replaces the bound vector with another bound vector (given as a vector + bound type).
*/
void TaskBase::setVectorBounds(const Eigen::VectorXd& b, soth::Bound::bound_t type)
{
// Dimensions must be consistent
assert( bounds.rows() == b.size() );
// Replacing the old bound vector with the new one
bounds.setZero(b.size(), 1);
boundType = type;
for(int i = 0; i < b.size(); ++i)
bounds[i] = soth::Bound(b(i), type);
#ifdef TASK_DEBUG
INFO("New bound vector:");
INFO(bounds);
#endif
}
/*
* Setter that replaces the bound vector with another bound vector (given as a general Eigen::MatrixXd).
* NOTE: in this case, the new bound is assumed to be of type soth::Bound::BOUND_DOUBLE.
*/
void TaskBase::setVectorBounds( const Eigen::MatrixXd& b )
{
// Dimensions must be consistent
assert( bounds.rows() == b.rows() );
assert( b.cols() == 2 );
// Replacing the old bounds with the new ones
bounds.setZero(b.rows(),1);
boundType = soth::Bound::BOUND_DOUBLE;
for(int i = 0; i < b.rows(); ++i)
bounds[i] = soth::Bound(b(i,0), b(i,1));
#ifdef TASK_DEBUG
INFO("New bound vector:");
INFO(bounds);
#endif
}
/*
* Setter that replaces the bound vector, directly taking as input a soth::VectorBound.
*/
void TaskBase::setVectorBounds( const soth::VectorBound& b )
{
// Dimensions must be consistent
assert( bounds.rows() == b.rows() );
bounds = b;
boundType = b[0].getType();
#ifdef TASK_DEBUG
INFO("New bound vector:");
INFO(bounds);
#endif
}
/*
* Setter that replaces the constraint matrix.
*/
void TaskBase::setConstraintMatrix( const Eigen::MatrixXd& A )
{
// Dimensions must be consistent
assert( A.rows() == constraint_matrix.rows() );
constraint_matrix = A;
#ifdef TASK_DEBUG
INFO("New constraint matrix:");
INFO(constraint_matrix);
#endif
}
/*
* Less-than operator overload: tasks are ordered by their priority value.
*/
bool operator<(const TaskBase& l_tb, const TaskBase& r_tb)
{
if(l_tb.priority <= r_tb.priority) return true;
else return false;
}
/*
* Stream operator overload: print the task on the output stream, in the form A*x=b.
*/
std::ostream& operator<<(std::ostream& out, const TaskBase& tb)
{
// Devise the task type (equality, inequality, 'double' inequality)
std::string op = "";
if(tb.bounds[0].getType() == soth::Bound::BOUND_INF) op = "<";
else if(tb.bounds[0].getType() == soth::Bound::BOUND_SUP) op = ">";
else if(tb.bounds[0].getType() == soth::Bound::BOUND_TWIN) op = "=";
else if(tb.bounds[0].getType() == soth::Bound::BOUND_DOUBLE) op = "in";
// Print the task equation row-by-row
for(unsigned int i = 0; i < tb.bounds.rows(); ++i)
{
if(i == tb.bounds.rows()/2 && op == "in")
out<<" | "<<tb.constraint_matrix.row(i)<<" | "<< op <<" "<< tb.bounds[i]<<std::endl;
else if(i == tb.bounds.rows()/2)
out<<" | "<<tb.constraint_matrix.row(i)<<" | "<< op <<" "<< tb.bounds[i]<<std::endl;
else
out<<" | "<<tb.constraint_matrix.row(i)<<" | "<< tb.bounds[i]<<std::endl;
}
return out;
}
/*
* Pre/postfix increment/decrement operators overload: the task priority is modified accordingly.
*/
TaskBase& TaskBase::operator++()
{
++priority;
return *this;
}
TaskBase& TaskBase::operator--()
{
--priority;
return *this;
}
TaskBase TaskBase::operator++(int)
{
TaskBase tmp_tb(*this);
++(*this);
return tmp_tb;
}
TaskBase TaskBase::operator--(int)
{
TaskBase tmp_tb(*this);
--(*this);
return tmp_tb;
}
/** ---------- Task ---------- */
/*
* Class constructor. Input arguments are:
* - The task dimension m,n where A*x=b being 'A' m x n and 'b' m x 1;
* - The task priority value (low value => higher priority and high value => lower priority);
* - A ConfigReader class object to initialize the task kinematic chain;
* - Two indices _base, _ee identifying the task kinematic chain in the ConfigReader object file.
*/
Task::Task(int m, int n, int _priority, ConfigReader theConfigReader, soth::Bound::bound_t boundType):
// Base class initalization
TaskBase(_priority, Eigen::MatrixXd::Identity(m, n), Eigen::VectorXd::Zero(m), boundType),
// Kinematic chain initialization
theKinChain( new Rmath::KinChain(theConfigReader) ), base_end(0),
parameters( inactive, 0, ACTIVATION_STEP, Eigen::VectorXd::Zero(m),
Eigen::VectorXd::Zero(n), Eigen::Matrix4d::Identity())
{
#ifdef TASK_DEBUG
INFO("Task kinematic chain:");
INFO(theKinChain);
#endif
}
Task::Task(int m, int n, int _priority, const Rmath::KinChain& _kc, int _base, soth::Bound::bound_t boundType):
// Base class initalization
TaskBase(_priority, Eigen::MatrixXd::Identity(m, n), Eigen::VectorXd::Zero(m), boundType),
// Kinematic chain initialization
theKinChain( new Rmath::KinChain(_kc) ), base_end(_base),
parameters( inactive, 0, ACTIVATION_STEP, Eigen::VectorXd::Zero(m),
Eigen::VectorXd::Zero(n), Eigen::Matrix4d::Identity())
{
#ifdef TASK_DEBUG
INFO("Task kinematic chain:");
INFO(theKinChain);
#endif
}
/*
* Class destructor: deallocates the kinematic chain from the heap.
*/
Task::~Task()
{
if(theKinChain) delete theKinChain;
}
void Task::activate(float activationStep)
{
if (parameters.taskStatus == inactive)
{
// Recover information about the target
if (parameters.positioningActive && !parameters.path.empty())
// Rebuild the path from scratch
setDesiredPose( parameters.path.at(parameters.path.size()-1), parameters.path.size());
}
if(parameters.taskStatus != active && parameters.taskStatus != inactive2active )
{
parameters.activationStep = activationStep;
if(parameters.activationValue == 1.0)
parameters.taskStatus = active;
else
parameters.taskStatus = inactive2active;
}
}
void Task::stop(float decayStep)
{
if(parameters.taskStatus != inactive && parameters.taskStatus != active2inactive )
{
parameters.activationStep = decayStep;
if(parameters.activationValue == 0.0)
parameters.taskStatus = inactive;
else
parameters.taskStatus = active2inactive;
}
}
Eigen::VectorXd Task::getCurrentPose() const
{
Eigen::Matrix4d H_chain;
theKinChain->forward((&H_chain));
H_chain = parameters.baseT * H_chain;
Eigen::VectorXd currentPose (constraint_matrix.rows());
if(constraint_matrix.rows() > POSITION_TASK_DIM)
// Retrieving the position from the translation vector of the forward kinematics
// Retrieving the orientation from the Euler fixed frame x-y-z angles
currentPose << H_chain.topRightCorner(POSITION_TASK_DIM,1),
Rmath::xyzEulerAngles( H_chain.topLeftCorner(3,3) ).head(constraint_matrix.rows()-POSITION_TASK_DIM);
// If the task target is a position vector (A row size <= 3) just the translation vector of the forward kinematics is needed
else
currentPose << H_chain.col(POSITION_TASK_DIM).head(constraint_matrix.rows());
return currentPose;
}
/* TOCOMMENT */
const Eigen::VectorXd Task::getTargetPose() const
{
if(parameters.positioningActive)
return parameters.path.at(parameters.path_currentStep);
else
return getCurrentPose();
}
void Task::setDesiredPose(const Eigen::VectorXd& dp, int n_controlPoints)
{
// Re-computing direct kinematics
Eigen::Matrix4d H_chain;
theKinChain->forward((&H_chain));
H_chain = parameters.baseT * H_chain;
Eigen::VectorXd initialPose (constraint_matrix.rows());
if(constraint_matrix.rows() > POSITION_TASK_DIM)
// Retrieving the position from the translation vector of the forward kinematics
// Retrieving the orientation from the Euler fixed frame x-y-z angles
initialPose << H_chain.topRightCorner(POSITION_TASK_DIM,1),
Rmath::xyzEulerAngles( H_chain.topLeftCorner(3,3) ).head(constraint_matrix.rows()-POSITION_TASK_DIM);
// If the task target is a position vector (A row size <= 3) just the translation vector of the forward kinematics is needed
else
initialPose << H_chain.col(POSITION_TASK_DIM).head(constraint_matrix.rows());
assert(dp.size() == initialPose.size());
parameters.path.clear();
for (float i = 1.0; i <= n_controlPoints; ++i)
parameters.path.push_back(initialPose + (i/static_cast<float>(n_controlPoints)) * (dp - initialPose));
parameters.path_currentStep = 0;
parameters.positioningActive = true;
if (parameters.jointControlActive) parameters.jointControlActive = false;
}
void Task::setDesiredPose(const Eigen::VectorXd& idp, const Eigen::VectorXd& dp, int n_controlPoints)
{
// Re-computing direct kinematics
Eigen::Matrix4d H_chain;
theKinChain->forward((&H_chain));
H_chain = parameters.baseT * H_chain;
Eigen::VectorXd initialPose (constraint_matrix.rows());
if(constraint_matrix.rows() > POSITION_TASK_DIM)
// Retrieving the position from the translation vector of the forward kinematics
// Retrieving the orientation from the Euler fixed frame x-y-z angles
initialPose << H_chain.topRightCorner(POSITION_TASK_DIM,1),
Rmath::xyzEulerAngles( H_chain.topLeftCorner(3,3) ).head(constraint_matrix.rows()-POSITION_TASK_DIM);
// If the task target is a position vector (A row size <= 3) just the translation vector of the forward kinematics is needed
else
initialPose << H_chain.col(POSITION_TASK_DIM).head(constraint_matrix.rows());
assert(idp.size() == initialPose.size());
assert(dp.size() == initialPose.size());
parameters.path.clear();
for (float i = 1.0; i <= n_controlPoints; ++i)
parameters.path.push_back(initialPose + (i/static_cast<float>(n_controlPoints)) * (idp - initialPose));
for (float i = 1.0; i <= n_controlPoints; ++i)
parameters.path.push_back(idp + (i/static_cast<float>(n_controlPoints)) * (dp - idp));
parameters.path_currentStep = 0;
parameters.positioningActive = true;
if (parameters.jointControlActive) parameters.jointControlActive = false;
}
void Task::setDesiredConfiguration(const Eigen::VectorXd& desiredConf, int n_controlPoints)
{
Eigen::VectorXd initialConf = theKinChain->jointConfiguration();
assert(initialConf.size() == desiredConf.size());
constraint_matrix = Eigen::MatrixXd::Identity(initialConf.size(), initialConf.size());
bounds.setZero(initialConf.size(),1);
parameters.path.clear();
for (float i = 1.0; i <= n_controlPoints; ++i)
parameters.path.push_back(initialConf + (i/static_cast<float>(n_controlPoints)) * (desiredConf - initialConf));
parameters.path_currentStep = 0;
parameters.positioningActive = true;
if (!parameters.jointControlActive) parameters.jointControlActive = true;
}
void Task::circularPathGenerator( const Eigen::VectorXd& dp, float z_shift, int n_controlPoints, float radius, int n )
{
// Re-computing direct kinematics
Eigen::Matrix4d H_chain;
theKinChain->forward((&H_chain));
H_chain = parameters.baseT * H_chain;
parameters.path.clear();
for (float i = 0.0; i < n*2*M_PI; i+= 2*M_PI/n_controlPoints)
{
Eigen::VectorXd ee_desiredPose_handframe(4);
ee_desiredPose_handframe << radius*cos(i), radius*sin(i), z_shift, 1.0;
Rmath::trim(&ee_desiredPose_handframe);
Eigen::VectorXd ee_desiredPose_CoMframe(dp.size());
if(dp.size() > 3)
ee_desiredPose_CoMframe << (H_chain * ee_desiredPose_handframe).head(3), dp(3), dp(4), dp(5);
else
ee_desiredPose_CoMframe << (H_chain * ee_desiredPose_handframe).head(3);
Rmath::trim(&ee_desiredPose_CoMframe);
parameters.path.push_back( ee_desiredPose_CoMframe );
}
parameters.path_currentStep = 0;
parameters.positioningActive = true;
if (parameters.jointControlActive) parameters.jointControlActive = false;
}
/*
* Task update function: update the constraint matrix A=A(q) with a new value of q and replace the target vector
* with a proportional/derivative control law of the type K*POSE_ERROR + DESIRED_VELOCITY.
*/
void Task::update( const Eigen::VectorXd& _q, const Eigen::VectorXd& desiredVel, double K )
{
// Dimensions must be consistent
assert(constraint_matrix.rows() == desiredVel.size());
assert(constraint_matrix.cols() == _q.size());
Eigen::VectorXd q(_q.size());
q << -_q.head(base_end).reverse(), _q.tail(_q.size()-base_end);
// Updating the task kinematic chain with the new joint values
theKinChain->update(q);
#ifdef TASK_DEBUG
INFO("Updating task...");
INFO("Current joint configuration: \n" << q);
INFO("Kinematic chain: \n" << (*theKinChain));
#endif
// Cartesian space task
if (!parameters.jointControlActive)
{
// Replacing the task constraint matrix with the updated version
if (constraint_matrix.rows() > POSITION_TASK_DIM)
{
// Re-computing differential kinematics
Eigen::MatrixXd J_chain(constraint_matrix.rows(), constraint_matrix.cols());
theKinChain->differential(&J_chain);
// Computing base transform
Eigen::MatrixXd baseT = Eigen::MatrixXd::Zero(6,6);
baseT.topLeftCorner(3,3) = parameters.baseT.topLeftCorner(3,3);
baseT.bottomRightCorner(3,3) = parameters.baseT.topLeftCorner(3,3);
// Pre-multipling base transform
constraint_matrix << (baseT * J_chain).topRows(constraint_matrix.rows());
}
else
{
// Re-computing differential kinematics
Eigen::MatrixXd J_chain(constraint_matrix.rows(), constraint_matrix.cols());
theKinChain->differential(&J_chain, POSITION_TASK_DIM);
// Pre-multipling base transform
constraint_matrix << (parameters.baseT.topLeftCorner(3,3) * J_chain).topRows(constraint_matrix.rows());
}
#ifdef TASK_DEBUG
INFO("New constraint matrix:");
INFO(std::endl << constraint_matrix);
#endif
Eigen::VectorXd transitionVelocity(constraint_matrix.rows());
transitionVelocity = constraint_matrix * parameters.qd_n;
// Equality task with position control in the Cartesian space
if ( (parameters.positioningActive) && (bounds[0].getType() == soth::Bound::BOUND_TWIN) )
{
// Re-computing direct kinematics
Eigen::Matrix4d H_chain;
theKinChain->forward((&H_chain));
H_chain = parameters.baseT * H_chain;
// Computing the current pose in the task space
Eigen::VectorXd currentPose(constraint_matrix.rows());
// If the task target is a pose (position+orientation) vector, a minimal description of the orientation has to be computed
if(constraint_matrix.rows() > POSITION_TASK_DIM)
// Retrieving the position from the translation vector of the forward kinematics
// Retrieving the orientation from the Euler fixed frame x-y-z angles
currentPose << H_chain.topRightCorner(POSITION_TASK_DIM,1),
Rmath::xyzEulerAngles( H_chain.topLeftCorner(3,3) ).head(constraint_matrix.rows()-POSITION_TASK_DIM);
// If the task target is a position vector (A row size <= 3) just the translation vector of the forward kinematics is needed
else
currentPose << H_chain.col(POSITION_TASK_DIM).head(constraint_matrix.rows());
Eigen::VectorXd pose_error;
if(parameters.path_currentStep < parameters.path.size())
pose_error = parameters.path.at(parameters.path_currentStep) - currentPose;
else
pose_error = parameters.path.at(parameters.path.size()-1) - currentPose;
parameters.targetVelocity = K * pose_error + desiredVel;
// Updating the bound vector with the task error + a feedforward term
for(int i=0; i<bounds.rows(); ++i)
{
bounds[i] = parameters.targetVelocity(i) * parameters.activationValue +
(1- parameters.activationValue)* transitionVelocity(i);
}
if ( (pose_error.norm() < POSE_ERROR_TOLERANCE) && (parameters.path_currentStep < parameters.path.size()-1) )
++parameters.path_currentStep;
}
// Equality task with velocity control in the Cartesian space
else if ( bounds[0].getType() == soth::Bound::BOUND_TWIN )
{
// Updating the bound vector with the task error + a feedforward term
for(int i=0; i<bounds.rows(); ++i)
bounds[i] = parameters.targetVelocity(i) * parameters.activationValue +
(1- parameters.activationValue)* transitionVelocity(i);
}
// Inequality task in the Cartesian space
else
{
// Re-computing direct kinematics
Eigen::Matrix4d H_chain;
theKinChain->forward((&H_chain));
H_chain = parameters.baseT * H_chain;
// Computing the current pose in the task space
Eigen::VectorXd currentPose(constraint_matrix.rows());
// If the task target is a pose (position+orientation) vector, a minimal description of the orientation has to be computed
if(constraint_matrix.rows() > POSITION_TASK_DIM)
// Retrieving the position from the translation vector of the forward kinematics
// Retrieving the orientation from the Euler fixed frame x-y-z angles
currentPose << H_chain.topRightCorner(POSITION_TASK_DIM,1),
Rmath::xyzEulerAngles( H_chain.topLeftCorner(3,3) ).head(constraint_matrix.rows()-POSITION_TASK_DIM);
// If the task target is a position vector (A row size <= 3) just the translation vector of the forward kinematics is needed
else
currentPose << H_chain.col(POSITION_TASK_DIM).head(constraint_matrix.rows());
Eigen::VectorXd new_b (bounds.rows());
new_b = ( parameters.path.at(parameters.path.size()-1) - currentPose ) / TIME_STEP;
for(int i=0; i<bounds.rows(); ++i)
bounds[i] = soth::Bound(new_b(i) * parameters.activationValue + (1- parameters.activationValue)* transitionVelocity(i),
boundType);
}
}
// Joint space task
else
{
// Equality task with position control in the joint space
if ( (parameters.positioningActive) && (bounds[0].getType() == soth::Bound::BOUND_TWIN) )
{
Eigen::VectorXd joint_error;
if(parameters.path_currentStep < parameters.path.size())
joint_error = parameters.path.at(parameters.path_currentStep) - theKinChain->jointConfiguration();
else
joint_error = parameters.path.at(parameters.path.size()-1) - theKinChain->jointConfiguration();
parameters.targetVelocity = K * joint_error + desiredVel;
// Updating the bound vector with the task error + a feedforward term
for(int i=0; i<bounds.rows(); ++i)
{
bounds[i] = parameters.targetVelocity(i) * parameters.activationValue +
(1- parameters.activationValue)* parameters.qd_n(i);
}
if ( (joint_error.norm() < POSE_ERROR_TOLERANCE) && (parameters.path_currentStep < parameters.path.size()-1) )
++parameters.path_currentStep;
}
// Equality task with velocity control in the joint space
else if ( bounds[0].getType() == soth::Bound::BOUND_TWIN )
{
// Updating the bound vector with the task error + a feedforward term
for(int i=0; i<bounds.rows(); ++i)
{
bounds[i] = parameters.targetVelocity(i) * parameters.activationValue +
(1- parameters.activationValue)* parameters.qd_n(i);
}
}
// Inequality task in the joint space
else
{
Eigen::VectorXd new_b (bounds.rows());
new_b = (parameters.path.at(parameters.path.size()-1) - q) / TIME_STEP;
for(int i=0; i<bounds.rows(); ++i)
bounds[i] = soth::Bound (new_b(i) * parameters.activationValue + (1- parameters.activationValue)* parameters.qd_n(i),
boundType);
}
}
if(parameters.taskStatus == inactive2active)
parameters.increaseActivationValue();
else if(parameters.taskStatus == active2inactive)
parameters.decreaseActivationValue();
#ifdef TASK_DEBUG
INFO("New bound vector:");
INFO(bounds);
#endif
}
| true |
5054558b64b26be4d034a703866c173e8927a61f | C++ | marioxe301/TrabajosEstructuraDatos1 | /Hash Table/HashEntry.h | UTF-8 | 128 | 2.515625 | 3 | [] | no_license | #pragma once
class HashEntry {
private:
int key;
int value;
public:
HashEntry(int, int);
int getKey();
int getValue();
}; | true |
2dea768c0bc5f1e4e81500d56d0ccf5c9a297c91 | C++ | logic-three-body/WordCountSystem | /MapCount/MapCount.cpp | UTF-8 | 611 | 3.21875 | 3 | [] | no_license | #include <map>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
void display_map(map<string, int> &wmap);
int main()
{
const char *szInputFileName = "data.txt";
ifstream ifs(szInputFileName);
string szTemp;
map<string, int> wmap;
while (ifs >> szTemp)
wmap[szTemp]++;
display_map(wmap);
return false;
}
void display_map(map<string, int> &wmap)
{
map<string, int>::const_iterator map_it;
for (map_it = wmap.begin(); map_it != wmap.end(); map_it++)
{
cout << "map_it->first: "<<map_it->first<<"\t"<<"map_it->second" << map_it->second << endl;
}
} | true |
82a01b27026e8c74e6980f313cba51349efc3f12 | C++ | kuonanhong/UVa-2 | /10168 - Summation of Four Primes.cpp | UTF-8 | 1,148 | 3.265625 | 3 | [] | no_license | /**
UVa 10168 - Summation of Four Primes
by Rico Tiongson
Submitted: June 10, 2013
Accepted 0.032s C++
O(sqrt(n)) time
*/
#include<iostream>
#include<vector>
#include<cmath>
using namespace std;
vector<int> p;
int lim,lim2,n,ans[3];
void addprime( int x ){
lim = sqrt(x) + 1;
for( int i=1; p[i] < lim; ++i ){
if( x%p[i]==0 ) return;
}
p.push_back( x );
}
bool isPrime( int x ){
if(x==1) return false;
lim2 = sqrt(x)+1;
for(int i=0;p[i]<lim2;++i){
if(x%p[i]==0) return false;
}
return true;
}
bool goldbach( int x ){
lim = x/2 + 1;
for( int i=0; p[i] < lim; ++i ){
if( isPrime( x-p[i] ) ){
ans[1] = p[i];
ans[2] = x-p[i];
return true;
}
}
return false;
}
int main(){
p.push_back(2);
p.push_back(3);
for( int i=5; i<3162; i+=4 ){
addprime( i );
addprime( i+=2 );
}
while( cin >> n ){
if(n<8) cout << "Impossible." << endl;
else{
if(n%2){
ans[0] = 3;
n-=5;
}
else{
ans[0] = 2;
n-=4;
}
if( goldbach(n) ) cout << "2 " << ans[0] << ' ' << ans[1] << ' ' << ans[2] << endl;
else cout << "Impossible." << endl;
}
}
}
| true |
af4f5e0853fa5f973d6f2f6035e07b2256f56c90 | C++ | jwlawson/qv | /include/cycle.h | UTF-8 | 4,434 | 3.515625 | 4 | [
"Apache-2.0"
] | permissive | /*
* cycle.h
* Copyright 2014-2015 John Lawson
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Contains the class Cycle which provides a wrapper to hold a cycle that
* appears in a quiver.
*/
#pragma once
#include <functional>
#include <memory>
#include <ostream>
#include <vector>
namespace cluster {
class Cycle {
public:
/**
* Default constructor creates an empty cycle.
*/
Cycle();
/**
* Create a cycle with the provided values. The values will be cyclically
* permuted so that the smallest value is the first one.
* @param vec Vector of vertex labels which form the cycle
*/
Cycle(const std::vector<int>& vec);
/**
* Create a cycle with part of a vector. the size tells how many of the
* values from the vector should be used from the first.
* @param vec Vector of vertex labels
* @param size Number of elements in cycle
*/
Cycle(const std::vector<int>& vec, const int size);
/**
* Check whether this cycle is equal to the one provided.
* @param rhs Cycle to check if equal to
* @return true if equal
*/
bool equals(const Cycle& rhs) const;
/**
* Check whether this cycle is equivalent to the one provided when it is
* permuted by the values given.
* @param rhs Cycle to check
* @param permutation Mappings from one vertex to another
* @return true if equivalent
*/
bool equals(const Cycle& rhs, const std::vector<int>& permutation) const;
/**
* Hash the cycle and return the hashcode.
* @return The hashcode.
*/
std::size_t hash() const;
/**
* Get the size of the cycle. That is the number of vertices in the cycle.
*/
std::size_t size() const;
/**
* Check whether the cycle contains the specified vertex.
* @param value Vertex index to check
* @return true if vertex is in the cycle
*/
bool contains(const int value) const;
/**
* Check whether the cycle contains the values in the order that is
* specified by the pair.
* @param pair The pair of integers to check
* @return true if both number are in the cycle and in the same order
*/
bool contains(const std::pair<int, int>& pair) const;
/**
* Need to overload == to allow unordered_sets of cycles to be compared.
*/
friend bool operator ==(const Cycle& lhs, const Cycle& rhs) {
return lhs.equals(rhs);
}
friend std::ostream& operator <<(std::ostream& os, const Cycle& cycle);
private:
/**
* Container to hold the cycle information.
*/
std::vector<int> cycle_;
/**
* Find the index in the vector of the smallest value stored in the vector.
* @param vec Vector to check
* @return Index of the smallest value
*/
static std::size_t smallest_index(const std::vector<int>& vec);
/**
* Find the index in the vector of the smallest value stored in the first
* size values in the vector.
* @param vec Vector to check
* @param size Number of values to check from the beginning of the vector
* @return Index of the smallest value
*/
static std::size_t smallest_index(const std::vector<int>& vec, const int size);
};
}
namespace std {
/* Add hash function to the std::hash struct. */
template <>
struct hash<cluster::Cycle> {
size_t operator()(const cluster::Cycle &x) const {
return x.hash();
}
};
/* Add equals function to std::equal_to */
template<>
struct equal_to<cluster::Cycle> {
bool operator()(const cluster::Cycle &lhs,
const cluster::Cycle &rhs) const {
return lhs.equals(rhs);
}
};
template <>
struct hash<std::shared_ptr<cluster::Cycle>> {
size_t operator()(const std::shared_ptr<cluster::Cycle> &x)
const {
return x->hash();
}
};
template<>
struct equal_to<std::shared_ptr<cluster::Cycle>> {
bool operator()(const std::shared_ptr<cluster::Cycle> &lhs,
const std::shared_ptr<cluster::Cycle> &rhs) const {
return lhs->equals(*rhs);
}
};
}
| true |
e1d324566d86edbedd04c87192b422b067c36f23 | C++ | tyhe12/DesignPatterns | /SingletonPattern/SingletonDatabase.h | UTF-8 | 461 | 2.6875 | 3 | [] | no_license | #pragma once
#include <string>
#include <iostream>
#include "Database.h"
using namespace std;
class SingletonDatabase : public Database
{
private:
SingletonDatabase();
SingletonDatabase(string database_name);
string db_name = "singleton database";
public:
SingletonDatabase(SingletonDatabase const&) = delete;
void operator=(SingletonDatabase const&) = delete;
~SingletonDatabase();
static SingletonDatabase& get();
string get_name() override;
};
| true |
eeb321e38928566c1ee79e73713ce45ecbb45795 | C++ | 8l/HrwCC | /codegen/typearith.cpp | UTF-8 | 6,985 | 3.15625 | 3 | [] | no_license |
#include "typearith.h"
#include "../include/hrwcccomp.h"
/** Create type of array element of variable. */
syntaxTreeNode* type_CreateArrayElmType( syntaxTreeNode* varDef)
{
if( type_IsAPointerVar(varDef) )
return type_RemoveStarFromType( syntax_GetChild(syntax_GetChild(varDef,0),0));
if( type_IsAArrayVar(varDef) )
return type_CreateType( varDef);
return 0;
}
/** Determine the size of an array element by the definition of the variable */
int type_GetArrayElmSize( symbolTable* symtab, syntaxTreeNode* varDef)
{
syntaxTreeNode* newtype;
int size;
//Create type of array element
newtype = type_CreateArrayElmType (varDef);
// Error occured
if( newtype == 0)
return -1;
//Determine new size and remove type
size = symbol_Sizeof_DataType( symtab, newtype);
syntax_FreeSyntaxTree(newtype);
return size;
}
/** Check if variable is a pointer */
int type_IsAPointerVar( syntaxTreeNode* varDef )
{
//Array is not a pointer
if( type_IsAArrayVar(varDef) )
return 0;
//Get just the data-type
varDef = syntax_GetChild( syntax_GetChild(varDef, 0), 0);
//At least a star
if( syntax_CountChilds(varDef) > 1 )
return 1;
return 0;
}
/** Check if variable is a array */
int type_IsAArrayVar( syntaxTreeNode* varDef )
{
// <typed_ident> [ <number ] ;
if( syntax_CountChilds(varDef) == 5 )
return 1;
return 0;
}
/** Check if variable is a struct-instance */
int type_IsAStructVar( syntaxTreeNode* varDef )
{
syntaxTreeNode* subtree;
//Arrays are not structs
if( type_IsAArrayVar(varDef) )
return 0;
//No definition
if( varDef == 0)
return 0;
//Get just the data-type
varDef = syntax_GetChild( syntax_GetChild(varDef, 0), 0);
//Pointer or non-struct typed
if( syntax_CountChilds(varDef) > 1)
return 0;
//Aha, struct name at front
subtree = syntax_GetChild(varDef,0);
if( subtree->tok.type == TOK_IDENT)
return 1;
return 0;
}
int type_IsAPointerType( syntaxTreeNode* type)
{
if( type == 0)
return 0;
if( syntax_CountChilds(type) > 1)
return 1;
return 0;
}
int type_IsAIntType( syntaxTreeNode* type)
{
syntaxTreeNode* subtree;
if( type_IsAPointerType(type) )
return 0;
subtree = syntax_GetChild(type,0);
if( subtree->tok.type == TOK_INT)
return 1;
return 0;
}
int type_IsACharType( syntaxTreeNode* type)
{
syntaxTreeNode* subtree;
if( type_IsAPointerType(type) )
return 0;
subtree = syntax_GetChild(type,0);
if( subtree->tok.type == TOK_CHAR)
return 1;
return 0;
}
int type_IsAStructType( syntaxTreeNode* type)
{
syntaxTreeNode* subtree;
//No type
if( type == 0)
return 0;
if( type_IsAPointerType(type) )
return 0;
subtree = syntax_GetChild(type,0);
if( subtree->tok.type == TOK_IDENT)
return 1;
return 0;
}
int type_IsLongSized( syntaxTreeNode* type)
{
if( type == 0 ||
type_IsAPointerType(type) ||
type_IsAIntType(type) )
return 1;
return 0;
}
int type_IsByteSized( syntaxTreeNode* type)
{
if( type == 0 ||
type_IsACharType(type) )
return 1;
return 0;
}
syntaxTreeNode* type_RemoveStarFromType( syntaxTreeNode* type)
{
syntaxTreeNode* newtype;
int idx;
int cnt;
//Cannot remove a star!
if( ! type_IsAPointerType(type) )
return 0;
//Create container for new-type and cut of last star...
newtype = syntax_CreateTreeNode();
idx = 0;
cnt = syntax_CountChilds(type) - 1;
//Add the tokens...
while( idx < cnt)
{
syntax_AddChildTree(newtype, syntax_CopyTree(syntax_GetChild(type,idx)));
idx = idx+1;
}
//This is the new type
return newtype;
}
syntaxTreeNode* type_AddStarToType( syntaxTreeNode* type)
{
syntaxTreeNode* newtype;
int idx;
int cnt;
token star;
//Create container for new-type and cut of last star...
newtype = syntax_CreateTreeNode();
idx = 0;
cnt = syntax_CountChilds(type);
//Add the tokens...
while( idx < cnt)
{
syntax_AddChildTree(newtype, syntax_CopyTree(syntax_GetChild(type,idx)));
idx = idx+1;
}
//Create additional star
strcpy(star.content, "*");
star.type = TOK_STAR;
syntax_AddChildNode(newtype, star);
//This is the new type
return newtype;
}
/** Get the data-type of a variable */
syntaxTreeNode* type_CreateType( syntaxTreeNode* varDef )
{
syntaxTreeNode* newtype;
int idx;
int cnt;
//Get just the data-type
varDef = syntax_GetChild( syntax_GetChild(varDef, 0), 0);
//Create container for new-type
newtype = syntax_CreateTreeNode();
idx = 0;
cnt = syntax_CountChilds(varDef) ;
//Add the tokens...
while( idx < cnt)
{
syntax_AddChildTree(newtype, syntax_CopyTree(syntax_GetChild(varDef,idx)));
idx = idx+1;
}
//This is the new type
return newtype;
}
/** Calculates the offset of a member in a containing type */
int type_GetMemberOffset( symbolTable* symtab, syntaxTreeNode* contType, token member )
{
symbolTableNode* structNode;
//Get to struct-ident directly
contType = syntax_GetChild(contType, 0);
//And search for struct
structNode = symbol_FindStruct(symtab, contType->tok);
//No such struct!
if( structNode == 0)
return -1;
//Calc offset in struct
return symbol_GetOffsetInStruct(symtab, structNode, member);
}
/** Get the member declaration in containing type */
syntaxTreeNode* type_GetMemberDeclaration( symbolTable* symtab, syntaxTreeNode* contType, token member)
{
symbolTableNode* structNode;
//Get to struct-ident directly
contType = syntax_GetChild(contType, 0);
//And search for struct
structNode = symbol_FindStruct(symtab, contType->tok);
//No such struct!
if( structNode == 0)
return 0;
//Calc offset in struct
return symbol_GetMemberDeclInStruct(symtab, structNode, member);
}
/** Count the resolutions in variable expression */
int type_CountVarexprResolutions( syntaxTreeNode* tree)
{
int cntresol;
syntaxTreeNode* subtree;
//Count children
cntresol = syntax_CountChilds(tree);
//Remove index specifier
subtree = syntax_GetChild(tree,cntresol-1);
if( subtree->tok.type == TOK_RECPAR_END)
cntresol = cntresol - 3;
//Remove deref or addr operator
subtree = syntax_GetChild(tree,0);
if( subtree->tok.type == TOK_STAR ||
subtree->tok.type == TOK_AND )
cntresol = cntresol - 1;
return (cntresol+1)/2;
}
/** Convert singlechar like "'\n'" to 0xd or so */
int type_ConvertSinglechar(char* sngchar)
{
char first;
char second;
first = sngchar[1];
//Esc-sequence
if( first == '\\' )
{
second = sngchar[2];
if( second == 'n' )
return 10;
if( second == 'r' )
return 13;
if( second == 't' )
return 9;
if( second == '\\' )
return 92;
if( second == 'b' )
return 8;
if( second == '\'' )
return 39;
if( second == '\"' )
return 34;
if( second == '0' )
return 0;
//Unknown esc-sequence --> give back second one
return second;
}
//So just return first
return first;
}
| true |
bf883e38198ed2cc4a7691280e5e574bdd419aca | C++ | BennetLeff/engine | /Core/Transform.cpp | UTF-8 | 725 | 2.734375 | 3 | [] | no_license | /*
* Transform.cpp
*
* Created on: Apr 22, 2016
* Author: bennetleff
*/
#include "Transform.h"
glm::mat4 Transform::getModel() const
{
glm::mat4 posMatrix = glm::translate(mPosition);
glm::mat4 rotXMatrix = glm::rotate(mRotation.x, glm::vec3(1, 0, 0));
glm::mat4 rotYMatrix = glm::rotate(mRotation.y, glm::vec3(0, 1, 0));
glm::mat4 rotZMatrix = glm::rotate(mRotation.z, glm::vec3(0, 0, 1));
glm::mat4 scaleMatrix = glm::scale(mScale);
glm::mat4 rotMatrix = rotZMatrix * rotYMatrix * rotXMatrix;
return posMatrix * rotMatrix * scaleMatrix;
}
Vec3* Transform::position()
{
return &mPosition;
}
Vec3* Transform::rotation()
{
return &mRotation;
}
Vec3* Transform::scale()
{
return &mScale;
}
| true |
4a36dba4588da572817783ea3a19efbb0a041411 | C++ | muthuubalakan/cpu-usage | /src/logging.h | UTF-8 | 1,540 | 3.03125 | 3 | [] | no_license | #ifndef LOGGING_H
#define LOGGING_H
#include <iostream>
#include <ctime>
using namespace std;
enum loglevel{
// Apache Log4J2 log levels int level.
TRACE,
DEBUG,
INFO,
WARN,
ERROR,
SUCCESS,
FATAL
}
struct ConfigLogging
{
};
extern ConfigLogging config;
class Logging{
public:
Logging(){}
Logging(loglevel level){
lglevel = level;
}
void logging(string msg){
if (lglevel){
cout << "[" + getLevel(lglevel) + "] " + msg << endl;
}else{
cout << "[DEBUG]" << msg <<endl;
}
}
string time_stamp(){
time_t time_now = time(0);
}
private:
loglevel lglevel = DEBUG;
inline string getLevel(loglevel level){
string l;
switch (level)
{
case TRACE:
l = "TRACE";
break;
case DEBUG:
l = "DEBUG";
break;
case INFO:
l = "INFO";
break;
case WARN:
l = "WARN";
break;
case ERROR:
l = "ERROR";
break;
case SUCCESS:
l = "SUCCESS";
break;
case FATAL:
l = "FATAL";
break;
default:
l = "DEBUG";
break;
}
return l;
}
protected:
};
#endif | true |
92717dcb25421d19699caea5e8d6dbe744911a0b | C++ | ilyasemikin/AlgorithmsAndStructures | /sort/include/insertion_sort_array.hpp | UTF-8 | 600 | 3.90625 | 4 | [] | no_license |
namespace learn::sort_array {
template <typename T, typename Compare>
void insertion_sort(T *array, size_t size, Compare comp) {
size_t j;
for (size_t i = 1; i < size; i++) {
auto key = array[i];
j = i;
while (j > 0 && comp(key, array[j - 1])) {
array[j] = array[j - 1];
j--;
}
array[j] = key;
}
}
template <typename T>
void insertion_sort(T *array, size_t size) {
insertion_sort(array, size, [](const auto &x, const auto &y) { return x < y; });
}
} | true |
4dcfb279c32355ec5a8f82d3dda078e7938619dc | C++ | svetthesaiyan/uni-projects-1st-year-2nd-trimester | /2021.01.22 Exercise 3/exercise_3.cpp | UTF-8 | 437 | 3.34375 | 3 | [] | no_license | // Да се изведат елементите на масив a {1,2,3,4,5} чрез индексни променливи и чрез указатели:
#include <iostream>
using namespace std;
int main()
{
int a[]={1,2,3,4,5}; int i;
for(i=0; i<5; ++i)
cout<<a[i]<<" "; // извежда 1 2 3 4 5
cout<<endl;
for(i=0; i<5; ++i)
cout<<*(a+i)<<" "; // извежда 1 2 3 4 5
cout<<endl;
return 0;
system("pause");
}
| true |
420660b41827d031d04afe678db389dc7c94b9af | C++ | CRASHGRIM/lab2 | /game/game.ino | UTF-8 | 5,227 | 2.703125 | 3 | [] | no_license | #include <LedControl.h>
#include <Wire.h>
#include <Servo.h>
#include "Game.h"
#define INVALID_DIRECTION -1
const char keyUp = 'U';
const char keyDown = 'D';
const char keyRight = 'R';
const char keyLeft = 'L';
const char keyNone = 'N';
const int keypadAdderss = 10;
const int boardSizeX = 24;
const int boardSizeY = 8;
Game game(boardSizeX, boardSizeY);
LedControl ledDisplay = LedControl(26, 22, 24, 3); // (DIN, CLK, CS, Количество дисплеев)
uint64_t lastGameUpdate;
uint64_t lastDisplayUpdate;
uint64_t lastFoodBlink;
const uint64_t gameUpdateDelayMs = 500;
const uint64_t displayUpdateDelayMs = 100;
const uint64_t foodBlinkDelayMs = 200;
bool showingFood = true;
char currentKey1 = keyNone;
char currentKey2 = keyNone;
const byte rowAmount = 4;
const byte colAmount = 4;
char keyMatrix[rowAmount][colAmount] = {
{keyNone, keyUp, keyNone, keyNone},
{keyRight, keyDown, keyLeft, keyNone},
{keyNone, keyNone, keyNone, keyNone},
{keyNone, keyNone, keyNone, keyNone}
};
static bool keyDownMatrix[rowAmount][colAmount];
byte rowPins1[rowAmount] = { 45, 44, 43, 42 };
byte colPins1[colAmount] = { 46, 47, 48, 49 };
byte rowPins2[rowAmount] = { 17, 16, 15, 14 };
byte colPins2[colAmount] = { 18, 19, 20, 21 };
const int address = 10;
bool gameStarted;
Servo servo1;
Servo servo2;
void setup()
{
for (int i=0; i<ledDisplay.getDeviceCount(); i++)
{
ledDisplay.shutdown(i, false);
ledDisplay.setIntensity(i, 10);
ledDisplay.clearDisplay(i);
}
Point point;
point.x = 1;
point.y = 2;
drawPoint(point);
Serial.begin(115200);
Serial.println(game.isRunning());
for (int i = 0; i < rowAmount; i++) {
pinMode(rowPins1[i], OUTPUT);
digitalWrite(rowPins1[i], HIGH);
}
for (int i = 0; i < colAmount; i++) {
pinMode(colPins1[i], INPUT);
digitalWrite(colPins1[i], HIGH);
}
for (int i = 0; i < rowAmount; i++) {
pinMode(rowPins2[i], OUTPUT);
digitalWrite(rowPins2[i], HIGH);
}
for (int i = 0; i < colAmount; i++) {
pinMode(colPins2[i], INPUT);
digitalWrite(colPins2[i], HIGH);
}
gameStarted=true;
servo1.attach(10);
servo2.attach(9);
}
void loop()
{
currentKey1 = getKey(1);
currentKey2 = getKey(2);
if (game.isRunning()) {
updateInput();
updateGame();
updateDisplay();
}
if (!game.isRunning() && gameStarted){
gameStarted=false;
if (game.isTie())
{
servo1.write(90);
servo2.write(90);
delay(1000);
servo1.write(0);
servo2.write(0);
}
else
{
if (game.getWinner()==1)
{
servo1.write(90);
delay(1000);
servo1.write(0);
}
else
{
servo2.write(90);
delay(1000);
servo2.write(0);
}
Serial.println(game.getWinner());
}
}
delay(gameUpdateDelayMs);
}
Direction keyToDirection(char key)
{
switch(key) {
case keyUp: return UP;
case keyDown: return DOWN;
case keyRight: return RIGHT;
case keyLeft: return LEFT;
}
return INVALID_DIRECTION;
}
char getKey(int player)
{
char result = keyNone;
for (int i = 0; i < rowAmount; i++) {
for (int j = 0; j < colAmount; j++) {
if (isKeyDown(i, j, player)) {
return keyMatrix[i][j];
}
}
}
return keyNone;
}
bool isKeyDown(int i, int j, int player)
{
if (player==1)
{
bool result = false;
digitalWrite(rowPins1[i], LOW);
if (digitalRead(colPins1[j]) == LOW) {
result = true;
}
digitalWrite(rowPins1[i], HIGH);
return result;
}
else
{
bool result = false;
digitalWrite(rowPins2[i], LOW);
if (digitalRead(colPins2[j]) == LOW) {
result = true;
}
digitalWrite(rowPins2[i], HIGH);
return result;
}
}
void drawPoint(Point point)
{
int displayIndex=(int)point.x/8;
ledDisplay.setLed(displayIndex, boardSizeY - 1 - point.y, point.x-8*displayIndex, true);// передат ьиндекс панели
}
void drawSnake(Snake &snake)
{
for (int i = 0; i < snake.getSize(); i++) {
drawPoint(snake.getPosition(i));
}
}
void drawFood(Point &food)
{
if (showingFood) {
drawPoint(food);
}
if (millis() - lastFoodBlink > foodBlinkDelayMs) {
showingFood = !showingFood;
lastFoodBlink = millis();
}
}
void updateInput() {
char key1 = getKey(1);
char key2 = getKey(2);
if (key1 != keyNone) {
currentKey1 = key1;
}
if (key2 != keyNone) {
currentKey2 = key2;
}
}
void updateGame()
{
if (millis() - lastGameUpdate > gameUpdateDelayMs) {
if (currentKey1 != keyNone) {
game.setSnakeDirection(keyToDirection(currentKey1), 1);
}
if (currentKey2 != keyNone) {
game.setSnakeDirection(keyToDirection(currentKey2), 2);
}
game.update();
currentKey1 = keyNone;
currentKey2 = keyNone;
lastGameUpdate = millis();
}
}
void updateDisplay()
{
if (millis() - lastDisplayUpdate > displayUpdateDelayMs) {
Snake snake1 = game.getSnake1();
Snake snake2 = game.getSnake2();
Point food = game.getFood();
for (int i=0; i<ledDisplay.getDeviceCount();i++)
{
ledDisplay.clearDisplay(i);
}
drawSnake(snake1);
drawSnake(snake2);
drawFood(food);
lastDisplayUpdate = millis();
}
}
| true |
fa5e8b3d3204411458f13fae5f0f9a0c0f07f0ab | C++ | AALEKH/solutions | /leetcode_107.cpp | UTF-8 | 1,361 | 3.75 | 4 | [
"MIT"
] | permissive | // Question: Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> elements;
vector<vector<int>> answer;
int height(TreeNode* root) {
if(!root) return 0;
int lheight = height(root->left);
int rheight = height(root->right);
if(lheight > rheight) {
return lheight+1;
} else {
return rheight+1;
}
}
void printGivenLevel(TreeNode* root, int level) {
if (root == NULL)
return;
if (level == 1)
// printf("%d ", root->data);
elements.push_back(root->val);
else if (level > 1)
{
printGivenLevel(root->left, level-1);
printGivenLevel(root->right, level-1);
}
}
vector<vector<int>> levelOrderBottom(TreeNode* root) {
for(int i = height(root); i >= 1; i--) {
printGivenLevel(root, i);
answer.push_back(elements);
elements.clear();
}
return answer;
}
};
| true |
3d3b73a822fe9e8783bad0e50312dfe6f991b9b3 | C++ | Ubpa/UGM | /include/UGM/Interfaces/IArray/IArray.hpp | UTF-8 | 45,478 | 2.953125 | 3 | [
"MIT"
] | permissive | #pragma once
#include "../../basic.hpp"
#include "../ImplTraits.hpp"
#include <array>
#include <vector>
#include <iostream>
#include <cmath>
#include <cassert>
#include <compare>
namespace Ubpa {
template<typename Base, typename Impl>
struct IArray1D;
}
namespace Ubpa::details {
enum class ArrayMode {
One,
Two,
Three,
Four,
#ifdef UBPA_UGM_USE_SIMD
Four_SIMD, // float4
#endif
Basic
};
template<typename Impl>
constexpr ArrayMode GetArrayMode() {
constexpr std::size_t N = SI_ImplTraits_N<Impl>;
if constexpr (SI_Contains_v<Impl, IArray1D>) {
if constexpr (N == 1)
return ArrayMode::One;
else if constexpr (N == 2)
return ArrayMode::Two;
else if constexpr (N == 3)
return ArrayMode::Three;
else if constexpr (N == 4) {
if constexpr (SI_ImplTraits_SupportSIMD<Impl>::value)
return ArrayMode::Four_SIMD;
else
return ArrayMode::Four;
}
else
return ArrayMode::Basic;
}
else
return ArrayMode::Basic;
}
template<typename Base, typename Impl>
struct IStdArrayBasic : Base {
using T = SI_ImplTraits_T<Impl>;
using F = SI_ImplTraits_F<Impl>;
static constexpr std::size_t N = SI_ImplTraits_N<Impl>;
static_assert(N > 0);
using Base::Base;
using Base::operator[];
std::array<T, N>& to_array() noexcept { return reinterpret_cast<std::array<T, N>&>(*this); }
const std::array<T, N>& to_array() const noexcept { return const_cast<IStdArrayBasic*>(this)->to_array(); }
using value_type = T;
using size_type = std::size_t;
using difference_type = ptrdiff_t;
using pointer = T*;
using const_pointer = const T*;
using reference = T&;
using const_reference = const T&;
using iterator = std::array<T, N>::iterator;
using const_iterator = std::array<T, N>::const_iterator;
using reverse_iterator = std::array<T, N>::reverse_iterator;
using const_reverse_iterator = std::array<T, N>::const_reverse_iterator;
void fill(T v) noexcept { to_array().fill(v); }
void swap(Impl& other) noexcept { to_array().swap(other.to_array()); }
iterator begin() noexcept { return to_array().begin(); }
const_iterator begin() const noexcept { return to_array().begin(); }
iterator end() noexcept { return to_array().end(); }
const_iterator end() const noexcept { return to_array().end(); }
reverse_iterator rbegin() noexcept { return to_array().rbegin(); }
const_reverse_iterator rbegin() const noexcept { return to_array().rbegin(); }
reverse_iterator rend() noexcept { return to_array().rend(); }
const_reverse_iterator rend() const noexcept { return to_array().rend(); }
const_iterator cbegin() const noexcept { return begin(); }
const_iterator cend() const noexcept { return end(); }
const_reverse_iterator crbegin() const noexcept { return rbegin(); }
const_reverse_iterator crend() const noexcept { return rend(); }
constexpr size_t size() const noexcept { return N; }
constexpr size_t max_size() const noexcept { return N; }
constexpr bool empty() const noexcept { return false; }
reference at(size_t i) { return to_array().at(i); }
const_reference at(size_t i) const { return to_array().at(i); }
reference operator[](size_t i) noexcept { return to_array().at(i); }
const_reference operator[](size_t i) const noexcept { return to_array().at(i); }
reference front() noexcept { return to_array().front(); }
const_reference front() const noexcept { return to_array().front(); }
reference back() noexcept { return to_array().back(); }
const_reference back() const noexcept { return to_array().back(); }
T* data() noexcept { return reinterpret_cast<T*>(this); }
const T* data() const noexcept { return const_cast<IStdArrayBasic*>(this)->data(); }
};
template<typename Base, typename Impl>
struct IStdArray : IStdArrayBasic<Base, Impl> {
using T = SI_ImplTraits_T<Impl>;
using F = SI_ImplTraits_F<Impl>;
static constexpr std::size_t N = SI_ImplTraits_N<Impl>;
using IStdArrayBasic<Base, Impl>::IStdArrayBasic;
using IStdArrayBasic<Base, Impl>::operator==;
using IStdArrayBasic<Base, Impl>::operator!=;
using IStdArrayBasic<Base, Impl>::operator>;
using IStdArrayBasic<Base, Impl>::operator>=;
using IStdArrayBasic<Base, Impl>::operator<;
using IStdArrayBasic<Base, Impl>::operator<=;
friend bool operator==(const Impl& lhs, const Impl& rhs) { return lhs.to_array() == rhs.to_array(); }
friend bool operator!=(const Impl& lhs, const Impl& rhs) { return lhs.to_array() != rhs.to_array(); }
friend bool operator< (const Impl& lhs, const Impl& rhs) { return lhs.to_array() < rhs.to_array(); }
friend bool operator> (const Impl& lhs, const Impl& rhs) { return lhs.to_array() > rhs.to_array(); }
friend bool operator<=(const Impl& lhs, const Impl& rhs) { return lhs.to_array() <= rhs.to_array(); }
friend bool operator>=(const Impl& lhs, const Impl& rhs) { return lhs.to_array() >= rhs.to_array(); }
};
template<typename Base, typename Impl>
struct IArrayCommon : IStdArray<Base, Impl> {
using T = SI_ImplTraits_T<Impl>;
using F = SI_ImplTraits_F<Impl>;
static constexpr std::size_t N = SI_ImplTraits_N<Impl>;
private:
template<size_t... Ns>
IArrayCommon(const T* arr, std::index_sequence<Ns...>) noexcept {
(((*this)[Ns] = arr[Ns]), ...);
}
template<size_t... Ns>
IArrayCommon(const T& t, std::index_sequence<Ns...>) noexcept {
(((*this)[Ns] = t), ...);
};
template<size_t... Ns>
IArrayCommon(const Impl& arr, std::index_sequence<Ns...>) noexcept {
(((*this)[Ns] = arr[Ns]), ...);
};
public:
using IStdArray<Base, Impl>::IStdArray;
IArrayCommon() noexcept {}
constexpr IArrayCommon(const T* arr) noexcept : IArrayCommon{ arr, std::make_index_sequence<N>{} } {}
constexpr IArrayCommon(const Impl& arr) noexcept : IArrayCommon{ arr, std::make_index_sequence<N>{} } {}
constexpr IArrayCommon(const T& t) noexcept : IArrayCommon{ t, std::make_index_sequence<N>{} } {}
static constexpr Impl Zero() noexcept {
return Impl{ T{static_cast<F>(0)} };
}
template<size_t i>
T get() const noexcept {
static_assert(i < N);
return (*this)[i];
}
template<size_t i>
void set(T v) noexcept {
static_assert(i < N);
(*this)[i] = v;
}
template<size_t i>
Impl replicate() const noexcept {
static_assert(i < N);
Impl rst;
rst.fill(get<i>());
return rst;
}
bool lex_lt(const Impl& y) const noexcept {
const auto& x = static_cast<const Impl&>(*this);
return x < y;
}
bool lex_le(const Impl& y) const noexcept {
const auto& x = static_cast<const Impl&>(*this);
return x <= y;
}
bool lex_gt(const Impl& y) const noexcept {
const auto& x = static_cast<const Impl&>(*this);
return x > y;
}
bool lex_ge(const Impl& y) const noexcept {
const auto& x = static_cast<const Impl&>(*this);
return x >= y;
}
static bool all_lt(const Impl& x, const Impl& y) noexcept {
for (size_t i = 0; i < N; i++) {
if (x[i] >= y[i])
return false;
}
return true;
}
static bool all_le(const Impl& x, const Impl& y) noexcept {
for (size_t i = 0; i < N; i++) {
if (x[i] > y[i])
return false;
}
return true;
}
static bool all_gt(const Impl& x, const Impl& y) noexcept {
for (size_t i = 0; i < N; i++) {
if (x[i] <= y[i])
return false;
}
return true;
}
static bool all_ge(const Impl& x, const Impl& y) noexcept {
for (size_t i = 0; i < N; i++) {
if (x[i] < y[i])
return false;
}
return true;
}
bool all_lt(const Impl& y) const noexcept {
const auto& x = static_cast<const Impl&>(*this);
return all_lt(x, y);
}
bool all_le(const Impl& y) const noexcept {
const auto& x = static_cast<const Impl&>(*this);
return all_le(x, y);
}
bool all_gt(const Impl& y) const noexcept {
const auto& x = static_cast<const Impl&>(*this);
return all_gt(x, y);
}
bool all_ge(const Impl& y) const noexcept {
const auto& x = static_cast<const Impl&>(*this);
return all_ge(x, y);
}
};
template<std::size_t... Ns>
constexpr bool is_duplicate(std::index_sequence<Ns...>) noexcept {
std::size_t indices[]{ Ns... };
for (std::size_t i{ 0 }; i < std::extent_v<decltype(indices)>; i++) {
for (std::size_t j{ 0 }; j < i; j++) {
if (indices[j] == indices[i])
return true;
}
}
return false;
}
template<typename Impl, std::size_t... Ns>
struct SwizzleImplBase {
auto& operator [](std::size_t i) noexcept {
constexpr std::size_t indices[]{ Ns... };
return get(indices[i]);
}
const auto& operator [](std::size_t i) const noexcept {
return const_cast<SwizzleImplBase&>(*this)[i];
}
protected:
template<std::size_t N>
auto get() const noexcept {
return reinterpret_cast<const Impl&>(*this).template get<N>();
}
auto& get(std::size_t i) noexcept {
return reinterpret_cast<Impl&>(*this)[i];
}
const auto& get(std::size_t i) const noexcept {
return const_cast<SwizzleImplBase*>(this)->get(i);
}
};
template<bool IsDuplicate, bool SupportImplN, typename Impl, std::size_t... Ns>
struct SwizzleImpl : SwizzleImplBase<Impl, Ns...> {};
template<typename Impl, std::size_t... Ns>
struct SwizzleImpl<true, true, Impl, Ns...> : SwizzleImplBase<Impl, Ns...> {
using ImplN = SI_ImplTraits_ImplN<Impl, sizeof...(Ns)>;
auto to_impl() const {
return ImplN{ this->template get<Ns>()... };
}
operator ImplN() const {
return to_impl();
}
};
template<typename A, typename B, std::size_t... Ns, std::size_t... Ms>
void assign_impl(A& lhs, const B& rhs, std::index_sequence<Ns...>, std::index_sequence<Ms...>) {
(lhs.template set<Ns>(rhs.template get<Ms>()), ...);
}
template<typename Impl, std::size_t... Ns>
struct SwizzleImpl<false, true, Impl, Ns...> : SwizzleImpl<true, true, Impl, Ns...> {
using ImplN = SI_ImplTraits_ImplN<Impl, sizeof...(Ns)>;
auto& operator=(const ImplN& rhs) noexcept {
assign_impl(reinterpret_cast<Impl&>(*this), rhs, std::index_sequence<Ns...>{}, std::make_index_sequence<sizeof...(Ns)>{});
return *this;
}
};
template<typename Impl, std::size_t... Ns>
struct Swizzle : SwizzleImpl<is_duplicate(std::index_sequence<Ns...>{}), Ubpa::SI_ImplTraits_SupportImplN<Impl, sizeof...(Ns)>, Impl, Ns...> {
using SwizzleImpl<is_duplicate(std::index_sequence<Ns...>{}), Ubpa::SI_ImplTraits_SupportImplN<Impl, sizeof...(Ns)>, Impl, Ns...>::operator=;
};
}
#define UBPA_ARRAY_SWIZZLE2_2(EI0, EI1, E0, E1) \
Ubpa::details::Swizzle<Impl, EI0, EI0> E0##E0; \
Ubpa::details::Swizzle<Impl, EI0, EI1> E0##E1; \
Ubpa::details::Swizzle<Impl, EI1, EI0> E1##E0; \
Ubpa::details::Swizzle<Impl, EI1, EI1> E1##E1
#define UBPA_ARRAY_SWIZZLE3_3(EI0, EI1, EI2, E0, E1, E2) \
Ubpa::details::Swizzle<Impl, EI0, EI0, EI0> E0##E0##E0; \
Ubpa::details::Swizzle<Impl, EI0, EI0, EI1> E0##E0##E1; \
Ubpa::details::Swizzle<Impl, EI0, EI0, EI2> E0##E0##E2; \
Ubpa::details::Swizzle<Impl, EI0, EI1, EI0> E0##E1##E0; \
Ubpa::details::Swizzle<Impl, EI0, EI1, EI1> E0##E1##E1; \
Ubpa::details::Swizzle<Impl, EI0, EI1, EI2> E0##E1##E2; \
Ubpa::details::Swizzle<Impl, EI0, EI2, EI0> E0##E2##E0; \
Ubpa::details::Swizzle<Impl, EI0, EI2, EI1> E0##E2##E1; \
Ubpa::details::Swizzle<Impl, EI0, EI2, EI2> E0##E2##E2; \
Ubpa::details::Swizzle<Impl, EI1, EI0, EI0> E1##E0##E0; \
Ubpa::details::Swizzle<Impl, EI1, EI0, EI1> E1##E0##E1; \
Ubpa::details::Swizzle<Impl, EI1, EI0, EI2> E1##E0##E2; \
Ubpa::details::Swizzle<Impl, EI1, EI1, EI0> E1##E1##E0; \
Ubpa::details::Swizzle<Impl, EI1, EI1, EI1> E1##E1##E1; \
Ubpa::details::Swizzle<Impl, EI1, EI1, EI2> E1##E1##E2; \
Ubpa::details::Swizzle<Impl, EI1, EI2, EI0> E1##E2##E0; \
Ubpa::details::Swizzle<Impl, EI1, EI2, EI1> E1##E2##E1; \
Ubpa::details::Swizzle<Impl, EI1, EI2, EI2> E1##E2##E2; \
Ubpa::details::Swizzle<Impl, EI2, EI0, EI0> E2##E0##E0; \
Ubpa::details::Swizzle<Impl, EI2, EI0, EI1> E2##E0##E1; \
Ubpa::details::Swizzle<Impl, EI2, EI0, EI2> E2##E0##E2; \
Ubpa::details::Swizzle<Impl, EI2, EI1, EI0> E2##E1##E0; \
Ubpa::details::Swizzle<Impl, EI2, EI1, EI1> E2##E1##E1; \
Ubpa::details::Swizzle<Impl, EI2, EI1, EI2> E2##E1##E2; \
Ubpa::details::Swizzle<Impl, EI2, EI2, EI0> E2##E2##E0; \
Ubpa::details::Swizzle<Impl, EI2, EI2, EI1> E2##E2##E1; \
Ubpa::details::Swizzle<Impl, EI2, EI2, EI2> E2##E2##E2
#define UBPA_ARRAY_SWIZZLE4_4(EI0, EI1, EI2, EI3, E0, E1, E2, E3) \
Ubpa::details::Swizzle<Impl, EI0, EI0, EI0, EI0> E0##E0##E0##E0; \
Ubpa::details::Swizzle<Impl, EI0, EI0, EI0, EI1> E0##E0##E0##E1; \
Ubpa::details::Swizzle<Impl, EI0, EI0, EI0, EI2> E0##E0##E0##E2; \
Ubpa::details::Swizzle<Impl, EI0, EI0, EI0, EI3> E0##E0##E0##E3; \
Ubpa::details::Swizzle<Impl, EI0, EI0, EI1, EI0> E0##E0##E1##E0; \
Ubpa::details::Swizzle<Impl, EI0, EI0, EI1, EI1> E0##E0##E1##E1; \
Ubpa::details::Swizzle<Impl, EI0, EI0, EI1, EI2> E0##E0##E1##E2; \
Ubpa::details::Swizzle<Impl, EI0, EI0, EI1, EI3> E0##E0##E1##E3; \
Ubpa::details::Swizzle<Impl, EI0, EI0, EI2, EI0> E0##E0##E2##E0; \
Ubpa::details::Swizzle<Impl, EI0, EI0, EI2, EI1> E0##E0##E2##E1; \
Ubpa::details::Swizzle<Impl, EI0, EI0, EI2, EI2> E0##E0##E2##E2; \
Ubpa::details::Swizzle<Impl, EI0, EI0, EI2, EI3> E0##E0##E2##E3; \
Ubpa::details::Swizzle<Impl, EI0, EI0, EI3, EI0> E0##E0##E3##E0; \
Ubpa::details::Swizzle<Impl, EI0, EI0, EI3, EI1> E0##E0##E3##E1; \
Ubpa::details::Swizzle<Impl, EI0, EI0, EI3, EI2> E0##E0##E3##E2; \
Ubpa::details::Swizzle<Impl, EI0, EI0, EI3, EI3> E0##E0##E3##E3; \
Ubpa::details::Swizzle<Impl, EI0, EI1, EI0, EI0> E0##E1##E0##E0; \
Ubpa::details::Swizzle<Impl, EI0, EI1, EI0, EI1> E0##E1##E0##E1; \
Ubpa::details::Swizzle<Impl, EI0, EI1, EI0, EI2> E0##E1##E0##E2; \
Ubpa::details::Swizzle<Impl, EI0, EI1, EI0, EI3> E0##E1##E0##E3; \
Ubpa::details::Swizzle<Impl, EI0, EI1, EI1, EI0> E0##E1##E1##E0; \
Ubpa::details::Swizzle<Impl, EI0, EI1, EI1, EI1> E0##E1##E1##E1; \
Ubpa::details::Swizzle<Impl, EI0, EI1, EI1, EI2> E0##E1##E1##E2; \
Ubpa::details::Swizzle<Impl, EI0, EI1, EI1, EI3> E0##E1##E1##E3; \
Ubpa::details::Swizzle<Impl, EI0, EI1, EI2, EI0> E0##E1##E2##E0; \
Ubpa::details::Swizzle<Impl, EI0, EI1, EI2, EI1> E0##E1##E2##E1; \
Ubpa::details::Swizzle<Impl, EI0, EI1, EI2, EI2> E0##E1##E2##E2; \
Ubpa::details::Swizzle<Impl, EI0, EI1, EI2, EI3> E0##E1##E2##E3; \
Ubpa::details::Swizzle<Impl, EI0, EI1, EI3, EI0> E0##E1##E3##E0; \
Ubpa::details::Swizzle<Impl, EI0, EI1, EI3, EI1> E0##E1##E3##E1; \
Ubpa::details::Swizzle<Impl, EI0, EI1, EI3, EI2> E0##E1##E3##E2; \
Ubpa::details::Swizzle<Impl, EI0, EI1, EI3, EI3> E0##E1##E3##E3; \
Ubpa::details::Swizzle<Impl, EI0, EI2, EI0, EI0> E0##E2##E0##E0; \
Ubpa::details::Swizzle<Impl, EI0, EI2, EI0, EI1> E0##E2##E0##E1; \
Ubpa::details::Swizzle<Impl, EI0, EI2, EI0, EI2> E0##E2##E0##E2; \
Ubpa::details::Swizzle<Impl, EI0, EI2, EI0, EI3> E0##E2##E0##E3; \
Ubpa::details::Swizzle<Impl, EI0, EI2, EI1, EI0> E0##E2##E1##E0; \
Ubpa::details::Swizzle<Impl, EI0, EI2, EI1, EI1> E0##E2##E1##E1; \
Ubpa::details::Swizzle<Impl, EI0, EI2, EI1, EI2> E0##E2##E1##E2; \
Ubpa::details::Swizzle<Impl, EI0, EI2, EI1, EI3> E0##E2##E1##E3; \
Ubpa::details::Swizzle<Impl, EI0, EI2, EI2, EI0> E0##E2##E2##E0; \
Ubpa::details::Swizzle<Impl, EI0, EI2, EI2, EI1> E0##E2##E2##E1; \
Ubpa::details::Swizzle<Impl, EI0, EI2, EI2, EI2> E0##E2##E2##E2; \
Ubpa::details::Swizzle<Impl, EI0, EI2, EI2, EI3> E0##E2##E2##E3; \
Ubpa::details::Swizzle<Impl, EI0, EI2, EI3, EI0> E0##E2##E3##E0; \
Ubpa::details::Swizzle<Impl, EI0, EI2, EI3, EI1> E0##E2##E3##E1; \
Ubpa::details::Swizzle<Impl, EI0, EI2, EI3, EI2> E0##E2##E3##E2; \
Ubpa::details::Swizzle<Impl, EI0, EI2, EI3, EI3> E0##E2##E3##E3; \
Ubpa::details::Swizzle<Impl, EI0, EI3, EI0, EI0> E0##E3##E0##E0; \
Ubpa::details::Swizzle<Impl, EI0, EI3, EI0, EI1> E0##E3##E0##E1; \
Ubpa::details::Swizzle<Impl, EI0, EI3, EI0, EI2> E0##E3##E0##E2; \
Ubpa::details::Swizzle<Impl, EI0, EI3, EI0, EI3> E0##E3##E0##E3; \
Ubpa::details::Swizzle<Impl, EI0, EI3, EI1, EI0> E0##E3##E1##E0; \
Ubpa::details::Swizzle<Impl, EI0, EI3, EI1, EI1> E0##E3##E1##E1; \
Ubpa::details::Swizzle<Impl, EI0, EI3, EI1, EI2> E0##E3##E1##E2; \
Ubpa::details::Swizzle<Impl, EI0, EI3, EI1, EI3> E0##E3##E1##E3; \
Ubpa::details::Swizzle<Impl, EI0, EI3, EI2, EI0> E0##E3##E2##E0; \
Ubpa::details::Swizzle<Impl, EI0, EI3, EI2, EI1> E0##E3##E2##E1; \
Ubpa::details::Swizzle<Impl, EI0, EI3, EI2, EI2> E0##E3##E2##E2; \
Ubpa::details::Swizzle<Impl, EI0, EI3, EI2, EI3> E0##E3##E2##E3; \
Ubpa::details::Swizzle<Impl, EI0, EI3, EI3, EI0> E0##E3##E3##E0; \
Ubpa::details::Swizzle<Impl, EI0, EI3, EI3, EI1> E0##E3##E3##E1; \
Ubpa::details::Swizzle<Impl, EI0, EI3, EI3, EI2> E0##E3##E3##E2; \
Ubpa::details::Swizzle<Impl, EI0, EI3, EI3, EI3> E0##E3##E3##E3; \
Ubpa::details::Swizzle<Impl, EI1, EI0, EI0, EI0> E1##E0##E0##E0; \
Ubpa::details::Swizzle<Impl, EI1, EI0, EI0, EI1> E1##E0##E0##E1; \
Ubpa::details::Swizzle<Impl, EI1, EI0, EI0, EI2> E1##E0##E0##E2; \
Ubpa::details::Swizzle<Impl, EI1, EI0, EI0, EI3> E1##E0##E0##E3; \
Ubpa::details::Swizzle<Impl, EI1, EI0, EI1, EI0> E1##E0##E1##E0; \
Ubpa::details::Swizzle<Impl, EI1, EI0, EI1, EI1> E1##E0##E1##E1; \
Ubpa::details::Swizzle<Impl, EI1, EI0, EI1, EI2> E1##E0##E1##E2; \
Ubpa::details::Swizzle<Impl, EI1, EI0, EI1, EI3> E1##E0##E1##E3; \
Ubpa::details::Swizzle<Impl, EI1, EI0, EI2, EI0> E1##E0##E2##E0; \
Ubpa::details::Swizzle<Impl, EI1, EI0, EI2, EI1> E1##E0##E2##E1; \
Ubpa::details::Swizzle<Impl, EI1, EI0, EI2, EI2> E1##E0##E2##E2; \
Ubpa::details::Swizzle<Impl, EI1, EI0, EI2, EI3> E1##E0##E2##E3; \
Ubpa::details::Swizzle<Impl, EI1, EI0, EI3, EI0> E1##E0##E3##E0; \
Ubpa::details::Swizzle<Impl, EI1, EI0, EI3, EI1> E1##E0##E3##E1; \
Ubpa::details::Swizzle<Impl, EI1, EI0, EI3, EI2> E1##E0##E3##E2; \
Ubpa::details::Swizzle<Impl, EI1, EI0, EI3, EI3> E1##E0##E3##E3; \
Ubpa::details::Swizzle<Impl, EI1, EI1, EI0, EI0> E1##E1##E0##E0; \
Ubpa::details::Swizzle<Impl, EI1, EI1, EI0, EI1> E1##E1##E0##E1; \
Ubpa::details::Swizzle<Impl, EI1, EI1, EI0, EI2> E1##E1##E0##E2; \
Ubpa::details::Swizzle<Impl, EI1, EI1, EI0, EI3> E1##E1##E0##E3; \
Ubpa::details::Swizzle<Impl, EI1, EI1, EI1, EI0> E1##E1##E1##E0; \
Ubpa::details::Swizzle<Impl, EI1, EI1, EI1, EI1> E1##E1##E1##E1; \
Ubpa::details::Swizzle<Impl, EI1, EI1, EI1, EI2> E1##E1##E1##E2; \
Ubpa::details::Swizzle<Impl, EI1, EI1, EI1, EI3> E1##E1##E1##E3; \
Ubpa::details::Swizzle<Impl, EI1, EI1, EI2, EI0> E1##E1##E2##E0; \
Ubpa::details::Swizzle<Impl, EI1, EI1, EI2, EI1> E1##E1##E2##E1; \
Ubpa::details::Swizzle<Impl, EI1, EI1, EI2, EI2> E1##E1##E2##E2; \
Ubpa::details::Swizzle<Impl, EI1, EI1, EI2, EI3> E1##E1##E2##E3; \
Ubpa::details::Swizzle<Impl, EI1, EI1, EI3, EI0> E1##E1##E3##E0; \
Ubpa::details::Swizzle<Impl, EI1, EI1, EI3, EI1> E1##E1##E3##E1; \
Ubpa::details::Swizzle<Impl, EI1, EI1, EI3, EI2> E1##E1##E3##E2; \
Ubpa::details::Swizzle<Impl, EI1, EI1, EI3, EI3> E1##E1##E3##E3; \
Ubpa::details::Swizzle<Impl, EI1, EI2, EI0, EI0> E1##E2##E0##E0; \
Ubpa::details::Swizzle<Impl, EI1, EI2, EI0, EI1> E1##E2##E0##E1; \
Ubpa::details::Swizzle<Impl, EI1, EI2, EI0, EI2> E1##E2##E0##E2; \
Ubpa::details::Swizzle<Impl, EI1, EI2, EI0, EI3> E1##E2##E0##E3; \
Ubpa::details::Swizzle<Impl, EI1, EI2, EI1, EI0> E1##E2##E1##E0; \
Ubpa::details::Swizzle<Impl, EI1, EI2, EI1, EI1> E1##E2##E1##E1; \
Ubpa::details::Swizzle<Impl, EI1, EI2, EI1, EI2> E1##E2##E1##E2; \
Ubpa::details::Swizzle<Impl, EI1, EI2, EI1, EI3> E1##E2##E1##E3; \
Ubpa::details::Swizzle<Impl, EI1, EI2, EI2, EI0> E1##E2##E2##E0; \
Ubpa::details::Swizzle<Impl, EI1, EI2, EI2, EI1> E1##E2##E2##E1; \
Ubpa::details::Swizzle<Impl, EI1, EI2, EI2, EI2> E1##E2##E2##E2; \
Ubpa::details::Swizzle<Impl, EI1, EI2, EI2, EI3> E1##E2##E2##E3; \
Ubpa::details::Swizzle<Impl, EI1, EI2, EI3, EI0> E1##E2##E3##E0; \
Ubpa::details::Swizzle<Impl, EI1, EI2, EI3, EI1> E1##E2##E3##E1; \
Ubpa::details::Swizzle<Impl, EI1, EI2, EI3, EI2> E1##E2##E3##E2; \
Ubpa::details::Swizzle<Impl, EI1, EI2, EI3, EI3> E1##E2##E3##E3; \
Ubpa::details::Swizzle<Impl, EI1, EI3, EI0, EI0> E1##E3##E0##E0; \
Ubpa::details::Swizzle<Impl, EI1, EI3, EI0, EI1> E1##E3##E0##E1; \
Ubpa::details::Swizzle<Impl, EI1, EI3, EI0, EI2> E1##E3##E0##E2; \
Ubpa::details::Swizzle<Impl, EI1, EI3, EI0, EI3> E1##E3##E0##E3; \
Ubpa::details::Swizzle<Impl, EI1, EI3, EI1, EI0> E1##E3##E1##E0; \
Ubpa::details::Swizzle<Impl, EI1, EI3, EI1, EI1> E1##E3##E1##E1; \
Ubpa::details::Swizzle<Impl, EI1, EI3, EI1, EI2> E1##E3##E1##E2; \
Ubpa::details::Swizzle<Impl, EI1, EI3, EI1, EI3> E1##E3##E1##E3; \
Ubpa::details::Swizzle<Impl, EI1, EI3, EI2, EI0> E1##E3##E2##E0; \
Ubpa::details::Swizzle<Impl, EI1, EI3, EI2, EI1> E1##E3##E2##E1; \
Ubpa::details::Swizzle<Impl, EI1, EI3, EI2, EI2> E1##E3##E2##E2; \
Ubpa::details::Swizzle<Impl, EI1, EI3, EI2, EI3> E1##E3##E2##E3; \
Ubpa::details::Swizzle<Impl, EI1, EI3, EI3, EI0> E1##E3##E3##E0; \
Ubpa::details::Swizzle<Impl, EI1, EI3, EI3, EI1> E1##E3##E3##E1; \
Ubpa::details::Swizzle<Impl, EI1, EI3, EI3, EI2> E1##E3##E3##E2; \
Ubpa::details::Swizzle<Impl, EI1, EI3, EI3, EI3> E1##E3##E3##E3; \
Ubpa::details::Swizzle<Impl, EI2, EI0, EI0, EI0> E2##E0##E0##E0; \
Ubpa::details::Swizzle<Impl, EI2, EI0, EI0, EI1> E2##E0##E0##E1; \
Ubpa::details::Swizzle<Impl, EI2, EI0, EI0, EI2> E2##E0##E0##E2; \
Ubpa::details::Swizzle<Impl, EI2, EI0, EI0, EI3> E2##E0##E0##E3; \
Ubpa::details::Swizzle<Impl, EI2, EI0, EI1, EI0> E2##E0##E1##E0; \
Ubpa::details::Swizzle<Impl, EI2, EI0, EI1, EI1> E2##E0##E1##E1; \
Ubpa::details::Swizzle<Impl, EI2, EI0, EI1, EI2> E2##E0##E1##E2; \
Ubpa::details::Swizzle<Impl, EI2, EI0, EI1, EI3> E2##E0##E1##E3; \
Ubpa::details::Swizzle<Impl, EI2, EI0, EI2, EI0> E2##E0##E2##E0; \
Ubpa::details::Swizzle<Impl, EI2, EI0, EI2, EI1> E2##E0##E2##E1; \
Ubpa::details::Swizzle<Impl, EI2, EI0, EI2, EI2> E2##E0##E2##E2; \
Ubpa::details::Swizzle<Impl, EI2, EI0, EI2, EI3> E2##E0##E2##E3; \
Ubpa::details::Swizzle<Impl, EI2, EI0, EI3, EI0> E2##E0##E3##E0; \
Ubpa::details::Swizzle<Impl, EI2, EI0, EI3, EI1> E2##E0##E3##E1; \
Ubpa::details::Swizzle<Impl, EI2, EI0, EI3, EI2> E2##E0##E3##E2; \
Ubpa::details::Swizzle<Impl, EI2, EI0, EI3, EI3> E2##E0##E3##E3; \
Ubpa::details::Swizzle<Impl, EI2, EI1, EI0, EI0> E2##E1##E0##E0; \
Ubpa::details::Swizzle<Impl, EI2, EI1, EI0, EI1> E2##E1##E0##E1; \
Ubpa::details::Swizzle<Impl, EI2, EI1, EI0, EI2> E2##E1##E0##E2; \
Ubpa::details::Swizzle<Impl, EI2, EI1, EI0, EI3> E2##E1##E0##E3; \
Ubpa::details::Swizzle<Impl, EI2, EI1, EI1, EI0> E2##E1##E1##E0; \
Ubpa::details::Swizzle<Impl, EI2, EI1, EI1, EI1> E2##E1##E1##E1; \
Ubpa::details::Swizzle<Impl, EI2, EI1, EI1, EI2> E2##E1##E1##E2; \
Ubpa::details::Swizzle<Impl, EI2, EI1, EI1, EI3> E2##E1##E1##E3; \
Ubpa::details::Swizzle<Impl, EI2, EI1, EI2, EI0> E2##E1##E2##E0; \
Ubpa::details::Swizzle<Impl, EI2, EI1, EI2, EI1> E2##E1##E2##E1; \
Ubpa::details::Swizzle<Impl, EI2, EI1, EI2, EI2> E2##E1##E2##E2; \
Ubpa::details::Swizzle<Impl, EI2, EI1, EI2, EI3> E2##E1##E2##E3; \
Ubpa::details::Swizzle<Impl, EI2, EI1, EI3, EI0> E2##E1##E3##E0; \
Ubpa::details::Swizzle<Impl, EI2, EI1, EI3, EI1> E2##E1##E3##E1; \
Ubpa::details::Swizzle<Impl, EI2, EI1, EI3, EI2> E2##E1##E3##E2; \
Ubpa::details::Swizzle<Impl, EI2, EI1, EI3, EI3> E2##E1##E3##E3; \
Ubpa::details::Swizzle<Impl, EI2, EI2, EI0, EI0> E2##E2##E0##E0; \
Ubpa::details::Swizzle<Impl, EI2, EI2, EI0, EI1> E2##E2##E0##E1; \
Ubpa::details::Swizzle<Impl, EI2, EI2, EI0, EI2> E2##E2##E0##E2; \
Ubpa::details::Swizzle<Impl, EI2, EI2, EI0, EI3> E2##E2##E0##E3; \
Ubpa::details::Swizzle<Impl, EI2, EI2, EI1, EI0> E2##E2##E1##E0; \
Ubpa::details::Swizzle<Impl, EI2, EI2, EI1, EI1> E2##E2##E1##E1; \
Ubpa::details::Swizzle<Impl, EI2, EI2, EI1, EI2> E2##E2##E1##E2; \
Ubpa::details::Swizzle<Impl, EI2, EI2, EI1, EI3> E2##E2##E1##E3; \
Ubpa::details::Swizzle<Impl, EI2, EI2, EI2, EI0> E2##E2##E2##E0; \
Ubpa::details::Swizzle<Impl, EI2, EI2, EI2, EI1> E2##E2##E2##E1; \
Ubpa::details::Swizzle<Impl, EI2, EI2, EI2, EI2> E2##E2##E2##E2; \
Ubpa::details::Swizzle<Impl, EI2, EI2, EI2, EI3> E2##E2##E2##E3; \
Ubpa::details::Swizzle<Impl, EI2, EI2, EI3, EI0> E2##E2##E3##E0; \
Ubpa::details::Swizzle<Impl, EI2, EI2, EI3, EI1> E2##E2##E3##E1; \
Ubpa::details::Swizzle<Impl, EI2, EI2, EI3, EI2> E2##E2##E3##E2; \
Ubpa::details::Swizzle<Impl, EI2, EI2, EI3, EI3> E2##E2##E3##E3; \
Ubpa::details::Swizzle<Impl, EI2, EI3, EI0, EI0> E2##E3##E0##E0; \
Ubpa::details::Swizzle<Impl, EI2, EI3, EI0, EI1> E2##E3##E0##E1; \
Ubpa::details::Swizzle<Impl, EI2, EI3, EI0, EI2> E2##E3##E0##E2; \
Ubpa::details::Swizzle<Impl, EI2, EI3, EI0, EI3> E2##E3##E0##E3; \
Ubpa::details::Swizzle<Impl, EI2, EI3, EI1, EI0> E2##E3##E1##E0; \
Ubpa::details::Swizzle<Impl, EI2, EI3, EI1, EI1> E2##E3##E1##E1; \
Ubpa::details::Swizzle<Impl, EI2, EI3, EI1, EI2> E2##E3##E1##E2; \
Ubpa::details::Swizzle<Impl, EI2, EI3, EI1, EI3> E2##E3##E1##E3; \
Ubpa::details::Swizzle<Impl, EI2, EI3, EI2, EI0> E2##E3##E2##E0; \
Ubpa::details::Swizzle<Impl, EI2, EI3, EI2, EI1> E2##E3##E2##E1; \
Ubpa::details::Swizzle<Impl, EI2, EI3, EI2, EI2> E2##E3##E2##E2; \
Ubpa::details::Swizzle<Impl, EI2, EI3, EI2, EI3> E2##E3##E2##E3; \
Ubpa::details::Swizzle<Impl, EI2, EI3, EI3, EI0> E2##E3##E3##E0; \
Ubpa::details::Swizzle<Impl, EI2, EI3, EI3, EI1> E2##E3##E3##E1; \
Ubpa::details::Swizzle<Impl, EI2, EI3, EI3, EI2> E2##E3##E3##E2; \
Ubpa::details::Swizzle<Impl, EI2, EI3, EI3, EI3> E2##E3##E3##E3; \
Ubpa::details::Swizzle<Impl, EI3, EI0, EI0, EI0> E3##E0##E0##E0; \
Ubpa::details::Swizzle<Impl, EI3, EI0, EI0, EI1> E3##E0##E0##E1; \
Ubpa::details::Swizzle<Impl, EI3, EI0, EI0, EI2> E3##E0##E0##E2; \
Ubpa::details::Swizzle<Impl, EI3, EI0, EI0, EI3> E3##E0##E0##E3; \
Ubpa::details::Swizzle<Impl, EI3, EI0, EI1, EI0> E3##E0##E1##E0; \
Ubpa::details::Swizzle<Impl, EI3, EI0, EI1, EI1> E3##E0##E1##E1; \
Ubpa::details::Swizzle<Impl, EI3, EI0, EI1, EI2> E3##E0##E1##E2; \
Ubpa::details::Swizzle<Impl, EI3, EI0, EI1, EI3> E3##E0##E1##E3; \
Ubpa::details::Swizzle<Impl, EI3, EI0, EI2, EI0> E3##E0##E2##E0; \
Ubpa::details::Swizzle<Impl, EI3, EI0, EI2, EI1> E3##E0##E2##E1; \
Ubpa::details::Swizzle<Impl, EI3, EI0, EI2, EI2> E3##E0##E2##E2; \
Ubpa::details::Swizzle<Impl, EI3, EI0, EI2, EI3> E3##E0##E2##E3; \
Ubpa::details::Swizzle<Impl, EI3, EI0, EI3, EI0> E3##E0##E3##E0; \
Ubpa::details::Swizzle<Impl, EI3, EI0, EI3, EI1> E3##E0##E3##E1; \
Ubpa::details::Swizzle<Impl, EI3, EI0, EI3, EI2> E3##E0##E3##E2; \
Ubpa::details::Swizzle<Impl, EI3, EI0, EI3, EI3> E3##E0##E3##E3; \
Ubpa::details::Swizzle<Impl, EI3, EI1, EI0, EI0> E3##E1##E0##E0; \
Ubpa::details::Swizzle<Impl, EI3, EI1, EI0, EI1> E3##E1##E0##E1; \
Ubpa::details::Swizzle<Impl, EI3, EI1, EI0, EI2> E3##E1##E0##E2; \
Ubpa::details::Swizzle<Impl, EI3, EI1, EI0, EI3> E3##E1##E0##E3; \
Ubpa::details::Swizzle<Impl, EI3, EI1, EI1, EI0> E3##E1##E1##E0; \
Ubpa::details::Swizzle<Impl, EI3, EI1, EI1, EI1> E3##E1##E1##E1; \
Ubpa::details::Swizzle<Impl, EI3, EI1, EI1, EI2> E3##E1##E1##E2; \
Ubpa::details::Swizzle<Impl, EI3, EI1, EI1, EI3> E3##E1##E1##E3; \
Ubpa::details::Swizzle<Impl, EI3, EI1, EI2, EI0> E3##E1##E2##E0; \
Ubpa::details::Swizzle<Impl, EI3, EI1, EI2, EI1> E3##E1##E2##E1; \
Ubpa::details::Swizzle<Impl, EI3, EI1, EI2, EI2> E3##E1##E2##E2; \
Ubpa::details::Swizzle<Impl, EI3, EI1, EI2, EI3> E3##E1##E2##E3; \
Ubpa::details::Swizzle<Impl, EI3, EI1, EI3, EI0> E3##E1##E3##E0; \
Ubpa::details::Swizzle<Impl, EI3, EI1, EI3, EI1> E3##E1##E3##E1; \
Ubpa::details::Swizzle<Impl, EI3, EI1, EI3, EI2> E3##E1##E3##E2; \
Ubpa::details::Swizzle<Impl, EI3, EI1, EI3, EI3> E3##E1##E3##E3; \
Ubpa::details::Swizzle<Impl, EI3, EI2, EI0, EI0> E3##E2##E0##E0; \
Ubpa::details::Swizzle<Impl, EI3, EI2, EI0, EI1> E3##E2##E0##E1; \
Ubpa::details::Swizzle<Impl, EI3, EI2, EI0, EI2> E3##E2##E0##E2; \
Ubpa::details::Swizzle<Impl, EI3, EI2, EI0, EI3> E3##E2##E0##E3; \
Ubpa::details::Swizzle<Impl, EI3, EI2, EI1, EI0> E3##E2##E1##E0; \
Ubpa::details::Swizzle<Impl, EI3, EI2, EI1, EI1> E3##E2##E1##E1; \
Ubpa::details::Swizzle<Impl, EI3, EI2, EI1, EI2> E3##E2##E1##E2; \
Ubpa::details::Swizzle<Impl, EI3, EI2, EI1, EI3> E3##E2##E1##E3; \
Ubpa::details::Swizzle<Impl, EI3, EI2, EI2, EI0> E3##E2##E2##E0; \
Ubpa::details::Swizzle<Impl, EI3, EI2, EI2, EI1> E3##E2##E2##E1; \
Ubpa::details::Swizzle<Impl, EI3, EI2, EI2, EI2> E3##E2##E2##E2; \
Ubpa::details::Swizzle<Impl, EI3, EI2, EI2, EI3> E3##E2##E2##E3; \
Ubpa::details::Swizzle<Impl, EI3, EI2, EI3, EI0> E3##E2##E3##E0; \
Ubpa::details::Swizzle<Impl, EI3, EI2, EI3, EI1> E3##E2##E3##E1; \
Ubpa::details::Swizzle<Impl, EI3, EI2, EI3, EI2> E3##E2##E3##E2; \
Ubpa::details::Swizzle<Impl, EI3, EI2, EI3, EI3> E3##E2##E3##E3; \
Ubpa::details::Swizzle<Impl, EI3, EI3, EI0, EI0> E3##E3##E0##E0; \
Ubpa::details::Swizzle<Impl, EI3, EI3, EI0, EI1> E3##E3##E0##E1; \
Ubpa::details::Swizzle<Impl, EI3, EI3, EI0, EI2> E3##E3##E0##E2; \
Ubpa::details::Swizzle<Impl, EI3, EI3, EI0, EI3> E3##E3##E0##E3; \
Ubpa::details::Swizzle<Impl, EI3, EI3, EI1, EI0> E3##E3##E1##E0; \
Ubpa::details::Swizzle<Impl, EI3, EI3, EI1, EI1> E3##E3##E1##E1; \
Ubpa::details::Swizzle<Impl, EI3, EI3, EI1, EI2> E3##E3##E1##E2; \
Ubpa::details::Swizzle<Impl, EI3, EI3, EI1, EI3> E3##E3##E1##E3; \
Ubpa::details::Swizzle<Impl, EI3, EI3, EI2, EI0> E3##E3##E2##E0; \
Ubpa::details::Swizzle<Impl, EI3, EI3, EI2, EI1> E3##E3##E2##E1; \
Ubpa::details::Swizzle<Impl, EI3, EI3, EI2, EI2> E3##E3##E2##E2; \
Ubpa::details::Swizzle<Impl, EI3, EI3, EI2, EI3> E3##E3##E2##E3; \
Ubpa::details::Swizzle<Impl, EI3, EI3, EI3, EI0> E3##E3##E3##E0; \
Ubpa::details::Swizzle<Impl, EI3, EI3, EI3, EI1> E3##E3##E3##E1; \
Ubpa::details::Swizzle<Impl, EI3, EI3, EI3, EI2> E3##E3##E3##E2; \
Ubpa::details::Swizzle<Impl, EI3, EI3, EI3, EI3> E3##E3##E3##E3
#define UBPA_ARRAY_SWIZZLE3_2(EI0, EI1, EI2, E0, E1, E2) \
Ubpa::details::Swizzle<Impl, EI0, EI0> E0##E0; \
Ubpa::details::Swizzle<Impl, EI0, EI1> E0##E1; \
Ubpa::details::Swizzle<Impl, EI0, EI2> E0##E2; \
Ubpa::details::Swizzle<Impl, EI1, EI0> E1##E0; \
Ubpa::details::Swizzle<Impl, EI1, EI1> E1##E1; \
Ubpa::details::Swizzle<Impl, EI1, EI2> E1##E2; \
Ubpa::details::Swizzle<Impl, EI2, EI0> E2##E0; \
Ubpa::details::Swizzle<Impl, EI2, EI1> E2##E1; \
Ubpa::details::Swizzle<Impl, EI2, EI2> E2##E2
#define UBPA_ARRAY_SWIZZLE4_2(EI0, EI1, EI2, EI3, E0, E1, E2, E3) \
Ubpa::details::Swizzle<Impl, EI0, EI0> E0##E0; \
Ubpa::details::Swizzle<Impl, EI0, EI1> E0##E1; \
Ubpa::details::Swizzle<Impl, EI0, EI2> E0##E2; \
Ubpa::details::Swizzle<Impl, EI0, EI3> E0##E3; \
Ubpa::details::Swizzle<Impl, EI1, EI0> E1##E0; \
Ubpa::details::Swizzle<Impl, EI1, EI1> E1##E1; \
Ubpa::details::Swizzle<Impl, EI1, EI2> E1##E2; \
Ubpa::details::Swizzle<Impl, EI1, EI3> E1##E3; \
Ubpa::details::Swizzle<Impl, EI2, EI0> E2##E0; \
Ubpa::details::Swizzle<Impl, EI2, EI1> E2##E1; \
Ubpa::details::Swizzle<Impl, EI2, EI2> E2##E2; \
Ubpa::details::Swizzle<Impl, EI2, EI3> E2##E3; \
Ubpa::details::Swizzle<Impl, EI3, EI0> E3##E0; \
Ubpa::details::Swizzle<Impl, EI3, EI1> E3##E1; \
Ubpa::details::Swizzle<Impl, EI3, EI2> E3##E2; \
Ubpa::details::Swizzle<Impl, EI3, EI3> E3##E3
#define UBPA_ARRAY_SWIZZLE4_3(EI0, EI1, EI2, EI3, E0, E1, E2, E3) \
Ubpa::details::Swizzle<Impl, EI0, EI0, EI0> E0##E0##E0; \
Ubpa::details::Swizzle<Impl, EI0, EI0, EI1> E0##E0##E1; \
Ubpa::details::Swizzle<Impl, EI0, EI0, EI2> E0##E0##E2; \
Ubpa::details::Swizzle<Impl, EI0, EI0, EI3> E0##E0##E3; \
Ubpa::details::Swizzle<Impl, EI0, EI1, EI0> E0##E1##E0; \
Ubpa::details::Swizzle<Impl, EI0, EI1, EI1> E0##E1##E1; \
Ubpa::details::Swizzle<Impl, EI0, EI1, EI2> E0##E1##E2; \
Ubpa::details::Swizzle<Impl, EI0, EI1, EI3> E0##E1##E3; \
Ubpa::details::Swizzle<Impl, EI0, EI2, EI0> E0##E2##E0; \
Ubpa::details::Swizzle<Impl, EI0, EI2, EI1> E0##E2##E1; \
Ubpa::details::Swizzle<Impl, EI0, EI2, EI2> E0##E2##E2; \
Ubpa::details::Swizzle<Impl, EI0, EI2, EI3> E0##E2##E3; \
Ubpa::details::Swizzle<Impl, EI0, EI3, EI0> E0##E3##E0; \
Ubpa::details::Swizzle<Impl, EI0, EI3, EI1> E0##E3##E1; \
Ubpa::details::Swizzle<Impl, EI0, EI3, EI2> E0##E3##E2; \
Ubpa::details::Swizzle<Impl, EI0, EI3, EI3> E0##E3##E3; \
Ubpa::details::Swizzle<Impl, EI1, EI0, EI0> E1##E0##E0; \
Ubpa::details::Swizzle<Impl, EI1, EI0, EI1> E1##E0##E1; \
Ubpa::details::Swizzle<Impl, EI1, EI0, EI2> E1##E0##E2; \
Ubpa::details::Swizzle<Impl, EI1, EI0, EI3> E1##E0##E3; \
Ubpa::details::Swizzle<Impl, EI1, EI1, EI0> E1##E1##E0; \
Ubpa::details::Swizzle<Impl, EI1, EI1, EI1> E1##E1##E1; \
Ubpa::details::Swizzle<Impl, EI1, EI1, EI2> E1##E1##E2; \
Ubpa::details::Swizzle<Impl, EI1, EI1, EI3> E1##E1##E3; \
Ubpa::details::Swizzle<Impl, EI1, EI2, EI0> E1##E2##E0; \
Ubpa::details::Swizzle<Impl, EI1, EI2, EI1> E1##E2##E1; \
Ubpa::details::Swizzle<Impl, EI1, EI2, EI2> E1##E2##E2; \
Ubpa::details::Swizzle<Impl, EI1, EI2, EI3> E1##E2##E3; \
Ubpa::details::Swizzle<Impl, EI1, EI3, EI0> E1##E3##E0; \
Ubpa::details::Swizzle<Impl, EI1, EI3, EI1> E1##E3##E1; \
Ubpa::details::Swizzle<Impl, EI1, EI3, EI2> E1##E3##E2; \
Ubpa::details::Swizzle<Impl, EI1, EI3, EI3> E1##E3##E3; \
Ubpa::details::Swizzle<Impl, EI2, EI0, EI0> E2##E0##E0; \
Ubpa::details::Swizzle<Impl, EI2, EI0, EI1> E2##E0##E1; \
Ubpa::details::Swizzle<Impl, EI2, EI0, EI2> E2##E0##E2; \
Ubpa::details::Swizzle<Impl, EI2, EI0, EI3> E2##E0##E3; \
Ubpa::details::Swizzle<Impl, EI2, EI1, EI0> E2##E1##E0; \
Ubpa::details::Swizzle<Impl, EI2, EI1, EI1> E2##E1##E1; \
Ubpa::details::Swizzle<Impl, EI2, EI1, EI2> E2##E1##E2; \
Ubpa::details::Swizzle<Impl, EI2, EI1, EI3> E2##E1##E3; \
Ubpa::details::Swizzle<Impl, EI2, EI2, EI0> E2##E2##E0; \
Ubpa::details::Swizzle<Impl, EI2, EI2, EI1> E2##E2##E1; \
Ubpa::details::Swizzle<Impl, EI2, EI2, EI2> E2##E2##E2; \
Ubpa::details::Swizzle<Impl, EI2, EI2, EI3> E2##E2##E3; \
Ubpa::details::Swizzle<Impl, EI2, EI3, EI0> E2##E3##E0; \
Ubpa::details::Swizzle<Impl, EI2, EI3, EI1> E2##E3##E1; \
Ubpa::details::Swizzle<Impl, EI2, EI3, EI2> E2##E3##E2; \
Ubpa::details::Swizzle<Impl, EI2, EI3, EI3> E2##E3##E3; \
Ubpa::details::Swizzle<Impl, EI3, EI0, EI0> E3##E0##E0; \
Ubpa::details::Swizzle<Impl, EI3, EI0, EI1> E3##E0##E1; \
Ubpa::details::Swizzle<Impl, EI3, EI0, EI2> E3##E0##E2; \
Ubpa::details::Swizzle<Impl, EI3, EI0, EI3> E3##E0##E3; \
Ubpa::details::Swizzle<Impl, EI3, EI1, EI0> E3##E1##E0; \
Ubpa::details::Swizzle<Impl, EI3, EI1, EI1> E3##E1##E1; \
Ubpa::details::Swizzle<Impl, EI3, EI1, EI2> E3##E1##E2; \
Ubpa::details::Swizzle<Impl, EI3, EI1, EI3> E3##E1##E3; \
Ubpa::details::Swizzle<Impl, EI3, EI2, EI0> E3##E2##E0; \
Ubpa::details::Swizzle<Impl, EI3, EI2, EI1> E3##E2##E1; \
Ubpa::details::Swizzle<Impl, EI3, EI2, EI2> E3##E2##E2; \
Ubpa::details::Swizzle<Impl, EI3, EI2, EI3> E3##E2##E3; \
Ubpa::details::Swizzle<Impl, EI3, EI3, EI0> E3##E3##E0; \
Ubpa::details::Swizzle<Impl, EI3, EI3, EI1> E3##E3##E1; \
Ubpa::details::Swizzle<Impl, EI3, EI3, EI2> E3##E3##E2; \
Ubpa::details::Swizzle<Impl, EI3, EI3, EI3> E3##E3##E3
#define UBPA_ARRAY_SWIZZLE2(E0, E1) UBPA_ARRAY_SWIZZLE2_2(0, 1, E0, E1)
#define UBPA_ARRAY_SWIZZLE3(E0, E1, E2) \
UBPA_ARRAY_SWIZZLE3_2(0, 1, 2, E0, E1, E2); \
UBPA_ARRAY_SWIZZLE3_3(0, 1, 2, E0, E1, E2)
#define UBPA_ARRAY_SWIZZLE4(E0, E1, E2, E3) \
UBPA_ARRAY_SWIZZLE4_2(0, 1, 2, 3, E0, E1, E2, E3); \
UBPA_ARRAY_SWIZZLE4_3(0, 1, 2, 3, E0, E1, E2, E3); \
UBPA_ARRAY_SWIZZLE4_4(0, 1, 2, 3, E0, E1, E2, E3)
namespace Ubpa {
template<details::ArrayMode mode, typename IArray_Base, typename Impl>
struct IArray_Impl;
/*
* IArray -> IArray_Impl -> IArrayCommon -> IStdArray -> IStdArrayBasic -> Base
* IArray (SIMD) -> IArray_Impl -> IStdArrayBasic -> Base
*/
template<typename Base, typename Impl>
struct IArray : IArray_Impl<details::GetArrayMode<Impl>(), Base, Impl> {
using IArray_Impl<details::GetArrayMode<Impl>(), Base, Impl>::IArray_Impl;
};
template<typename IArray_Base, typename Impl>
struct alignas(alignof(SI_ImplTraits_T<Impl>)) IArray_Impl<details::ArrayMode::One, IArray_Base, Impl>
: details::IArrayCommon<IArray_Base, Impl>
{
using T = SI_ImplTraits_T<Impl>;
static_assert(SI_ImplTraits_N<Impl> == 1);
union {
T _Elems[1];
struct { T x; };
struct { T r; };
struct { T s; };
};
using details::IArrayCommon<IArray_Base, Impl>::IArrayCommon;
};
template<typename IArray_Base, typename Impl>
struct alignas(alignof(SI_ImplTraits_T<Impl>)) IArray_Impl<details::ArrayMode::Two, IArray_Base, Impl>
: details::IArrayCommon<IArray_Base, Impl>
{
using T = SI_ImplTraits_T<Impl>;
static_assert(SI_ImplTraits_N<Impl> == 2);
union {
T _Elems[2];
struct { T x, y; };
struct { T r, g; };
struct { T s, t; };
UBPA_ARRAY_SWIZZLE2(x, y);
UBPA_ARRAY_SWIZZLE2(r, g);
UBPA_ARRAY_SWIZZLE2(s, t);
};
using details::IArrayCommon<IArray_Base, Impl>::IArrayCommon;
template<typename... Us, std::enable_if_t<sizeof...(Us) == 2, int> = 0>
constexpr IArray_Impl(Us... vals) noexcept : _Elems{ static_cast<T>(vals)... } {}
};
template<typename IArray_Base, typename Impl>
struct alignas(alignof(SI_ImplTraits_T<Impl>)) IArray_Impl<details::ArrayMode::Three, IArray_Base, Impl>
: details::IArrayCommon<IArray_Base, Impl>
{
using T = SI_ImplTraits_T<Impl>;
static_assert(SI_ImplTraits_N<Impl> == 3);
union {
T _Elems[3];
struct { T x, y, z; };
struct { T r, g, b; };
struct { T s, t, p; };
UBPA_ARRAY_SWIZZLE3(x, y, z);
UBPA_ARRAY_SWIZZLE3(r, g, b);
UBPA_ARRAY_SWIZZLE3(s, t, p);
};
using details::IArrayCommon<IArray_Base, Impl>::IArrayCommon;
template<typename... Us, std::enable_if_t<sizeof...(Us) == 3, int> = 0>
constexpr IArray_Impl(Us... vals) noexcept : _Elems{ static_cast<T>(vals)... } {}
};
template<typename IArray_Base, typename Impl>
struct alignas(alignof(SI_ImplTraits_T<Impl>)) IArray_Impl<details::ArrayMode::Four, IArray_Base, Impl>
: details::IArrayCommon<IArray_Base, Impl>
{
using T = SI_ImplTraits_T<Impl>;
static_assert(SI_ImplTraits_N<Impl> == 4);
union {
T _Elems[4];
struct { T x, y, z, w; };
struct { T r, g, b, a; };
struct { T s, t, p, q; };
UBPA_ARRAY_SWIZZLE4(x, y, z, w);
UBPA_ARRAY_SWIZZLE4(r, g, b, a);
UBPA_ARRAY_SWIZZLE4(s, t, p, q);
};
using details::IArrayCommon<IArray_Base, Impl>::IArrayCommon;
template<typename... Us, std::enable_if_t<sizeof...(Us) == 4, int> = 0>
constexpr IArray_Impl(Us... vals) noexcept : _Elems{ static_cast<T>(vals)... } {}
};
template<typename IArray_Base, typename Impl>
struct alignas(alignof(SI_ImplTraits_T<Impl>)) IArray_Impl<details::ArrayMode::Basic, IArray_Base, Impl>
: details::IArrayCommon<IArray_Base, Impl>
{
using T = SI_ImplTraits_T<Impl>;
static constexpr std::size_t N = SI_ImplTraits_N<Impl>;
T _Elems[N];
using details::IArrayCommon<IArray_Base, Impl>::IArrayCommon;
template<typename... Us, std::enable_if_t<sizeof...(Us) == N, int> = 0>
constexpr IArray_Impl(Us... vals) noexcept : _Elems{static_cast<T>(vals)...} {}
};
#ifdef UBPA_UGM_USE_SIMD
template<typename IArray_Base, typename Impl>
struct alignas(16) IArray_Impl<details::ArrayMode::Four_SIMD, IArray_Base, Impl>
: details::IStdArrayBasic<IArray_Base, Impl>
{
public:
using T = float;
static constexpr size_t N = 4;
using F = float;
union {
__m128 m;
T _Elems[4];
struct { T x, y, z, w; };
struct { T r, g, b, a; };
struct { T s, t, p, q; };
UBPA_ARRAY_SWIZZLE4(x, y, z, w);
UBPA_ARRAY_SWIZZLE4(r, g, b, a);
UBPA_ARRAY_SWIZZLE4(s, t, p, q);
};
friend bool operator==(const Impl& x, const Impl& y) noexcept {
return _mm_movemask_ps(_mm_cmpeq_ps(x, y)) == 0xf;
}
friend bool operator!=(const Impl& x, const Impl& y) noexcept {
return _mm_movemask_ps(_mm_cmpneq_ps(x, y)) == 0xf;
}
friend bool operator<(const Impl& x, const Impl& y) noexcept {
int mask_lt = _mm_movemask_ps(_mm_cmplt_ps(x, y));
int mask_eq = _mm_movemask_ps(_mm_cmpeq_ps(x, y));
for (size_t i = 0; i < 4; i++) {
int cur_bit = (1 << i);
if (mask_eq & cur_bit)
continue;
if (mask_lt & cur_bit)
return true;
else
return false;
}
return false;
}
friend bool operator<=(const Impl& x, const Impl& y) noexcept {
int mask_lt = _mm_movemask_ps(_mm_cmplt_ps(x, y));
int mask_eq = _mm_movemask_ps(_mm_cmpeq_ps(x, y));
for (size_t i = 0; i < 4; i++) {
int cur_bit = (1 << i);
if (mask_eq & cur_bit)
continue;
if (mask_lt & cur_bit)
return true;
else
return false;
}
return true;
}
friend bool operator>(const Impl& x, const Impl& y) noexcept {
int mask_lt = _mm_movemask_ps(_mm_cmplt_ps(x, y));
int mask_eq = _mm_movemask_ps(_mm_cmpeq_ps(x, y));
for (size_t i = 0; i < 4; i++) {
int cur_bit = (1 << i);
if (mask_eq & cur_bit)
continue;
if (mask_lt & cur_bit)
return false;
else
return true;
}
return false;
}
friend bool operator>=(const Impl& x, const Impl& y) noexcept {
int mask_lt = _mm_movemask_ps(_mm_cmplt_ps(x, y));
int mask_eq = _mm_movemask_ps(_mm_cmpeq_ps(x, y));
for (size_t i = 0; i < 4; i++) {
int cur_bit = (1 << i);
if (mask_eq & cur_bit)
continue;
if (mask_lt & cur_bit)
return false;
else
return true;
}
return true;
}
bool lex_lt(const Impl& y) const noexcept {
const auto& x = static_cast<const Impl&>(*this);
return x < y;
}
bool lex_le(const Impl& y) const noexcept {
const auto& x = static_cast<const Impl&>(*this);
return x <= y;
}
bool lex_gt(const Impl& y) const noexcept {
const auto& x = static_cast<const Impl&>(*this);
return x > y;
}
bool lex_ge(const Impl& y) const noexcept {
const auto& x = static_cast<const Impl&>(*this);
return x >= y;
}
static bool all_lt(const Impl& x, const Impl& y) noexcept {
return _mm_movemask_ps(_mm_cmplt_ps(x, y)) == 0xf;
}
static bool all_le(const Impl& x, const Impl& y) noexcept {
return _mm_movemask_ps(_mm_cmple_ps(x, y)) == 0xf;
}
static bool all_gt(const Impl& x, const Impl& y) noexcept {
return _mm_movemask_ps(_mm_cmpgt_ps(x, y)) == 0xf;
}
static bool all_ge(const Impl& x, const Impl& y) noexcept {
return _mm_movemask_ps(_mm_cmpge_ps(x, y)) == 0xf;
}
bool all_lt(const Impl& y) const noexcept {
const auto& x = static_cast<const Impl&>(*this);
return all_lt(x, y);
}
bool all_le(const Impl& y) const noexcept {
const auto& x = static_cast<const Impl&>(*this);
return all_le(x, y);
}
bool all_gt(const Impl& y) const noexcept {
const auto& x = static_cast<const Impl&>(*this);
return all_gt(x, y);
}
bool all_ge(const Impl& y) const noexcept {
const auto& x = static_cast<const Impl&>(*this);
return all_ge(x, y);
}
// ==================
using details::IStdArrayBasic<IArray_Base, Impl>::IStdArrayBasic;
IArray_Impl() noexcept {}
IArray_Impl(const float* f4) noexcept : m{ _mm_loadu_ps(f4) } {}
IArray_Impl(__m128 f4) noexcept : m{ f4 } {} // align
explicit IArray_Impl(float v) noexcept : m{ _mm_set1_ps(v) } {}
IArray_Impl(const IArray_Impl& f4) noexcept : m{ f4.m } {}
IArray_Impl& operator=(const IArray_Impl& f4) noexcept { m = f4.m; return *this; }
operator __m128& () noexcept { return m; }
operator const __m128&() const noexcept { return const_cast<IArray_Impl*>(this)->operator __m128 &(); }
IArray_Impl(float x, float y, float z, float w) noexcept : m{ _mm_set_ps(w, z, y, x) } {} // little-endianness
template<typename Ux, typename Uy, typename Uz, typename Uw>
IArray_Impl(Ux x, Uy y, Uz z, Uw w) noexcept
: IArray_Impl{ static_cast<float>(x),static_cast<float>(y),static_cast<float>(z),static_cast<float>(w) } {}
static Impl Zero() noexcept {
return _mm_setzero_ps();
}
template<size_t i>
float get() const noexcept {
static_assert(i < 4);
if constexpr (i == 0)
return _mm_cvtss_f32(m);
else
return _mm_cvtss_f32(_mm_shuffle_ps(m, m, _MM_SHUFFLE(i, i, i, i)));
}
template<size_t i>
void set(float v) noexcept {
static_assert(i < 4);
if constexpr (i == 0)
m = _mm_move_ss(m, _mm_set_ss(v));
else {
__m128 t = _mm_move_ss(m, _mm_set_ss(v));
if constexpr (i == 1)
t = _mm_shuffle_ps(t, t, _MM_SHUFFLE(3, 2, 0, 0));
else if constexpr (i == 2)
t = _mm_shuffle_ps(t, t, _MM_SHUFFLE(3, 0, 1, 0));
else // if constexpr (i == 3)
t = _mm_shuffle_ps(t, t, _MM_SHUFFLE(0, 2, 1, 0));
m = _mm_move_ss(t, m);
}
}
template<size_t i>
Impl replicate() const noexcept {
static_assert(i < N);
return _mm_shuffle_ps(m, m, _MM_SHUFFLE(i, i, i, i));
}
};
#endif
}
| true |
43c79de6da204e7eb825906e73cc633b8516aeab | C++ | ac-lan/AiningLiu_MediaArt206_Homework | /Aining Liu - Final Project/src/utils.cpp | UTF-8 | 1,497 | 2.90625 | 3 | [] | no_license | #include "utils.h"
void drawBox(ofPoint position, ofPoint dimensions, ofColor color) {
ofPushMatrix();
ofTranslate(position.x + dimensions.x / 2, position.y + dimensions.y / 2, position.z + dimensions.z / 2);
ofBoxPrimitive box = ofBoxPrimitive(dimensions.x, dimensions.y, dimensions.z);
ofSetColor(color);
box.draw();
ofPopMatrix();
}
void drawBox(ofPoint dimensions, ofColor color) {
ofPushMatrix();
ofTranslate(dimensions.x / 2, dimensions.y / 2, dimensions.z / 2);
ofBoxPrimitive box = ofBoxPrimitive(dimensions.x, dimensions.y, dimensions.z);
ofSetColor(color);
box.draw();
ofPopMatrix();
}
BoundingBox getMeshBoundingBox(ofMesh mesh)
{
auto extremes_x = minmax_element(mesh.getVertices().begin(), mesh.getVertices().end(), [](const ofPoint& point1, const ofPoint& point2) {
return point1.x < point2.x;
});
auto extremes_y = minmax_element(mesh.getVertices().begin(), mesh.getVertices().end(), [](const ofPoint& point1, const ofPoint& point2) {
return point1.y < point2.y;
});
auto extremes_z = minmax_element(mesh.getVertices().begin(), mesh.getVertices().end(), [](const ofPoint& point1, const ofPoint& point2) {
return point1.z < point2.z;
});
ofPoint max = ofPoint(extremes_x.second->x, extremes_y.second->y, extremes_z.second->z);
ofPoint min = ofPoint(extremes_x.first->x, extremes_y.first->y, extremes_z.first->z);
ofPoint size = max - min;
BoundingBox bb = BoundingBox();
bb.min = min;
bb.max = max;
bb.size = size;
return bb;
} | true |
bafc5f1bc7e887f23dae955f51f981ca11a71f14 | C++ | osom8979/example | /wxwidgets/tutorials/t24.cpp | UTF-8 | 908 | 2.875 | 3 | [
"Zlib"
] | permissive | #include "tutorial.h"
class MyFrameT24: public wxFrame
{
public:
MyFrameT24(const wxString& title);
void OnMove(wxMoveEvent & event);
wxStaticText *st1;
wxStaticText *st2;
};
MyFrameT24::MyFrameT24(const wxString& title) :
wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxSize(250, 130))
{
wxPanel *panel = new wxPanel(this, -1);
st1 = new wxStaticText(panel, -1, wxT(""), wxPoint(10, 10));
st2 = new wxStaticText(panel, -1, wxT(""), wxPoint(10, 30));
Connect(wxEVT_MOVE, wxMoveEventHandler(MyFrameT24::OnMove));
Centre();
}
void MyFrameT24::OnMove(wxMoveEvent& event)
{
wxPoint size = event.GetPosition();
st1->SetLabel(wxString::Format(wxT("x: %d"), size.x));
st2->SetLabel(wxString::Format(wxT("y: %d"), size.y));
}
int t24()
{
MyFrameT24 * frame = new MyFrameT24(wxT("MyFrame"));
frame->Show(true);
return EXIT_SUCCESS;
}
| true |
8987b0af1bad41d0021f61de7684ec42b2cff524 | C++ | jiangyinzuo/icpc | /exercise/ecfinal_2019/m.cpp | UTF-8 | 843 | 2.625 | 3 | [] | no_license | //
// Created by Jiang Yinzuo on 2020/12/10.
//
#include <algorithm>
#include <cstdio>
long long a[100001], b[100001];
int n;
long long max_score;
void dfs(int base, int cur_v, long long score) {
if (cur_v > n) {
max_score = std::max(max_score, score);
return;
}
dfs(base, cur_v * base, score + )
}
int main() {
scanf("%d", &n);
long long ans = 0;
for (int i = 1; i <= n; ++i) {
scanf("%lld", a + i);
ans += a[i];
}
for (int i = 1; i <= n; ++i)
scanf("%lld", b + i);
static bool visited[100001]{false};
for (int i = 2; i <= n; ++i) {
if (!visited[i]) {
for (int j = i * i; j <= n; j *= i) {
visited[j] = true;
ans -= std::min(a[j], b[j]);
}
}
}
printf("%lld\n", ans);
return 0;
} | true |
e6795df0a89a98fab06ea3e94a7cb7b3ca197a21 | C++ | YueLung/Game2048 | /Game2048/main.cpp | UTF-8 | 1,274 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include <SFML/Graphics.hpp>
#include "TxtAnimation.h"
#include "BlockMgr.h"
#include "Block.h"
#include "GameStage.h"
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 700), "2048");
GameStage stage;
BlockMgr mgr;
TxtAnimation gameOverAn;
mgr.init();
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed) {
window.close();
}
if (!mgr.isAnyEvent()) {
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
mgr.moveRight();
mgr.isPressAnyKey = true;
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
mgr.moveLeft();
mgr.isPressAnyKey = true;
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
mgr.moveUp();
mgr.isPressAnyKey = true;
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
mgr.moveDown();
mgr.isPressAnyKey = true;
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) {
mgr.init();
mgr.isPressAnyKey = false;
}
}
}
mgr.update();
window.clear();
mgr.draw(window);
if (mgr.isGameOver()) {
gameOverAn.update();
gameOverAn.draw(window);
}
stage.draw(window);
window.display();
}
return 0;
} | true |
023aeb79b05750d42c78e6396a2d6e88cc7ff599 | C++ | phanhuytran/Base-TechniquesProgramming | /Programming Base/BTH04_BT07.cpp | UTF-8 | 1,394 | 3.15625 | 3 | [] | no_license | //Project: BTH4_BT07.cpp
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
system("color 0a");
int a, b;
int pt, lc;
do {
cout << endl << "-----Menu-----\n" << "1. Cong\n" << "2. Tru\n" << "3. Nhan\n" << "4. Chia\n" << "5. Thoat\n";
cout << "Moi ban chon phep tinh: ";
cin >> pt;
switch(pt)
{
case 1:
cout << "Nhap vao 2 so nguyen: ";
cin >> a >> b;
cout << "\nKet qua: " << a << " + " << b << " = " << a + b << endl << endl;
break;
case 2:
cout << "Nhap vao 2 so nguyen: ";
cin >> a >> b;
cout << "\nKet qua: " << a << " - " << b << " = " << a - b << endl << endl;
break;
case 3:
cout << "Nhap vao 2 so nguyen: ";
cin >> a >> b;
cout << "\nKet qua: " << a << " * " << b << " = " << a * b << endl << endl;
break;
case 4:
cout << "Nhap vao 2 so nguyen: ";
cin >> a >> b;
if (b == 0)
cout << "\nLoi chia 0!" << endl << endl;
else
cout << "\nKet qua: " << a << " / " << b << " = " << fixed << setprecision(2) << double(a) / b << endl << endl;
break;
case 5:
cout << "\nChao tam biet! Hen gap lai!" << endl << endl;
exit(0);
break;
default:
cout << "\nNgoai kha nang thuc hien!" << endl << endl;
}
cout << "\n1. Tiep tuc\n" << "2. Ket thuc\n" << "Tuy chon: ";
cin >> lc;
if (lc >= 2 || lc < 1)
{
cout << "n\Chao tam biet! Hen gap lai!" << endl;
exit(0);
}
} while (pt > 0 || pt <= 0);
return 0;
} | true |
c3691a0440208240c807c304dac8970343ba5fe1 | C++ | hazelguo/Computer-Network-Practicum | /Cluster/k_to_schools.cc | UTF-8 | 1,449 | 2.640625 | 3 | [] | no_license | #include "k_to_schools.h"
#include <vector>
//#include <unordered_set>
#include <set>
#include <string>
using namespace std;
KStudentsToSchools::KStudentsToSchools(
const vector<set<int> >& school_ids_for_student,
const vector<SchoolScore>& school_score) {
_school_ids_for_student.clear();
_school_score.clear();
for (vector<set<int> >::const_iterator iter =
school_ids_for_student.begin(); iter != school_ids_for_student.end();
++iter) {
_school_ids_for_student.push_back(*iter);
}
for (vector<SchoolScore>::const_iterator iter =
school_score.begin(); iter != school_score.end(); ++iter) {
_school_score.push_back(*iter);
}
}
KStudentsToSchools::~KStudentsToSchools() {}
void KStudentsToSchools::SchoolRecommendation(const vector<int>& k_students,
vector<string>* school_recommendation) {
set<int> potential_schools;
potential_schools.clear();
for (vector<int>::const_iterator student = k_students.begin();
student != k_students.end(); ++student) {
for (set<int>::const_iterator school =
_school_ids_for_student[*student].begin();
school != _school_ids_for_student[*student].end();
school ++) {
potential_schools.insert(*school);
}
}
for (vector<SchoolScore>::iterator school = _school_score.begin();
school != _school_score.end(); ++school) {
if (potential_schools.find(school->_id) != potential_schools.end()) {
school_recommendation->push_back(school->_name);
}
}
}
| true |
620a4007631fd9ba0b947d5b75a2bca310176415 | C++ | RhythmBoys/AlgoContest | /topcoder/BuyingTshirts.cpp | UTF-8 | 1,888 | 2.609375 | 3 | [] | no_license | #include <set>
#include <map>
#include <queue>
#include <ctime>
#include <cmath>
#include <vector>
#include <string>
#include <cstring>
#include <fstream>
#include <sstream>
#include <typeinfo>
#include <algorithm>
using namespace std;
typedef long long int64;
// Single Round Match 641 Div
// BuyingTshirts 250
// Memo Limit: 256 MB
// Time Limit: 2000 ms
class BuyingTshirts {
public:
int meet(int T, vector<int> Q, vector<int> P) {
int curQ = 0, curP = 0;
int len = Q.size();
int ans = 0;
for(int i = 0; i < len; ++i) {
curQ += Q[i];
curP += P[i];
if(curQ >= T && curP >= T)
ans++;
if(curP >= T) curP -= T;
if(curQ >= T) curQ -= T;
}
return ans;
}
};
// CUT begin
//------------------------------------------------------------------------------
const double CASE_TIME_OUT = 2.0;
bool disabledTest(int x)
{
return x < 0;
}
template<class I, class O> vector<pair<I,O>> getTestCases() { return {
{ { 5, {1,2,3,4,5}, {5,4,3,2,1} }, {2} },
{ { 10, {10,10,10}, {10,10,10} }, {3} },
{ { 2, {1,2,1,2,1,2,1,2}, {1,1,1,1,2,2,2,2} }, {5} },
{ { 100, {1,2,3}, {4,5,6} }, {0} },
{ { 10, {10,1,10,1}, {1,10,1,10} }, {0} },
// Your custom test goes here:
//{ { , {}, {}}, {} },
};}
//------------------------------------------------------------------------------
// Tester code:
//#define DISABLE_THREADS
#include "BuyingTshirts-tester.cpp"
struct input {
int p0;vector<int> p1;vector<int> p2;
int run(BuyingTshirts* x) {
return x->meet(p0,p1,p2);
}
void print() { Tester::printArgs(p0,p1,p2); }
};
int main() {
return Tester::runTests<BuyingTshirts>(
getTestCases<input, Tester::output< int> >(), disabledTest,
250, 1418313629, CASE_TIME_OUT, Tester::COMPACT_REPORT
);
}
// CUT end
| true |
5295fdf283295b8c37735f19c7ccaf974b57b20e | C++ | xiangyu/sgwater-dpseg | /Scoring.h | UTF-8 | 2,317 | 3.09375 | 3 | [] | no_license | #ifndef _SCORING_H_
#define _SCORING_H_
#include <iostream>
#include "Utterance.h"
#include "typedefs.h"
/*
Scoring class calculates number of words correct
in each utterance and keeps a running tally.
Calculates precision and recall, and lexicon precision.
*/
class Scoring {
public:
Scoring():
_utterances(0), _words_correct(0),
_segmented_words(0), _reference_words(0),
_bs_correct(0), _segmented_bs(0), _reference_bs(0) {}
// find correct, segmented, and reference words
// for utterance and add to totals. Add words
// to seg lexicon.
void score_utterance(Utterance* utterance);
double precision() const {
return (double)_words_correct/_segmented_words;}
double recall() const {
return (double)_words_correct/_reference_words;}
double fmeas() const {
return 2*recall()*precision()/(recall()+precision());}
double b_precision() const {
return (double)_bs_correct/_segmented_bs;}
double b_recall() const {
return (double)_bs_correct/_reference_bs;}
double b_fmeas() const {
return 2*b_recall()*b_precision()/(b_recall()+b_precision());}
double lexicon_precision() const {
return (double)lexicon_correct()/_segmented_lex.ntypes();}
double lexicon_recall() const {
return (double)lexicon_correct()/_reference_lex.ntypes();}
double lexicon_fmeas() const{
return 2*lexicon_precision()*lexicon_recall()/
(lexicon_precision() + lexicon_recall());}
void reset();
void print_results(ostream& os=cout) const;
void print_final_results(ostream& os=cout) const;
void print_segmented_lexicon(ostream& os=cout) const;
void print_reference_lexicon(ostream& os=cout) const;
void print_segmentation_summary(ostream& os=cout) const {
print_lexicon_summary(_segmented_lex);}
private:
typedef StringLexicon Lexicon;
int lexicon_correct() const;
void add_words_to_lexicon(const Utterance::Words& words, Lexicon& lex);
void print_lexicon(const Lexicon& lexicon,ostream& os=cout) const;
void print_lexicon_summary(const Lexicon& lexicon,ostream& os=cout) const;
int _utterances; // number of utterances so far in block
int _words_correct; // tokens
int _segmented_words;
int _reference_words;
int _bs_correct;
int _segmented_bs;
int _reference_bs;
Lexicon _segmented_lex;
Lexicon _reference_lex;
};
#endif
| true |
df0d94a7507b5286e74cfa3a2996b89e10ed7c27 | C++ | qqsskk/opcua-server | /opcua-plugin/logger/Logger.h | UTF-8 | 2,202 | 2.625 | 3 | [] | no_license | /*
* --- License -------------------------------------------------------------- *
*/
/*
* Copyright (c) 2015
*
* Hochschule Offenburg, University of Applied Sciences
* Institute for reliable Embedded Systems
* and Communications Electronic (ivESK)
*
* All rights reserved
*/
#ifndef _LOGGER_H
#define _LOGGER_H
#include "OpcUaStackCore/Core/FileLogger.h"
#include "OpcUaStackCore/Base/Log.h"
#include <stdarg.h>
#include <queue>
#include <map>
#include <string>
namespace OpcUaLWM2M {
using namespace OpcUaStackCore;
class Logger {
static LogLevel displayLevel_;
static std::map<std::string, LogLevel> logLevels;
static void getParameters(std::queue<std::string>& parameterQueue) {}
static std::string to_string() {return nullptr;}
static void replaceWithParameters(std::string &message,
std::queue<std::string> params);
public:
Logger();
Logger(LogLevel displayLevel);
~Logger();
static LogLevel getLoggerDisplayLevel();
static void log() {}
static bool setLoggerDisplayLevel(LogLevel loggingLevel);
static LogLevel getLogLevel(std::string key);
static LogLevel getLogLevel();
// --------------------- TEMPLATE INSTANTIATION ----------------------------
private:
template<typename P>
static void getParameters(std::queue<std::string>& parameterQueue,
P parameter) {
parameterQueue.push(Logger::to_string(parameter));
}
template<typename H, typename ... P>
static void getParameters(std::queue<std::string>& parameterQueue,
H paramaterHead, P ... parameterTail) {
parameterQueue.push(Logger::to_string(paramaterHead));
getParameters(parameterQueue, parameterTail...);
}
// Fix for the to_string method, Kudos to Stack Overflow
template<typename T>
static std::string to_string(T value) {
std::ostringstream os;
os << value;
return os.str();
}
public:
template<typename T = LogLevel, typename ... P>
static void log(T level, std::string message, P ... parameter) {
std::queue<std::string> parameters;
getParameters(parameters, parameter...);
if (!parameters.empty())
replaceWithParameters(message, parameters);
if (Logger::displayLevel_ >= level)
Log::logout(level, message);
}
};
}
#endif /* _LOGGER_H */
| true |
60b0f86272cf1e0d1f65b772ed73d292515408d0 | C++ | mikeNickaloff/ChessBlitz | /square.h | UTF-8 | 783 | 2.703125 | 3 | [] | no_license | #ifndef SQUARE_H
#define SQUARE_H
#include <QObject>
#include <QQuickItem>
class Piece;
class Square : public QQuickItem
{
Q_OBJECT
Q_PROPERTY(int row READ row WRITE setRow)
Q_PROPERTY(int col READ col WRITE setCol)
public:
Square();
int m_row;
int m_col;
Piece* m_piece;
Q_INVOKABLE int row() { return m_row; }
Q_INVOKABLE int col() { return m_col; }
Q_INVOKABLE Piece* piece() { return m_piece; }
bool m_highlight;
QByteArray serialize();
signals:
void highlight_changed(QVariant rv);
public slots:
void setRow(int new_row) { m_row = new_row; }
void setCol(int new_col) { m_col = new_col; }
void setPiece(Piece* new_piece) { m_piece = new_piece; }
void highlight(bool should_highlight);
};
#endif // SQUARE_H | true |
24f50c36dc88b899a50b325ae7c0fae0694ebb9f | C++ | hyeseonko/Algorithm-Baekjoon | /물통_baekjoon2251.cpp | UTF-8 | 1,414 | 2.984375 | 3 | [] | no_license | /*
TITLE: WATER BOTTLE
BAEKJOON 2251
CATEGORY: BFS
DATE: 2017-07-17
*/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <queue>
#include <vector>
#include <algorithm> // sort
using namespace std;
typedef struct {
int A;
int B;
int C;
}water;
queue <water> q;
vector <int> v;
int MAX[3];
int front[3];
int tmp[3];
bool visited[201][201][201];
int main()
{
scanf("%d %d %d", &MAX[0], &MAX[1], &MAX[2]);
q.push({ 0,0,MAX[2] });
visited[0][0][MAX[2]] = true;
while (!q.empty())
{
front[0] = q.front().A; // front A
front[1] = q.front().B; // front A
front[2] = q.front().C; // front
q.pop();
if (front[0] == 0) v.push_back(front[2]);
for (int i = 0; i < 3; i++)
{
if(front[i]!=0)
{
for (int j = 0; j < 3; j++)
{
tmp[0] = front[0];
tmp[1] = front[1];
tmp[2] = front[2];
if (j != i)
{
if (front[i] + front[j] > MAX[j])
{
tmp[j] = MAX[j];
tmp[i] -= (MAX[j] - front[j]);
}
else
{
tmp[j] += tmp[i];
tmp[i] = 0;
}
if (!visited[tmp[0]][tmp[1]][tmp[2]])
{
q.push({ tmp[0], tmp[1], tmp[2] });
visited[tmp[0]][tmp[1]][tmp[2]] = true;
}
}
}
}
}
}
sort(v.begin(), v.end());
for (int i = 0; i < v.size(); i++) printf("%d ", v[i]);
return 0;
} | true |
8aa64d1616f283a1b4637b7d6c3a9c9e4680c6c9 | C++ | moukraintsev/oop_project | /film.h | UTF-8 | 532 | 2.890625 | 3 | [] | no_license | #ifndef FILM_H
#define FILM_H
#include "video.h"
class Film: public Video {
public:
// Сonstructors
Film();
Film(const std::string &, const int &, const std::string &, const std::string &, const bool &, const std::string &);
Film(const Film &);
// Getters
const std::string &getStyle()const;
// Setters
void setStyle(const std::string &);
VideoType getType() const override;
bool operator == (Film *);
private:
std::string style;
};
#endif // FILM_H
| true |
d7fb3bd3295592a40e071b283d881c19e5048815 | C++ | keithroe/keithscode | /mview/src/mesh/HalfEdge.h | UTF-8 | 1,740 | 3.046875 | 3 | [] | no_license |
/*****************************************************************************\
*
* filename: HalfEdge.h
* author : r. keith morley
*
* Changelog:
*
\*****************************************************************************/
#ifndef _HALFEDGE_H_
#define _HALFEDGE_H_
#include <utility>
class Vertex;
class Face;
class HalfEdge
{
public:
~HalfEdge();
HalfEdge();
HalfEdge( Vertex* origin, Face* face );
HalfEdge( HalfEdge* twin, HalfEdge* next,
Vertex* origin, Face* face );
typedef std::pair<HalfEdge*, HalfEdge*> EdgePair;
static EdgePair createEdgePair();
static EdgePair createEdgePair( Vertex* origin1, Vertex* origin2 );
static EdgePair createEdgePair( Vertex* origin1, Vertex* origin2,
Face* face1, Face* face2 );
HalfEdge* twin() { return _twin; }
HalfEdge* next() { return _next; }
Vertex* origin() { return _origin; }
Face* face() { return _face; }
HalfEdge* nextAroundVertex() { return _twin->next(); }
HalfEdge* prevAroundVertex();
HalfEdge* prev();
void setTwin( HalfEdge* twin ) { _twin = twin; }
void setNext( HalfEdge* next) { _next = next; }
void setFace( Face* face) { _face = face; }
void setOrigin( Vertex* origin) { _origin = origin; }
bool checkConsistent();
unsigned int flags() { return _flags; }
void setFlags( unsigned int f ) { _flags = f; }
private:
HalfEdge* _twin;
HalfEdge* _next;
Vertex* _origin;
Face* _face;
unsigned int _flags;
};
#endif // _HALFEDGE_H_
| true |
876f77c392ec1d8533b3781bdcd9a7df1b62ec56 | C++ | SVolkoff/- | /List.cpp | UTF-8 | 1,587 | 3.734375 | 4 | [] | no_license |
#include <iostream>
using namespace std;
class List
{
private:
int *list;
int size;
public:
List()
{
list = nullptr;
size = 0;
}
~List()
{
delete list;
size = 0;
}
List(const int& value)
{
list = new int[value]();
size = value;
}
void add(int & pos, int & value)
{
if (pos >= size)
{
int * ptr = new int[pos + 1]();
for (int i = 0; i < size; ++i)
ptr[i] = list[i];
delete[] list;
list = ptr;
size = pos + 1;
}
list[pos] = value;
}
void del(int & pos)
{
if (pos < size)
{
int * ptr = new int[size - 1]();
for (int i = 0; i < pos; ++i)
ptr[i] = list[i];
for (int i = pos; i < size - 1; ++i)
ptr[i] = list[i + 1];
delete list;
list = ptr;
size--;
}
}
const int & get(int & pos)
{
if (pos < size)
return list[pos];
}
void print()
{
for (int i = 0; i < size; ++i)
cout << list[i] << " ";
cout << endl;
}
};
int main()
{
List list;
int a = 0;
int position = 0, value = 0, number = 0;
cout << "LIST\n\n";
do
{
cout << "\nSelect the command:\n1 - add\n2 - del\n3 - get\n4 - print\n0 - exit\n\n";
cin >> a;
switch (a)
{
case 1:
{
cout << "Enter position and value ";
cin >> position >> value;
list.add(position, value);
break;
}
case 2:
{
cout << "Enter position ";
cin >> position;
list.del(position);
break;
}
case 3:
{
cout << "Enter position ";
cin >> position;
list.get(position);
break;
}
case 4:
{
list.print();
break;
}
default: break;
}
} while (a != 0);
system("pause");
return 0;
}
| true |
c993bb2e9ea16523b67f2b9ea9c0293879dad634 | C++ | ArneStenkrona/Prototype | /Prototype/src/System/GUI/UIElement/UIGridEditor.h | UTF-8 | 2,022 | 2.71875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "UIElement.h"
#include "UIGridTile.h"
#include "World\room.h"
#include "UISelect\UISelector\UITileSelector.h"
#include "UISelect\UISelector\UIColliderSelector.h"
#include "UISelect\UISelector\UIObjectSelector.h"
#include "UISelect\UISelector\UIToolSelector.h"
#include "UIBorder.h"
#include "UIPanel\UIPanel\UIInfoBox.h"
class UIObjectPlacementListener;
//Responsible for editing of the room grid
class UIGridEditor : public UIElement {
public:
UIGridEditor(Room* _room, int _posx, int _posy, int _layer);
~UIGridEditor();
//Set room to _room. If null is provided, no room is set
void setRoom(Room* _room);
//Checks if gridselector is selected
inline bool isSelected() const { return selected || UIElement::isSelected(); }
//Gets coordniates of the tile that mouse is currently over.
//Coordinates may be set to (-1, -1) if not applicable
void getActiveTileCoordinates(int &x, int &y);
inline UIToolSelector::TOOL getTool() const { return (UIToolSelector::TOOL)toolSelector.getSelectedIndex(); }
private:
Room* room;
UITileSelector tileSelector;
UIColliderSelector colliderSelector;
UIObjectSelector objectSelector;
UIToolSelector toolSelector;
UIObjectPlacementListener* objectPlacementListener;
UIInfoBox infoBox;
std::vector<std::vector<UIGridTile*>> tiles;
//Is any tile in tiles selected?
bool selected;
//room offset position
int roomPosX, roomPosY;
//Tells what coordinate tile is active
int tilePosX, tilePosY;
UIBorder border[2];
//Dimensions of the room
unsigned int columns, rows;
void render();
void update();
void renderRoom();
//Sets selected tile at position (x, y)
void setTile(int x, int y);
//Sets selected collider at position (x, y)
void setCollider(int x, int y);
//Sets selected object at position (x, y)
void setObject(int x, int y);
void setActiveTileCoordinates(int x, int y);
friend class UIGridTile;
}; | true |
529f16dd639e9fc47de55a5991f75bf7d3a4b8eb | C++ | katherinr/snippets | /theTime.cpp | WINDOWS-1251 | 3,528 | 3.34375 | 3 | [] | no_license | #include "stdio.h"
#include <fstream>
#include <string>
#include <unordered_map>
#include <algorithm>
#include <iostream>
#include <cctype>
#include <locale> // std::locale, std::tolowe
//
template <typename T1, typename T2>
struct less_letter
{
typedef std::pair<T1, T2> type;
bool operator ()(type const& a, type const& b) const
{
auto & a_it = a.first.begin();
auto & b_it = b.first.begin();
bool sign = false;
if (a.second > b.second)
{
sign = true;
}
else if (a.second < b.second)
{
sign = false;
}
else
{
for (; a_it != a.first.end(), b_it != b.first.end();)
{
if (char(*a_it) == char(*b_it))
{
a_it++;
b_it++;
}
else
{
if (char(*a_it) > char(*b_it))
{
sign = false;
}
else if (char(*a_it) < char(*b_it))
{
sign = true;
}
break;
}
}
}
return sign;
}
};
///******************************************************************************************************
int main(int argc, char* argv[])
{
char *my_input = nullptr, *my_output = nullptr;
//setlocale(LC_ALL, "ru_RU.UTF8");
//
if (argc == 0)
{
// std::cerr << "No arguments in input!" << std::endl;
return 0;
}
else if (argc == 1)
{
//
my_input = "in.txt";
my_output = "out.txt";
}
else
{
//
my_input = argv[1];
my_output = argv[2];
}
///******************************************************************************************************
//
std::wifstream fin(my_input); //
std::unordered_map <std::wstring, int> raw_input; //
std::wstring buf_str;
std::locale loc("ru_RU.UTF8");// ("en_US.UTF8");
//loc.all();// = "ru_RU.UTF8";
while (getline(fin, buf_str, L' '))
{
for (rsize_t i = 0; i < buf_str.size(); ++i)
{
if (isalpha(buf_str[i],loc))
{
if (isupper(buf_str[i],loc))
buf_str[i] = std::tolower(buf_str[i],loc);
}
else
{
//
buf_str.erase(buf_str.begin() + i);
}
}
auto & found_str = raw_input.find(buf_str);
// , ,
if (found_str != raw_input.end())
{
found_str->second += 1;
}
else
{
raw_input.insert(std::make_pair(buf_str, 1));
}
}
fin.close(); //
///******************************************************************************************************
//
std::vector< std::pair< std::wstring, int> > raw_output(raw_input.begin(), raw_input.end());
std::sort(raw_output.begin(), raw_output.end(), less_letter<std::wstring, int>());
///******************************************************************************************************
//
std::wofstream output(my_output);
for (const auto &iter : raw_output)
{
std::wstring buf_str = std::to_wstring(iter.second) + L' ' + iter.first;
output << buf_str << std::endl;
}
output.close();
}
| true |
7d98be6b78e54bfdeeef230954a0c78d063bda3e | C++ | Nedusat/MurderEngine | /src/nodes/node_render.cpp | UTF-8 | 2,052 | 2.765625 | 3 | [] | no_license | #include "node.h"
#include "node_render.h"
#include "../renderer/render_helper.h"
double node_render_get_sock_x(node_socket* socket, node* _node)
{
return (socket->dir==NODE_SOCKET_OUT?_node->scaleX:0) + _node->posX + socket->offX;
}
double node_render_get_sock_y(node_socket* socket, node* _node)
{
return _node->posY + NODE_PANEL_HEIGHT + 16 + socket->offY;
}
void node_render_update_socket_pos(node* _node)
{
for (int i = 0; i < _node->info.sockets.size(); i++)
{
node_socket* socket = _node->info.sockets.at(i);
socket->posX = node_render_get_sock_x(socket, _node);
socket->posY = node_render_get_sock_y(socket, _node);
}
}
void node_render_sockets(node* _node)
{
for (int i = 0; i < _node->info.sockets.size(); i++)
{
node_socket* socket = _node->info.sockets.at(i);
render_lozenge(socket->data_type, socket->posX, socket->posY, NODE_SOCKET_SIZE, NODE_SOCKET_SIZE, true);
render_lozenge(0xFF000000, socket->posX, socket->posY, NODE_SOCKET_SIZE, NODE_SOCKET_SIZE, false);
for (node_socket* connection : socket->connections)
{
node_render_socket_wire(socket->posX+(NODE_SOCKET_SIZE/2), socket->posY+(NODE_SOCKET_SIZE/2), connection->posX+(NODE_SOCKET_SIZE/2), connection->posY+(NODE_SOCKET_SIZE/2));
}
}
}
const double CURVE_AMOUNT = 0.5D;
mVec2d* BEZIER_CURVE = new mVec2d[4]{{0, 0},{0, 0},{0, 0},{0, 0}};
void node_render_socket_wire(double fromX, double fromY, double toX, double toY)
{
double width = toX-fromX;
BEZIER_CURVE[0].x = fromX;
BEZIER_CURVE[0].y = fromY;
double v = toX > fromX ? (width * CURVE_AMOUNT) : (width * CURVE_AMOUNT * -1);
BEZIER_CURVE[1].x = fromX + v;
BEZIER_CURVE[1].y = fromY;
BEZIER_CURVE[2].x = toX - v;
BEZIER_CURVE[2].y = toY;
BEZIER_CURVE[3].x = toX;
BEZIER_CURVE[3].y = toY;
render_start();
render_enable_smooth_line();
render_line_width(NODE_SOCKET_WIRE_WIDTH);
render_color(0xFFFFFFFF);
render_bezier(BEZIER_CURVE, 0.025D, true, 0x0003, 0, 4);
render_line_width(1);
render_disable_smooth_line();
render_end();
}
| true |
1a401ed3b79f772844c5994aae67ab6e1486f066 | C++ | alice965/LaonSillv2 | /LaonSill/src/core/Broker.cpp | UTF-8 | 6,787 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | /**
* @file Broker.cpp
* @date 2016-12-19
* @author moonhoen lee
* @brief
* @details
*/
#include "common.h"
#include "Broker.h"
#include "SysLog.h"
#include "Param.h"
#include "MemoryMgmt.h"
using namespace std;
map<uint64_t, Job*> Broker::contentMap;
mutex Broker::contentMutex;
map<uint64_t, int> Broker::waiterMap;
mutex Broker::waiterMutex;
Broker::AdhocSess *Broker::adhocSessArray;
list<int> Broker::freeAdhocSessIDList;
mutex Broker::adhocSessMutex;
void Broker::init() {
int allocSize = sizeof(Broker::AdhocSess) * SPARAM(BROKER_ADHOC_SESS_COUNT);
SMALLOC_ONCE(Broker::adhocSessArray, Broker::AdhocSess, allocSize);
SASSERT0(Broker::adhocSessArray != NULL);
for (int i = 0; i < SPARAM(BROKER_ADHOC_SESS_COUNT); i++) {
Broker::adhocSessArray[i].arrayIdx = i;
Broker::adhocSessArray[i].sessID = i + SPARAM(BROKER_ADHOC_SESS_STARTS);
Broker::adhocSessArray[i].found = false;
SNEW_ONCE(Broker::adhocSessArray[i].sessMutex, mutex);
SASSERT0(Broker::adhocSessArray[i].sessMutex != NULL);
SNEW_ONCE(Broker::adhocSessArray[i].sessCondVar, condition_variable);
SASSERT0(Broker::adhocSessArray[i].sessCondVar != NULL);
Broker::freeAdhocSessIDList.push_back(i + SPARAM(BROKER_ADHOC_SESS_STARTS));
}
}
void Broker::destroy() {
for (int i = 0; i < SPARAM(BROKER_ADHOC_SESS_COUNT); i++) {
SDELETE(Broker::adhocSessArray[i].sessMutex);
SDELETE(Broker::adhocSessArray[i].sessCondVar);
}
SFREE(Broker::adhocSessArray);
}
/**
* XXX: 현재는 publisher가 직접 waiter를 깨우고 있다.
* publisher의 부하가 많은 수 있기 때문에 이 부분에 대한 설계를 고민해야 한다.
* (예를들어서 background 관리 쓰레드가 깨워준다던지..)
*/
Broker::BrokerRetType Broker::publishEx(int jobID, int taskID, Job *content) {
// (1) content를 집어 넣는다.
uint64_t key = MAKE_JOBTASK_KEY(jobID, taskID);
unique_lock<mutex> contentLock(Broker::contentMutex);
Broker::contentMap[key] = content;
contentLock.unlock();
// (2) 기다리고 있는 subscriber가 있으면 깨워준다.
map<uint64_t, int>::iterator waiterMapIter;
unique_lock<mutex> waiterLock(Broker::waiterMutex);
waiterMapIter = Broker::waiterMap.find(key);
if (waiterMapIter != Broker::waiterMap.end()) {
int sessID = (int)(waiterMapIter->second);
Broker::waiterMap.erase(waiterMapIter);
waiterLock.unlock();
// wakeup with sessID
int adhocSessIdx = sessID - SPARAM(BROKER_ADHOC_SESS_STARTS);
SASSERT0(adhocSessIdx < SPARAM(BROKER_ADHOC_SESS_COUNT));
Broker::AdhocSess *adhocSess = &Broker::adhocSessArray[adhocSessIdx];
SASSERT0(adhocSess->arrayIdx == adhocSessIdx);
adhocSess->found = true;
unique_lock<mutex> sessLock(*adhocSess->sessMutex);
adhocSess->sessCondVar->notify_one();
sessLock.unlock();
} else {
waiterLock.unlock();
}
return Broker::Success;
}
Broker::BrokerRetType Broker::publish(int jobID, Job *content) {
return Broker::publishEx(jobID, 0, content);
}
/**
* NOTE:
* subscribe에서 가져간 content는 가져간 사람이 지워야 한다.
* content Lock을 잡고, waiter lock 혹은 adhocSess lock을 잡도록 되어 있다.
* 순서가 바뀌면 안된다.
*/
Broker::BrokerRetType Broker::subscribeEx(int jobID, int taskID, Job **content,
Broker::BrokerAccessType access) {
SASSERT0(access < BrokerAccessTypeMax);
uint64_t key = MAKE_JOBTASK_KEY(jobID, taskID);
map<uint64_t, Job*>::iterator contentMapIter;
unique_lock<mutex> contentLock(Broker::contentMutex);
// XXX: content Lock을 너무 오래 잡고 있다.
// 나중에 성능봐서 Lock 튜닝하자
// (1) 콘텐트가 들어 있는지 확인하고, 들어 있으면 content에 포인터를 연결시켜주고
// 종료한다.
contentMapIter = Broker::contentMap.find(key);
if (contentMapIter != Broker::contentMap.end()) {
(*content) = (Job*)(contentMapIter->second);
Broker::contentMap.erase(contentMapIter);
contentLock.unlock();
return Broker::Success;
}
// (2) non blocking이면 곧바로 리턴
if (access == Broker::NoBlocking) {
contentLock.unlock();
return Broker::NoContent;
}
// (3) adhoc sess ID를 발급해준다.
// (원래는 sess ID를 인자로 받고, sess ID가 없는 경우에 대해서 adhoc sess ID를
// 발급해 주려고 하였다.)
int sessID = Broker::getFreeAdhocSessID();
if (sessID == 0) {
contentLock.unlock();
return Broker::NoFreeAdhocSess;
}
// (4) waiter에 등록해준다.
unique_lock<mutex> waiterLock(Broker::waiterMutex);
Broker::waiterMap[key] = sessID;
waiterLock.unlock();
contentLock.unlock();
// (5) 깨워줄때까지 대기한다.
int adhocSessIdx = sessID - SPARAM(BROKER_ADHOC_SESS_STARTS);
SASSERT0(adhocSessIdx < SPARAM(BROKER_ADHOC_SESS_COUNT));
AdhocSess *adhocSess = &Broker::adhocSessArray[adhocSessIdx];
SASSERT0(adhocSess->arrayIdx == adhocSessIdx);
unique_lock<mutex> sessLock(*adhocSess->sessMutex);
adhocSess->sessCondVar->wait(sessLock,
[&adhocSess] { return (adhocSess->found == true); });
sessLock.unlock();
SASSERT0(adhocSess->found == true);
SASSERT0(Broker::contentMap[key] != NULL);
(*content) = (Job*)Broker::contentMap[key];
// (6) adhoc sess를 반환한다.
Broker::releaseAdhocSessID(sessID);
return Broker::Success;
}
Broker::BrokerRetType Broker::subscribe(int jobID, Job **content,
Broker::BrokerAccessType access) {
return Broker::subscribeEx(jobID, 0, content, access);
}
/*
* @return 0 : there is no adhoc sess id
* otherwise : adhoc sess id
*/
int Broker::getFreeAdhocSessID() {
unique_lock<mutex> adhocSessLock(Broker::adhocSessMutex);
if (Broker::freeAdhocSessIDList.empty()) {
adhocSessLock.unlock();
return 0;
}
int sessID = Broker::freeAdhocSessIDList.front();
Broker::freeAdhocSessIDList.pop_front();
adhocSessLock.unlock();
return sessID;
}
void Broker::releaseAdhocSessID(int sessID) {
SASSERT0(sessID >= SPARAM(BROKER_ADHOC_SESS_STARTS));
int adhocSessArrayIdx = sessID - SPARAM(BROKER_ADHOC_SESS_STARTS);
SASSERT0(adhocSessArrayIdx < SPARAM(BROKER_ADHOC_SESS_COUNT));
Broker::adhocSessArray[adhocSessArrayIdx].found = false;
unique_lock<mutex> adhocSessLock(Broker::adhocSessMutex);
Broker::freeAdhocSessIDList.push_back(sessID);
adhocSessLock.unlock();
}
| true |
b770a30db17854117ade97e860bba1a80a08fc56 | C++ | ALaDyn/Smilei | /src/Radiation/RadiationTables.h | UTF-8 | 9,660 | 2.5625 | 3 | [] | no_license | // ----------------------------------------------------------------------------
//! \file RadiationTables.h
//
//! \brief This class contains the tables and the functions to generate them
//! for the Nonlinear Inverse Compton Scattering
//
//! \details This header contains the definition of the class RadiationTables.
//! The implementation is adapted from the thesis results of M. Lobet
//! See http://www.theses.fr/2015BORD0361
// ----------------------------------------------------------------------------
#ifndef RADIATIONTABLES_H
#define RADIATIONTABLES_H
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cstring>
#include <iomanip>
#include <cmath>
#include "userFunctions.h"
#include "Params.h"
#include "H5.h"
#include "Random.h"
#include "Table.h"
#include "Table2D.h"
#include "RadiationTools.h"
//------------------------------------------------------------------------------
//! RadiationTables class: holds parameters, tables and functions to compute
//! cross-sections,
//! optical depths and other useful parameters for the Compton Monte-Carlo
//! pusher.
//------------------------------------------------------------------------------
class RadiationTables
{
public:
//! Constructor for RadiationTables
RadiationTables();
//! Destructor for RadiationTables
~RadiationTables();
//! Initialization of the parmeters for the nonlinear
//! inverse Compton scattering
void initialization( Params ¶ms , SmileiMPI *smpi );
// ---------------------------------------------------------------------
// PHYSICAL COMPUTATION
// ---------------------------------------------------------------------
//! Computation of the photon production yield dNph/dt which is
//! also the cross-section for the Monte-Carlo
//! param[in] particle_chi particle quantum parameter
//! param[in] particle_gamma particle Lorentz factor
//! param[in] integfochi_table table of the discretized integrated f/chi function for Photon production yield computation
double computePhotonProductionYield( const double particle_chi,
const double particle_gamma);
//! Determine randomly a photon quantum parameter photon_chi
//! for an emission process
//! from a particle chi value (particle_chi) and
//! using the tables xip and chiphmin
//! \param particle_chi particle quantum parameter
// double computeRandomPhotonChi( double particle_chi );
//! Computation of the photon quantum parameter photon_chi for emission
//! ramdomly and using the tables xi and chiphmin
//! \param[in] particle_chi particle quantum parameter
//! \param[in] xi
//! \param[in] table_min_photon_chi
//! \param[in] table_xi
double computeRandomPhotonChiWithInterpolation( double particle_chi,
double xi);
//! Return the value of the function h(particle_chi) of Niel et al.
//! Use an integration of Gauss-Legendre
//
//! \param particle_chi particle quantum parameter
//! \param nb_iterations number of iterations for the Gauss-Legendre integration
//! \param eps epsilon for the modified bessel function
double computeHNiel( double particle_chi, int nb_iterations, double eps );
//! Return the value of the function h(particle_chi) of Niel et al.
//! from the computed table niel_.table
//! \param particle_chi particle quantum parameter
double getHNielFromTable( double particle_chi );
//! Return the stochastic diffusive component of the pusher
//! of Niel et al.
//! \param gamma particle Lorentz factor
//! \param particle_chi particle quantum parameter
//! \param dt time step
// double getNielStochasticTerm( double gamma,
// double particle_chi,
// double dt,
// Random * rand);
//! Computation of the corrected continuous quantum radiated energy
//! during dt from the quantum parameter particle_chi using the Ridgers
//! formulae.
//! \param particle_chi particle quantum parameter
//! \param dt time step
//#pragma omp declare simd
inline double __attribute__((always_inline)) getRidgersCorrectedRadiatedEnergy( const double particle_chi,
const double dt )
{
return computeRidgersFit( particle_chi )*dt*particle_chi*particle_chi*factor_classical_radiated_power_;
};
//! Computation of the function g of Erber using the Ridgers
//! approximation formulae
//! \param particle_chi particle quantum parameter
//#pragma omp declare simd
static inline double __attribute__((always_inline)) computeRidgersFit( double particle_chi )
{
return std::pow( 1.0 + 4.8*( 1.0+particle_chi )*std::log( 1.0 + 1.7*particle_chi )
+ 2.44*particle_chi*particle_chi, -2.0/3.0 );
};
//! Get of the classical continuous radiated energy during dt
//! \param particle_chi particle quantum parameter
//! \param dt time step
inline double __attribute__((always_inline)) getClassicalRadiatedEnergy( double particle_chi, double dt )
{
return dt*particle_chi*particle_chi*factor_classical_radiated_power_;
};
//! Return the minimum_chi_discontinuous_ value
//! Under this value, no discontinuous radiation reaction
inline double __attribute__((always_inline)) getMinimumChiDiscontinuous()
{
return minimum_chi_discontinuous_;
}
//! Return the minimum_chi_continuous_ value
//! Under this value, no continuous radiation reaction
inline double __attribute__((always_inline)) getMinimumChiContinuous()
{
return minimum_chi_continuous_;
}
inline std::string __attribute__((always_inline)) getNielHComputationMethod()
{
return this->niel_computation_method_;
}
inline int __attribute__((always_inline)) getNielHComputationMethodIndex()
{
return this->niel_computation_method_index_;
}
// -----------------------------------------------------------------------------
//! Return the classical power factor factor_classical_radiated_power_.
// -----------------------------------------------------------------------------
inline double __attribute__((always_inline)) getFactorClassicalRadiatedPower()
{
return factor_classical_radiated_power_;
}
// ---------------------------------------------------------------------
// TABLE READING
// ---------------------------------------------------------------------
//! Read the external table h
//! \param smpi Object of class SmileiMPI containing MPI properties
void readHTable( SmileiMPI *smpi );
//! Read the external table integfochi_
//! \param smpi Object of class SmileiMPI containing MPI properties
void readIntegfochiTable( SmileiMPI *smpi );
//! Read the external table xip_chiphmin and xip
//! \param smpi Object of class SmileiMPI containing MPI properties
void readXiTable( SmileiMPI *smpi );
//! Read the external all external tables for the radiation
//! \param smpi Object of class SmileiMPI containing MPI properties
void readTables( Params ¶ms, SmileiMPI *smpi );
// ---------------------------------------------------------------------
// TABLE COMMUNICATIONS
// ---------------------------------------------------------------------
//! Bcast of the external table xip_chiphmin and xip
//! \param smpi Object of class SmileiMPI containing MPI properties
void bcastTableXi( SmileiMPI *smpi );
// ---------------------------------------------
// Table h for the
// stochastic diffusive operator of Niel et al.
// ---------------------------------------------
// 1d array
// axe 0 = particle_chi
Table niel_;
// ---------------------------------------------
// Table integfochi
// ---------------------------------------------
// 1d array
// axe 0 = particle_chi
Table integfochi_;
// ---------------------------------------------
// Structure for min_photon_chi_for_xi and xi
// ---------------------------------------------
// 2d array
// axe0: particle_chi
// axe1: photon_chi
Table2D xi_;
private:
// ---------------------------------------------
// General parameters
// ---------------------------------------------
//! Output format of the tables
std::string output_format_;
//! Path to the tables
std::string table_path_;
//! Flag that activate the table computation
bool compute_table_;
//! Minimum threshold above which the Monte-Carlo algorithm is working
//! This avoids using the Monte-Carlo algorithm when particle_chi is too low
double minimum_chi_discontinuous_;
//! Under this value, no radiation loss
double minimum_chi_continuous_;
//! Method to be used to get the h values (table, fit5, fit10)
std::string niel_computation_method_;
//! Index for the computational method
int niel_computation_method_index_;
// ---------------------------------------------
// Factors
// ---------------------------------------------
//! Factor for the computation of dNphdt
double factor_dNph_dt_;
//! Factor for the Classical radiated power
//! 2.*params.fine_struct_cst/(3.*normalized_Compton_wavelength_);
double factor_classical_radiated_power_;
//! Normalized reduced Compton wavelength
double normalized_Compton_wavelength_;
};
#endif
| true |
805811c7be8c6d7d2a54db778bfe61f2e562acf6 | C++ | adrian2004/tpa | /exercicio29.cpp | ISO-8859-1 | 378 | 3.125 | 3 | [] | no_license | /*
Funo: calcular o fatorial de um nmero digitado pelo usurio
Data:16/10/2019
Autor: Adrian Wilmer Jaquier
*/
#include <iostream>
#include <locale.h>
int main() {
setlocale(LC_ALL, "");
int m = 0, r = 0;
printf("digite um nmero: ");
scanf("%i", &m);
printf("\nTabuda de %i\n",m);
for(int p = 0; p<=10; p++){
r = m * p;
printf("%i X %i = %i\n", m, p, r);
}
return 0;
}
| true |
ea86181429978efbd64f75e981ab93d3c140fbde | C++ | HaooWang/C--Projects-forClion | /src/demo_1to6/指针ptr与数组array/01.指针.cpp | UTF-8 | 329 | 2.9375 | 3 | [] | no_license |
#include <iostream>
using namespace std;
#if 0
int main(){
int i;
int *ptr=&i;
i=10;
cout<<"i="<<i<<endl;
cout<<"*ptr="<<*ptr<<endl;
return 0;
}
#else
int main(){
void *pv;
int i=5;
pv = &i;
int *pint = static_cast<int*>(pv);
cout<<"*pint= "<<*pint<<endl;
return 0;
}
#endif | true |
e56a87bf5db8674c86660b1f5cd83829e607bff7 | C++ | jc4250/coding | /ccl/merge-triplets.cpp | UTF-8 | 944 | 2.96875 | 3 | [] | no_license | //https://leetcode.com/problems/merge-triplets-to-form-target-triplet/
class Solution {
public:
bool mergeTriplets(vector<vector<int>>& triplets, vector<int>& t) {
for (int i = 0; i < triplets.size(); i++) {
if (triplets[i] == t) return true;
}
int ans[3] = {0,0,0};
for (int i = 0; i < triplets.size(); i++) {
int a = triplets[i][0];
int b = triplets[i][1];
int c = triplets[i][2];
if ((a == t[0] || b == t[1] || c == t[2]) && a <= t[0] && b <= t[1] && c <= t[2]) {
ans[0] = max(ans[0], a);
ans[1] = max(ans[1], b);
ans[2] = max(ans[2], c);
}
// cout<<ans[0]<<" "<<ans[1]<<" "<<ans[2]<<endl;
}
for (int i = 0; i < 3; i++) {
if (ans[i] != t[i]) return false;
}
return true;
}
}; | true |
80a4fb1eab1023c76fb8ebfc606e61fe1543247c | C++ | antimatterhorn/SPH-Routines | /wvt/wvt_mass.cpp | UTF-8 | 1,954 | 2.96875 | 3 | [] | no_license | #include <iostream>
#include <math.h>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
/* This code will read in the inputh.dat and inputmodel.dat files */
/* to produce the correct cutoff that corresponds to the desired mass */
using namespace std;
const double pi = 3.1415926;
const double onethird = 1.0 / 3.0;
const double twothirds = 2.0 / 3.0;
const double fourthirds = 4.0 / 3.0;
double mass,total,sub,r,dr;
int n,i;
int main()
{
FILE *file2;
ifstream file("inputh.dat") ;
string line ;
vector<string> lines ;
while( getline( file, line ) ) lines.push_back( line ) ;
n = lines.size();
cout << "inputh.dat contains " << n << " line(s)" << endl;
cout << "Desired mass: ";
cin >> mass;
double input[n][3];
/* inputh.dat will contain r and h, while inputmodel will contain r, rho, u ... */
/* here we want just r, h, rho */
float d1,d2,d3;
file2 = fopen("inputh.dat","r");
i=0;
while (fscanf(file2,"%g %g", &d1,&d2)!=EOF) {
//printf("%e %e\n",d1,d2);
input[i][0] = d1;
input[i][1] = d2;
i++;
}
fclose(file2);
file2 = fopen("inputmodel.dat", "r");
i=0;
while (fscanf(file2,"%g %g %*g %*g %*g", &d1,&d2)!=EOF) {
if (d1 != input[i][0]) {
/* there's a problem here */
printf("r in inputmodel.dat does not match r in inputh.dat for row %d\n",i);
}
input[i][2] = d2;
i++;
}
fclose(file2);
// for (i=0;i<n;i++)
// {
// fscanf(file2,"%f %f %f %f %f\n",&d1,&d2,&d3,&d3,&d3);
// if (d1 != input[i][0]) {
// /* there's a problem here */
// //printf("r in inputmodel.dat does not match r in inputh.dat for row %d\n",i);
// }
// input[i][2] = d2;
// }
// fclose(file2);
for (i=0;i<n-1;i++) {
r = (input[i+1][0] + input[i][0])*0.5;
dr = (input[i+1][0] - input[i][0]);
sub = 4*pi*(input[i+1][2]+input[i][2])*dr*0.5*pow(r,2.0);
//printf("%e %e %e\n",input[i][0],input[i][1],input[i][2]);
total += sub;
}
printf("total mass:%e\n",total);
return 0;
}
| true |
5e058946591b64511424fa1d33c3f51aedc375ea | C++ | LLNL/cardioid | /elec/unitTests/CellModelTests/OneCell.cc | UTF-8 | 5,985 | 2.875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #include <cstdio>
#include <iostream>
#include <cassert>
#include <cmath>
#include <string>
#include <vector>
#include "Anatomy.hh"
#include "Reaction.hh"
#include "TT04_CellML_Reaction.hh"
#include "TT04Dev_Reaction.hh"
#include "TT06_CellML_Reaction.hh"
#include "TT06Dev_Reaction.hh"
#include "TT06_RRG_Reaction.hh"
#include "ReactionFHN.hh"
using namespace std;
class PeriodicPulse
{
public:
PeriodicPulse(double magnitude, double tStart, double tEnd, double tRepeat)
:magnitude_(magnitude), tStart_(tStart), tEnd_(tEnd), tRepeat_(tRepeat){}
double operator()(double time)
{
time -= (floor(time/tRepeat_) * tRepeat_);
if (time >= tStart_ && time < tEnd_)
return magnitude_;
return 0;
}
private:
double magnitude_;
double tStart_;
double tEnd_;
double tRepeat_;
};
Anatomy buildAnatomy(int cellType)
{
AnatomyCell c;
c.gid_ = 0;
c.cellType_ = 100+cellType;
c.sigma_.a11 = 0;
c.sigma_.a12 = 0;
c.sigma_.a13 = 0;
c.sigma_.a22 = 0;
c.sigma_.a23 = 0;
c.sigma_.a33 = 0;
Anatomy a;
a.setGridSize(1, 1, 1);
a.cellArray().push_back(c);
a.nLocal() = 1;
//a.setGridSize(14, 14, 14);
//a.cellArray().resize(14*14*14,c);
//a.nLocal() = 14*14*14;
a.nRemote() = 0;
a.dx() = 0.2;
a.dy() = 0.2;
a.dz() = 0.2;
return a;
}
Reaction* factory(const string& name, const Anatomy& anatomy, double tolerance,int mod)
{
if (name == "cellml_tt04") return new TT04_CellML_Reaction(anatomy, TT04_CellML_Reaction::rushLarsen);
if (name == "cellml_tt04_fe") return new TT04_CellML_Reaction(anatomy, TT04_CellML_Reaction::forwardEuler);
if (name == "cellml_tt06") return new TT06_CellML_Reaction(anatomy, TT06_CellML_Reaction::rushLarsen);
if (name == "cellml_tt06_fe") return new TT06_CellML_Reaction(anatomy, TT06_CellML_Reaction::forwardEuler);
if (name == "tt06rrg") return new TT06_RRG_Reaction(anatomy);
if (name == "fhn") return new ReactionFHN(anatomy);
if (name == "tt04dev") return new TT04Dev_Reaction(anatomy);
if (name == "tt06dev") return new TT06Dev_Reaction(anatomy,tolerance,mod);
assert(false);
return 0;
}
int main(int argc, char *argv[])
{
if (argc < 12)
{
cout << "program arguments:" << endl;
cout << "argv[1] - method name (see list below)" << endl;
cout << "argv[2] - amplitude of stimulus -52.0" << endl;
cout << "argv[3] - start time of stimulus [ms] 2 ms" << endl;
cout << "argv[4] - length of stimulus [ms] 1 ms" << endl;
cout << "argv[5] - frequency of stimulus [ms] 1000 ms" << endl;
cout << "argv[6] - simulation time [ms] 1000 ms" << endl;
cout << "argv[7] - time step [ms] 2e-2 ms"<< endl;
cout << "argv[8] - print Vm every N time steps 50" << endl;
cout << "argv[9] - equilibration time t [ms] 0" << endl;
cout << "argv[10] - cell position [endo=0; mid=1; epi=2]" << endl;
cout << "argv[11] - tolerance for pade approximations" << endl;
cout << "argv[12] - mod (used by tt06dev only)" << endl;
cout <<endl;
cout << "Supported cell models:" <<endl;
cout << "----------------------" <<endl;
cout << " cellml_tt04 TT04 from CellML. Rush-Larsen integrator" << endl;
cout << " cellml_tt04_fe TT04 from CellML. Forward Euler integrator" << endl;
cout << " cellml_tt06 TT06 from CellML. Rush-Larsen integrator" << endl;
cout << " cellml_tt06_fe TT06 from CellML. Forward Euler integrator" << endl;
cout << " tt06rrg TT06 as modified by Rice et al." << endl;
cout << " fhn FitzHugh-Nagumo" << endl;
cout << " tt04dev Developmental version of TT04" << endl;
cout << " tt06dev Developmental version of TT06" << endl;
return 0;
}
string method = (argv[1]);
double stimMagnitude = atof(argv[2]);
double stimStart = atof(argv[3]);
double stimLength = atof(argv[4]);
double stimCycleLength = atof(argv[5]);
double tEnd = atof(argv[6]);
double dt = atof(argv[7]);
int printRate = atoi(argv[8]);
double equilTime = atof(argv[9]);
int cellPosition = atoi(argv[10]);
double tolerance = atof(argv[11]);
int mod = atoi(argv[12]);
unsigned firstStepToPrint = unsigned(equilTime/dt);
PeriodicPulse stimFunction(
stimMagnitude, stimStart, stimStart+stimLength, stimCycleLength);
Anatomy anatomy = buildAnatomy(cellPosition);
Reaction* cellModel = factory(method, anatomy,tolerance,mod);
cout << "# method: " << method
<< "\tstimMagnitude " << stimMagnitude
<< "\tstimStart " << stimStart
<< "\tstimLength " << stimLength
<< "\tstimCycleLength " << stimCycleLength
<< "\ttend " << tEnd
<< "\tdt " << dt
<< "\tcell type " << cellPosition
<< endl;
double time = 0.0;
unsigned loop = 0;
unsigned nLocal = anatomy.nLocal();
double tmp = stimFunction(time);
vector<double> Vm(nLocal);
cellModel->initializeMembraneVoltage(Vm);
vector<double> iStim(nLocal, tmp);
vector<double> dVmReaction(nLocal, 0);
printf("# Starting the computation time loop\n");
printf("# time Vm iStim dVmReaction\n");
if (firstStepToPrint == 0)
printf("%f %le %le %le\n",time,Vm[0],iStim[0],dVmReaction[0]);
fflush (stdout);
while (time < tEnd)
{
cellModel->calc(dt, Vm, iStim, dVmReaction);
for (unsigned ii=0; ii<nLocal; ++ii)
Vm[ii] += dt*(dVmReaction[ii] - iStim[ii]);
++loop;
time = loop*dt;
tmp = stimFunction(time);
iStim.assign(nLocal, tmp);
if (loop%printRate == 0 && loop >= firstStepToPrint)
{
printf("%f %le %le %le\n",time-equilTime,Vm[0],iStim[0],dVmReaction[0]);
fflush (stdout);
}
} // end time loop
return 0;
}
| true |
8233ff872abe7e50d68eb18b21207701627cd9ab | C++ | flupes/smake | /moving.cpp | UTF-8 | 1,161 | 3.3125 | 3 | [
"Apache-2.0"
] | permissive | #include <cstdio>
using namespace std;
struct NoMove {
NoMove(int n) : id{n} {
printf("NoMove(%d) @ %p\n", id, this);
buffer = new char[4];
for (int i = 0; i < 3; i++) buffer[i] = n + 96;
buffer[3] = 0;
}
NoMove(const NoMove& nm) {
id = nm.id;
buffer = new char[4];
for (int i = 0; i < 4; i++) buffer[i] = nm.buffer[i];
printf("NoMove Copy Constructor: id=%d @ %p\n", id, this);
}
NoMove operator=(const NoMove& nm) {
id = nm.id;
if (buffer) delete[] buffer;
buffer = new char[4];
for (int i = 0; i < 4; i++) buffer[i] = nm.buffer[i];
printf("NoMove Assignement Operator: id=%d @ %p", id, this);
return *this;
}
~NoMove() {
printf("~NoMove(%d) @ %p\n", id, this);
delete[] buffer;
}
void Data() { printf("id=%d @ %p ==> %s\n", id, this, buffer); }
int id;
char* buffer;
};
NoMove MakeNoMove(int n) { return NoMove(n); }
NoMove a{1};
int main() {
printf("starting\n");
NoMove b{2};
b.Data();
NoMove* c = new NoMove{3};
NoMove d{a};
NoMove e = b;
printf("MakeNoMove...\n");
NoMove f = MakeNoMove(4);
f.Data();
delete (c);
printf("exiting\n");
}
| true |
1fa0df9fa727cde5410faf4cf1a1baddac739880 | C++ | EnsicoinDevs/ensicoin-cpp | /src/message/messages.cpp | UTF-8 | 685 | 2.703125 | 3 | [] | no_license | #include "messages.hpp"
#include "constants.hpp"
#include "networkable.hpp"
#include "networkbuffer.hpp"
#include <iostream>
#include <string>
namespace message{
Message::Message(message_type messageType) : magic(constants::MAGIC),
type(messageType) {}
message_type Message::getType() const{
return type;
}
std::string Message::byteRepr() const{
auto strType = getTypeAsString(type);
strType += std::string(12-strType.size(), char(0x00));
auto payloadString = this->payload();
auto payloadLength = payloadString.size();
networkable::MessageHeader header(magic,strType,payloadLength);
return header.byteRepr() +
payloadString;
}
} // namespace message
| true |
63c8b6fba16dd7f9beafae5ea028e4b56dac5a00 | C++ | Stenardt-9002/CODECHEF-Datastructure-and-algo | /Gfg_list/Microsoft_30_Days/Day10/3-add_2_numbers_LL.cpp | UTF-8 | 1,856 | 3.015625 | 3 | [] | no_license | // https://practice.geeksforgeeks.org/batch/microsdaysoft-29/track/microsoft-29days-day10/problem/add-two-numbers-represented-by-linked-list
#include <bits/stdc++.h>
#include<ext/pb_ds/tree_policy.hpp>
#include<ext/pb_ds/assoc_container.hpp>
using namespace std;
using namespace __gnu_pbds ;
typedef long long int ll;
#define DEBUG_var 1
#define fastIO ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
const int mod1 = (1e9+7);
const int MOD1 = 1000000007;
struct Node {
int data;
struct Node *next;
Node(int x)
{
data = x;
next = NULL ;
}
};
Node* addSameSize(Node* head1, Node* head2, int* carry)
{
// Your code here
stack<int> s1,s2;
while (head1!=NULL && head2!=NULL)
{
s1.push(head1->data);
s2.push(head2->data);
head1 = head1->next;
head2 = head2->next;
}
int carry_temp = 0;
Node *ans1 = NULL;
while (!s1.empty() && !s2.empty())
{
int temp = carry_temp+s1.top()+s2.top();
s1.pop();
s2.pop();
carry_temp = temp/10 ;
temp = temp%10 ;
Node *nodetemp = new Node(temp);
nodetemp->next = ans1 ;
ans1 = nodetemp ;
// cout<<"\nDEUG " <<temp;
}
*carry = carry_temp ;
return ans1 ;
}
//This function is called after the smaller list is added to the sublist of
//bigger list of same size. Once the right sublist is added, the carry
//must be added to left side of larger list to get the final result.
void addCarryToRemaining(Node* head1, Node* curr, int* carry, Node** result)
{
// Your code here
if(head1->next != curr)
addCarryToRemaining(head1->next, curr, carry, result);
else if(head1->next == curr)
head1->next = *result;
head1->data += *carry;
*carry = head1->data / 10;
head1->data %= 10;
*result = head1;
}
| true |
5469c90eac8aee5a9cdb21fe09f6b77f1f309bd2 | C++ | tzn893/little-ray-tracer | /Main/Shape.h | UTF-8 | 2,193 | 2.828125 | 3 | [] | no_license | #pragma once
#include "../Tool/geometry.h"
struct Ray {
Vec3f p, dir;
Ray(Vec3f p, Vec3f dir)
:p(p),dir(dir){}
};
struct Insection { Vec4f color; Vec3f n; float t; float reflect = 0.0;};
class Shape {
public:
virtual bool insection(Ray r,Insection*) = 0;
virtual ~Shape() {}
};
class Sphere :public Shape{
public:
Sphere(Vec3f pos = Vec3f(0, 0, 0), Vec3f diffus = Vec3f(1, 0.7, 0.7), float radius = 1)
:pos(pos),radius(radius),diffus(diffus){}
virtual bool insection(Ray r,Insection* insec) override;
private:
Vec3f pos,diffus;
float radius;
};
class Plane : public Shape {
public:
Plane(float width, float length, Matrix4x4f o2w,Vec3f diffus = Vec3f(1,1,1)):
width(width),length(length),o2w(o2w),w2o(o2w.R()),diffus(diffus) {}
virtual bool insection(Ray t,Insection* insec) override;
private:
float width, length;
Matrix4x4f w2o, o2w;
Vec3f diffus;
};
class ReflectablePlane : public Plane{
public:
using Plane::insection;
ReflectablePlane(float reflect,float width,float length,Matrix4x4f o2w,Vec3f diffus = Vec3f(1,1,1)):
Plane(width,length,o2w,diffus), reflect(reflect){}
virtual bool insection(Ray r,Insection* insec)override;
private:
float reflect;
};
class ReflectableSphere : public Sphere {
public:
using Sphere::insection;
ReflectableSphere(float reflect = 0,Vec3f pos = Vec3f(0, 0, 0), Vec3f diffus = Vec3f(1, 0.7, 0.7), float radius = 1):
Sphere(pos,diffus,radius),reflect(reflect){}
virtual bool insection(Ray r,Insection* insec) override;
private:
float reflect;
};
struct Light {
virtual ~Light() {}
virtual Vec3f dir(Vec3f pos) = 0;
Light(float intensity, Vec3f color) :
intensity(clamp(intensity)),color(clamp3f(color,1,0)) {}
float intensity;
Vec3f color;
};
struct PointLight : public Light{
PointLight(float intensity,Vec3f color,Vec3f pos)
:Light(intensity,color),pos(pos){}
virtual Vec3f dir(Vec3f pos) override { return (pos - this->pos).normalize(); }
Vec3f pos;
};
struct DirectionalLight : public Light{
DirectionalLight(float intensity,Vec3f color,Vec3f direction):
Light(intensity,color),direction(direction.normalize()){}
virtual Vec3f dir(Vec3f pos)override { return direction; }
Vec3f direction;
}; | true |
c982e5526f0480af73bd76d292d2301dd9a69e90 | C++ | mpsm/spyc | /src/Call.hh | UTF-8 | 952 | 2.8125 | 3 | [
"MIT"
] | permissive | #ifndef __SPYC_CALL_HH__
#define __SPYC_CALL_HH__
#include "Method.hh"
#include <functional>
#include <unordered_set>
#include <utility>
namespace spyc {
using Call = std::pair<std::reference_wrapper<const Method>,
std::reference_wrapper<const Method>>;
struct CallHasher {
std::size_t
operator()(const Call& c) const noexcept
{
return ~std::hash<Method>{}(c.first.get()) |
std::hash<Method>{}(c.second.get());
}
};
struct CallCompare {
bool
operator()(const Call& left, const Call& right) const noexcept
{
return (left.first.get() == right.first.get()) &&
(left.second.get() == right.second.get());
}
};
using CallSet = std::unordered_set<Call, CallHasher, CallCompare>;
Call make_call(const Method& caller, const Method& callee);
} // namespace spyc
#endif /* __SPYC_CALL_HH__ */ | true |
2111405ef6adaedf7b72cdb414bfdaf36289974d | C++ | harsimarsingh8/C-AND-Cpp-Questions- | /C++ Questions/Q-41.cpp | UTF-8 | 967 | 3.8125 | 4 | [] | no_license | #include<iostream>
using namespace std;
class counter
{
static int count;
public:
void increment();
void decrement();
static void print();
};
int counter::count;
void counter::increment()
{
count++;
}
void counter::decrement()
{
count--;
}
void counter::print()
{
cout<<"Value is "<<count<<endl;
}
int main()
{
counter obj;
int val=1;
while(val!=0)
{
cout<<"Enter 1 to increment 2 to decrement or 0 to exit"<<endl;
cin>>val;
if(val==0)
{
break;
}
else if(val==1)
{
obj.increment();
counter::print();
}
else if(val==2)
{
obj.decrement();
counter::print();
}
}
} | true |
cad7be39b4a7bebd478fc011874252f36b2ff35e | C++ | shpp-vhrebenko/cs-b-assignment1 | /4-Flesch-Kincaid/src/FleschKincaid.cpp | UTF-8 | 3,651 | 3.65625 | 4 | [] | no_license | #include <iostream>
#include "console.h"
#include <fstream>
#include "tokenscanner.h"
using namespace std;
//Function prototypes
void settingFile();
void fleschKincaid(ifstream &infile);
int syllablesIn(string word);
bool checkVowels(char letter);
double grade(int words,int sentens,int syllables);
int main() {
settingFile();
return 0;
}
/*The function prompts the user for a filename.
Checks whether there is such a file.
If there is the object -ifstream infile-(The object read from the stream file) creates the file and
passes it to the function fleschKincaid */
void settingFile(){
char str[255];
cout<<"Enter input file name: ";
if(cin.getline(str, sizeof(str))){
ifstream infile(str,ios::in);
if(infile.is_open()){
fleschKincaid(infile);
infile.close();
}
else{
cout<<"This file does not exist"<<endl;
settingFile();
}
}
}
/*The function takes an object by reference,
and creates for him an object TokenScanner scanner*/
void fleschKincaid(ifstream &infile){
TokenScanner scanner(infile);
//Definitions of symbols are ignored when scanning
scanner.ignoreWhitespace();
scanner.addWordCharacters("\'");
/*Create a variable to store the number of words,
sentences and syllables.*/
int words = 0;
int sentens = 0;
int syllables = 0;
/*Reading the file using a TokenScanner. Finding token.
Determination of the number of words and syllables therein.
As well as determining the number of sentences.*/
while (scanner.hasMoreTokens()) {
string token = scanner.nextToken();
if(isalpha(token[0])){
syllables += syllablesIn(token);
words++;
}
else if(token[0]=='.'||token[0]=='!'||token[0]== '?'){
sentens++;
}
}
if(words == 0 && sentens == 0){
words = 1;
sentens =1;
}
/*Displays the number of words, sentences, syllables and Grade Level.*/
cout<<"Words: "<<words<<endl;
cout<<"Syllables: "<<syllables<<endl;
cout<<"Sentences: "<<sentens<<endl;
double gradeLevel = grade(words,sentens,syllables);
cout<<"Grade Level: "<<gradeLevel<<endl;
}
//Determination of the number of syllables
int syllablesIn(string word) {
int countWSyllables = 0;
for (int i = 0; i < word.length(); i++) {
char letter = tolower(word[i]);
if (checkVowels(letter)) {
if (i == 0) {
countWSyllables++;
} else if (letter == 'e' && i != word.length() - 1 && !checkVowels(word[i - 1])) {
countWSyllables++;
} else if (i > 0) {
if (letter != 'e' && !checkVowels(word[i - 1])) {
countWSyllables++;
}
}
}
}
if (countWSyllables == 0) {
countWSyllables = 1;
}
return countWSyllables;
}
//Determination of whether the letter is a vowel
bool checkVowels(char letter) {
if (letter == 'a' || letter == 'e' || letter == 'y'
|| letter == 'i' || letter == 'u' || letter == 'o') {
return true;
}
return false;
}
//Calculation Grade Level formula with pre-defined constants.
double grade(int words,int sentens,int syllables){
double grade=0;
double const c0=-15.59;
double const c1=0.39;
double const c2=11.8;
grade = c0+c1*((double)words/sentens)+c2*((double)syllables/words);
return grade;
}
| true |
b2ce901a254378c771b25b6406de7092ffa4a9ee | C++ | MythaelX/Projet_Ultime | /Cpp/Widgets/Scene.hpp | UTF-8 | 631 | 2.640625 | 3 | [] | no_license | /*!
*
* \file Scene.hpp
* \author Mathias CABIOCH-DELALANDE
* \date 30 mai 2018
*
*/
#ifndef HEADER_SCENE
#define HEADER_SCENE
#include <QtWidgets>
#include <iostream>
/*!
* \class Scene
* \brief An implementation of QGraphcsScene with an updator
*/
class Scene : public QGraphicsScene {
Q_OBJECT
public:
/*! \brief Construct the QGraphicsScene */
Scene(QObject* parent = nullptr);
~Scene();
public slots:
/*!
* \brief A pure virtual method to redefine it in child classes
* \return void
*/
virtual void update() = 0;
signals:
protected:
bool initialized;
private:
QTimer* updater;
};
#endif //HEADER_SCENE
| true |
780d2d2339ced935e187c740335f97d585bb8785 | C++ | pulkitag/caffe | /include/caffe/layers/topography_layer.hpp | UTF-8 | 2,215 | 2.578125 | 3 | [
"BSD-3-Clause",
"MIT",
"BSD-2-Clause",
"LicenseRef-scancode-public-domain"
] | permissive | #ifndef CAFFE_TOPOGRAPHY_LAYER_HPP_
#define CAFFE_TOPOGRAPHY_LAYER_HPP_
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
namespace caffe {
/**
* @brief: The channels are arranged in a 2D topography.
*
*/
template <typename Dtype>
class TopographyLayer : public Layer<Dtype> {
public:
explicit TopographyLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual inline const char* type() const { return "Topography"; }
virtual inline int MinBottomBlobs() const { return 1; }
virtual inline int MinTopBlobs() const { return 1; }
virtual inline bool EqualNumBottomTopBlobs() const { return true; }
virtual inline void PrintWeights() const;
protected:
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
int kernel_h_, kernel_w_;
int stride_h_, stride_w_;
int num_;
int channels_;
int pad_h_, pad_w_;
int height_, width_;
int chHeight_, chWidth_;
int group_;
int height_out_, width_out_;
int height_col_, width_col_;
bool smooth_output_;
/// M_ is the channel dimension of the output for a single group, which is the
/// leading dimension of the filter matrix.
int M_;
/// K_ is the dimension of an unrolled input for a single group, which is the
/// leading dimension of the data matrix.
int K_;
/// N_ is the spatial dimension of the output, the H x W, which are the last
/// dimensions of the data and filter matrices.
int N_;
Blob<Dtype> col_buffer_;
Blob<Dtype> top_col_buffer_;
};
} //namespave caffe
#endif // CAFFE_RANDOM_NOISE_LAYER_HPP_
| true |
07f9a0d878cc68cb4f3088ac4a00927992e1dc3e | C++ | Elescant/SevenColor | /CusLabel.cpp | UTF-8 | 1,144 | 2.65625 | 3 | [] | no_license | #include "CusLabel.h"
#include <QPalette>
#include <QDebug>
CusLabel::CusLabel(QWidget *parent, Qt::WindowFlags f):
QLabel(parent,f)
{
}
CusLabel::CusLabel(const QString &text, QWidget *parent, Qt::WindowFlags f):
QLabel(text,parent,f)
{
}
CusLabel::~CusLabel()
{
}
void CusLabel::mouseReleaseEvent(QMouseEvent *event)
{
Q_UNUSED(event)
emit clicked();
QString str=QString("rgb(%1,%2,%3)").arg(color.red()).arg(color.green()).arg(color.blue());
this->setStyleSheet("background-color:"+str);
}
void CusLabel::mousePressEvent(QMouseEvent *event)
{
Q_UNUSED(event)
QPalette pat = palette();
color = pat.color(QPalette::Background);
QColor temp = lightenDarkenColor(color,-20);
this->setStyleSheet(QString("background-color: rgb(%1, %2, %3);").arg(temp.red()).arg(temp.green()).arg(temp.blue()));
}
QColor CusLabel::lightenDarkenColor(QColor color,int factor)
{
QColor newColor;
newColor.setRed(qBound(0,color.red() + factor,255));
newColor.setGreen(qBound(0,color.green() + factor,255));
newColor.setBlue(qBound(0,color.blue() + factor,255));
return newColor;
}
| true |
af18e00ace152635d3b32f63a6f441f7d0108c95 | C++ | henryzrr/hackerEart | /cod/e-maze.cpp | UTF-8 | 538 | 2.65625 | 3 | [] | no_license | #include<stdio.h>
using namespace std;
int main(){
char cad[205];
scanf("%s",cad);
int i=0,posx=0,posy=0;;
while(cad[i]!='\0'){
switch (cad[i])
{
case'L':
posx -=1;
break;
case'R':
posx +=1;
break;
case'U':
posy +=1;
break;
default:
posy -=1;
break;
}
i++;
}
printf("%i %i\n",posx,posy);
return 0;
} | true |
70b3866b383c81e519a1cc7cc9dec6e3239764f0 | C++ | duchevich/c-plus-plus-VS2017-course | /Project3/Project3/main.cpp | WINDOWS-1251 | 2,796 | 2.765625 | 3 | [] | no_license | #include <iostream>
#include "SDL.h"
#include "Game.h"
using namespace std;
Game *game = nullptr;
int main(int argc, char* argv[]) {
game = new Game;
game->init("Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, true);
while (game->running()) {
game->handleEvent();
game->update();
game->render();
}
game->clean();
return 0;
/*if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
cout << "SDL_Init Error: " << SDL_GetError() << endl;
return 1;
}
SDL_Window *win = SDL_CreateWindow("Hello World!", 100, 100, 640, 480, SDL_WINDOW_SHOWN);
if (win == nullptr) {
cout << "SDL_CreateWindow Error: " << SDL_GetError() << endl;
return 2;
}
SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (ren == nullptr) {
cout << "SDL_CreateRenderer Error: " << SDL_GetError() << endl;
return 3;
}
SDL_Surface *bmp = SDL_LoadBMP("hello.bmp");
if (bmp == nullptr) {
cout << "SDL_LoadBMP Error: " << SDL_GetError() << endl;
system("pause");
return 4;
}
SDL_Texture *tex = SDL_CreateTextureFromSurface(ren, bmp);
SDL_FreeSurface(bmp);
if (tex == nullptr) {
cout << "SDL_CreateTextureFromSurface Error: " << SDL_GetError() << std::endl;
return 5;
}
SDL_RenderClear(ren);
SDL_RenderCopy(ren, tex, NULL, NULL);
SDL_RenderPresent(ren);
SDL_Delay(2000);
SDL_DestroyTexture(tex);
SDL_DestroyRenderer(ren);
SDL_DestroyWindow(win);
SDL_Quit();
return 0;*/
}
/*#include <stdio.h>
#include <iostream>
#include <windows.h>
#include <string.h>
#include <tchar.h>
#include "sqlite3.h"
using namespace std;
// - int main() :
int WINAPI WinMain(HINSTANCE hInstance, //
HINSTANCE hPrevInstance, // Win32
LPSTR lpCmdLine, //
int nCmdShow) //
{
// "" ( )
MessageBox(NULL, ", !!!", " ", MB_OK);
return NULL; //
}
*/
/*
int main(int argc, char* argv[])
{
sqlite3 *db;
int rc;
tstring msg;
rc = sqlite3_open("test.db", &db);
if (rc) {
msg = "Can't open database: %s\n" + (string)sqlite3_errmsg(db);
MessageBox(NULL, msg, " ", MB_OK);
exit(0);
}
else {
msg = "Opened database successfully\n";
MessageBox(NULL, msg, " ", MB_OK);
}
sqlite3_close(db);
system("pause");
}*/ | true |
e9ee8a146e5082f10ecde3476dedb86176a8d832 | C++ | MaximBombardier/Arena-v-2.0 | /Magic/AttackMagic/AttackMagic.h | UTF-8 | 705 | 2.890625 | 3 | [] | no_license | #ifndef ATTACK_MAGIC_H_
#define ATTACK_MAGIC_H_
#include "../Magic.h"
class AttackMagic : virtual public Magic
{
public:
AttackMagic(std::string name, int manaCost, int damage);
virtual void effectUnit(Unit& unit) override;
virtual void uneffectUnit(Unit& unit)const override;
virtual MagicPtr clone()const override;
virtual bool isBuff()const override;
virtual bool isEqual(const MagicPtr& magic)const override;
virtual void showFullInfo()const override;
virtual ~AttackMagic() = default;
protected:
virtual bool hasEqualParametres(const MagicPtr& magic)const override;
virtual void showData()const override;
virtual void putOn(Unit& unit)const override;
protected:
int m_damage;
};
#endif | true |
079916d9eb915515683c67b50d112b82798be369 | C++ | CaroRomo1/InterviewQuestions | /TopTecProgrammer/2623 - Super Encryption/Caro/2623 - Super Encryption/2623 - Super Encryption/main.cpp | UTF-8 | 983 | 3.203125 | 3 | [] | no_license | //
// main.cpp
// 2623 - Super Encryption
//
// Created by Carolina Romo on 2/7/17.
// Copyright © 2017 CaroRomo. All rights reserved.
//
#include <iostream>
using namespace std;
string reverseString(string str){
int i = 0, j = int(str.length()-1);
char aux;
while (i < j) {
aux = str[i];
str[i] = str[j];
str[j] = aux;
i++;
j--;
}
return str;
}
int main() {
string str, part1 = "", part2 = "";
cin >> str;
if (int(str.length()) % 2 == 0){
part1 = str.substr(0,int((str.length()/2)));
part2 = str.substr(int(str.length()/2), int((str.length()/2)));
cout << reverseString(part1) << reverseString(part2) << endl;
}
else {
part1 = str.substr(0,int((str.length()/2)));
part2 = str.substr(int(str.length()/2)+1, int((str.length()/2)));
cout << reverseString(part1) << str[str.length()/2] << reverseString(part2) << endl;
}
return 0;
}
| true |
14415b3f97311a979fe0424655a31cd455e64420 | C++ | wzxchy/code_c | /20150527/LU_Decomposition.cpp | UTF-8 | 1,184 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include "stdio.h"
#include "string.h"
#include <cmath>
using namespace std;
const int maxn=20;
double a[maxn][maxn];
double x[maxn],b[maxn];
void backward(int n)
{
int i,j;
for(i=n;i>0;i--)
{
double s=0;
for(j=i+1;j<=n;j++)
{
s+=a[i][j]*x[j];
}
x[i]=(b[i]-s)/a[i][i];
}
}
void forward(int n)
{
int i,j;
for(i=1;i<=n;i++)
{
double s=0;
for(j=1;j<i;j++)
{
s+=a[i][j]*x[j];
}
x[i]=(b[i]-s)/a[i][i];
}
}
void LU_Decomposition(int n)
{
int i,j,k;
for(k=1;k<n;k++)
{
for(i=k+1;i<=n;i++)
{
a[i][k]=a[i][k]/a[k][k];
for(j=k+1;j<=n;j++)
{
a[i][j]=a[i][j]-a[i][k]*a[k][j];
}
}
}
}
int main()
{
int n,i,j;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
scanf("%lf",&a[i][j]);
}
LU_Decomposition(n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%.2lf ",a[i][j]);
}
printf("\n");
}
return 0;
}
/*
3
1 -1 3
1 1 0
3 -2 1
*/
| true |
f2ab05f2b0091bf9c8849f415cd89cfe5d377cdb | C++ | dry3ss/MLF | /machine_learning_framework/src/framework_headers/MLF_InterfaceLayers.h | UTF-8 | 1,106 | 3.109375 | 3 | [] | no_license | #pragma once
#include <vector>
template<class T>
using VectorMatrix3D = std::vector< std::vector < std::vector<T> > >;
template <class T>
class InterfaceLayers// this is quite ugly, I just want to hold something like vector<vector<vector<float>>>
{ //where i can do in[layer_nb][neuron_nb][weight_nb], but be able to hold just as easily
//queue<queue<queue<float>>>
public:
virtual T &get(const int layer_nb, const int neuron_nb, const int weight_nb)const = 0;
virtual int size_layers()const = 0;
virtual int size_neurons(const int layer_nb)const = 0;
virtual int size_weights(const int layer_nb, const int neuron_nb)const = 0;
};
template <class T>
class VectorLayers
{
public:
VectorMatrix3D<T> a;
virtual T &get(int layer_nb, int neuron_nb, int weight_nb)const
{
return a[layer_nb][neuron_nb][weight_nb];
}
virtual int size_layers()const
{
return a.size();
}
virtual int size_neurons(const int layer_nb)const
{
return a[layer_nb].size();
}
virtual int size_weights(const int layer_nb, const int neuron_nb)const
{
return a[layer_nb][neuron_nb].size();
}
};
| true |
4cd3caccca5007c72eb24d65c161e555e574353f | C++ | AlMazyr/algorithms | /sw_tests/magn/magnetic_dev2.cpp | UTF-8 | 6,361 | 2.65625 | 3 | [] | no_license | #include <iostream>
using namespace std;
#define N_MAX 100
#define QUEUE_MAX 10000000
#define extract_bit(bit_arr,idx) ((bit_arr[(idx)/8] >> (idx)%8) & 1)
#define set_bit(bit_arr,idx) (bit_arr[(idx)/8] |= 1 << ((idx)%8))
typedef unsigned char uint8;
struct Elem {
uint8 bit_arr[13]; // 100 bits == 12.5 bytes
uint8 it; // number of bits in the array
uint8 rep; // number of repetitive bits from the right end
uint8 min_rep;
uint8 recs; // number of recs for min_rep
};
unsigned long long v_cnt = 0; //DEBUG
int head, tail;
Elem queue[QUEUE_MAX];
int used[N_MAX][N_MAX][N_MAX][2]; //[min_rep][rep][bits][last_bit]
int calc_rec_num(uint8 *bit_arr, int idx, int n)
{
int recs = 0, rep = 0;
int prev = extract_bit(bit_arr, 0);
for (int i = 1; i < idx; ++i) {
int cur = extract_bit(bit_arr, i);
if (cur != prev) {
recs += rep / n;
if (rep % n)
recs++;
rep = 1;
prev = cur;
} else {
rep++;
}
}
recs += rep / n;
if (rep % n)
recs++;
return recs;
}
int calc_score(int lc, int n, int k, int recs)
{
return lc * n + k * recs;
}
//DEBUG
void print_bitarr(uint8 *ba, int it)
{
for (int i = 0; i < it; ++i) {
cout << extract_bit(ba, i);
}
cout << endl;
}
void print_elem(Elem &el)
{
print_bitarr(el.bit_arr, el.it);
cout << (int)el.it << ' ' << (int)el.rep << endl << endl;
}
int is_val(Elem &el, int min_sc, int LC, int K)
{
if (el.rep < el.min_rep)
return 1;
int score = calc_score(LC, el.min_rep, K, el.recs);
return score > min_sc ? 0 : 1;
}
uint8 bitarr_r[5] = {0b11110000, 0b11000000, 0b11};
int exec_test(int N, int LC, int K, char *str)
{
char *ch;
int str_cnt = 0; //DEBUG
int min_score;
Elem e;
for (int i = 0; i < N_MAX; ++i) {
for (int j = 0; j < N_MAX; ++j) {
for (int k = 0; k < N_MAX; ++k) {
used[i][j][k][0] = 0;
used[i][j][k][1] = 0;
}
}
}
v_cnt = 0;
int i = 0;
char prev = str[0];
for (ch = str; *ch; ch++) {
str_cnt++;
if (*ch == '*') {
continue;
} else {
if (*ch != prev) {
i ^= 1;
prev = *ch;
}
*ch = '0' + i;
}
}
// we can calculate score for n=1
min_score = calc_score(LC, 1, K, N);
//cout << "Min score for n=1 : " << min_score << endl;
head = 0;
tail = 0;
e.it = 1;
e.rep = 0;
e.min_rep = N;
e.recs = 0;
for (int i = 0; i < 13; ++i)
e.bit_arr[i] = 0;
if (str[0] == '1')
e.bit_arr[0] |= 1;
queue[tail++] = e;
while (tail != head) {
Elem &cur = queue[head++];
bool invalid = false;
// iterate over string until end or fork
int i = cur.it;
char prev = extract_bit(cur.bit_arr, i-1) + '0';
for (ch = &str[i-1]; *ch; ch++) {
uint8 bit = extract_bit(cur.bit_arr, i-1);
v_cnt++; //DEBUG
if (*ch != '*') {
if (*ch != prev) {
if (cur.rep < 2) {
// invalid elem
invalid = true;
break;
}
if (cur.rep < cur.min_rep) {
cur.min_rep = cur.rep;
cur.recs = calc_rec_num(cur.bit_arr, i,
cur.min_rep);
} else {
cur.recs += cur.rep / cur.min_rep;
if (cur.rep % cur.min_rep)
cur.recs += 1;
}
// check used array
if (used[cur.min_rep][cur.recs][i][bit]) {
invalid = true;
break;
}
used[cur.min_rep][cur.recs][i][bit] = 1;
cur.rep = 1;
} else {
cur.rep++;
}
if (*ch == '1')
set_bit(cur.bit_arr, i);
i++;
prev = *ch;
} else { // ch == '*'
bool e1_bad = false, e2_bad = false;
if (cur.rep >= 2 || cur.it == 1) {
Elem e1 = cur, e2 = cur;
set_bit(e1.bit_arr, i);
if (prev == '1') {
e1.rep++;
if (cur.it != 1) {
if (e2.rep < e2.min_rep) {
e2.min_rep = e2.rep;
e2.recs = calc_rec_num(e2.bit_arr, i, e2.min_rep);
} else {
e2.recs += e2.rep / e2.min_rep;
if (e2.rep % e2.min_rep)
e2.recs += 1;
}
if (used[e2.min_rep][e2.recs][i][bit])
e2_bad = true;
else
used[e2.min_rep][e2.recs][i][bit] = 1;
}
e2.rep = 1;
} else {
e2.rep++;
if (cur.it != 1) {
if (e1.rep < e1.min_rep) {
e1.min_rep = e1.rep;
e1.recs = calc_rec_num(e1.bit_arr, i, e1.min_rep);
} else {
e1.recs += e1.rep / e1.min_rep;
if (e1.rep % e1.min_rep)
e1.recs += 1;
}
if (used[e1.min_rep][e1.recs][i][bit])
e1_bad = true;
else
used[e1.min_rep][e1.recs][i][bit] = 1;
}
e1.rep = 1;
}
i++;
e1.it = i;
e2.it = i;
if (!e1_bad)
queue[tail++] = e1;
if (!e2_bad)
queue[tail++] = e2;
//DEBUG
/*
if (tail >= QUEUE_MAX) {
cout << "Queue overflow!" << endl;
cout << tail << endl;
}
*/
invalid = true;
break;
} else {
// duplicate prev
cur.rep++;
if (prev == '1') {
set_bit(cur.bit_arr, i);
}
i++;
}
}
cur.it = i;
/*
if (!is_val(cur, min_score, LC, K)) {
invalid = true;
break;
}
*/
}
if (invalid || cur.rep < 2)
continue;
if (cur.rep < cur.min_rep) {
cur.min_rep = cur.rep;
cur.recs = calc_rec_num(cur.bit_arr, cur.it, cur.min_rep);
} else {
cur.recs += cur.rep / cur.min_rep;
if (cur.rep % cur.min_rep)
cur.recs += 1;
}
//cout << "n:" << (int)cur.min_rep << " r:" << (int)cur.recs << endl;
//cout << "rep:" << (int)cur.rep << endl;
/*
if (cur.min_rep == 4) {
print_bitarr(cur.bit_arr, cur.it);
}*/
for (int i = 2; i <= cur.min_rep; ++i) {
cur.recs = calc_rec_num(cur.bit_arr, cur.it, i);
int score = calc_score(LC, i, K, cur.recs);
if (score < min_score) {
min_score = score;
}
}
/*
int score = calc_score(LC, cur.min_rep, K, cur.recs);
if (score < min_score) {
min_score = score;
//DEBUG
cout << "min_score: " << min_score << endl;
cout << "n:" << (int)cur.min_rep << " r:" << (int)cur.recs << endl;
cout << "rep:" << (int)cur.rep << endl;
print_bitarr(cur.bit_arr, cur.it);
}
*/
}
//DEBUG
//cout << "tail: " << tail << " head: " << head << " v_cnt: " << v_cnt
// << endl;
return min_score;
}
int main()
{
int test_total;
int N, LC, K;
char str[N_MAX+1];
cin >> test_total;
cout << "REF bitarr:" << endl;
print_bitarr(bitarr_r, 22);
for (int i = 0; i < test_total; ++i) {
cin >> N >> LC >> K >> str;
cout << '#' << i+1 << ' ' << exec_test(N, LC, K, str) << endl;
}
return 0;
}
| true |
1cca72bfb60802d6579247ae7f5b1e4dfd3944db | C++ | necabo/ppcpp | /chapter4/primes.cpp | UTF-8 | 711 | 3.703125 | 4 | [] | no_license | #include <vector>
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int n;
cout << "Enter a number up to which you want to know the prime numbers:\n";
cin >> n;
vector<bool> striked(n, false);
striked[0] = true;
striked[1] = true;
vector<int> primes;
for (int i = 2; i <= sqrt(n); ++i) {
if (!striked[i]) {
for (int j = i * i; j <= n; j += i)
striked[j] = true;
}
}
for (size_t i = 0; i < striked.size(); ++i) {
if (!striked[i])
primes.push_back(i);
}
cout << "Here are the prime numbers up to " << n << ":\n";
for (int prime: primes)
cout << prime << '\n';
}
| true |
582fee171ce20b8c71445b15d623dafc78bb7b9a | C++ | ClaudioTazza/listecpp | /likePython/nodo.cpp | UTF-8 | 960 | 3.625 | 4 | [] | no_license | #include <iostream>
using namespace std;
#include "nodo.hpp"
#include <cstddef>
nodo::nodo(int n){
setNum(n);
setNext(NULL);
}//Costruttore del nodo
void nodo::setNum(int n){
num = n;
}//Setta il valore all'interno del nodo
void nodo::setNext(nodo* nextNodo){
next = nextNodo;
}
int nodo::getNum(){
return num;
}//Ritorna il numero presente nel nodo
nodo* nodo::getNext(){
return next;
}//Ritorna il nodo successivo
void nodo::append(int Num){
if(this->getNext() == NULL){
this->setNext(new nodo(Num));
}//Se il nodo e' l'ultimo ne attacca uno nuovo con Num
else{
(*this->getNext()).append(Num);
}//Altrimenti passa al prossimo
}
void nodo::stampa(){
if(this->getNext() == NULL){
cout << this->getNum() << endl;
}//Se il nodo e' l'ultimo nodo, lo stampa e si ferma
else{
cout << this->getNum() << endl; //Stampa il nodo attuale
(*this->getNext()).stampa(); //Stampa il prossimo nodo e i restanti
}
}
| true |
6db95fa81b890ecfad761663620517fc00690bd6 | C++ | akashmodak97/Competitive-Coding-and-Interview-Problems | /Leet Code/Time Needed to Buy Tickets.cpp | UTF-8 | 1,873 | 3.546875 | 4 | [
"MIT"
] | permissive | /* Leet Code */
/* Title - Time Needed to Buy Tickets */
/* Created By - Akash Modak */
/* Date - 14/05/2023 */
// There are n people in a line queuing to buy tickets, where the 0th person is at the front of the line and the (n - 1)th person is at the back of the line.
// You are given a 0-indexed integer array tickets of length n where the number of tickets that the ith person would like to buy is tickets[i].
// Each person takes exactly 1 second to buy a ticket. A person can only buy 1 ticket at a time and has to go back to the end of the line (which happens instantaneously) in order to buy more tickets. If a person does not have any tickets left to buy, the person will leave the line.
// Return the time taken for the person at position k (0-indexed) to finish buying tickets.
// Example 1:
// Input: tickets = [2,3,2], k = 2
// Output: 6
// Explanation:
// - In the first pass, everyone in the line buys a ticket and the line becomes [1, 2, 1].
// - In the second pass, everyone in the line buys a ticket and the line becomes [0, 1, 0].
// The person at position 2 has successfully bought 2 tickets and it took 3 + 3 = 6 seconds.
// Example 2:
// Input: tickets = [5,1,1,1], k = 0
// Output: 8
// Explanation:
// - In the first pass, everyone in the line buys a ticket and the line becomes [4, 0, 0, 0].
// - In the next 4 passes, only the person in position 0 is buying tickets.
// The person at position 0 has successfully bought 5 tickets and it took 4 + 1 + 1 + 1 + 1 = 8 seconds.
class Solution {
public:
int timeRequiredToBuy(vector<int>& tickets, int k) {
int count = 0, maximumValues = 0;
for(int i=k+1;i<tickets.size();i++) if(tickets[k]<=tickets[i]) maximumValues++;
for(int i=0;i<tickets.size();i++) count = tickets[k]>tickets[i] ? count+tickets[i] : count+tickets[k];
return count-maximumValues;
}
};
| true |
e9dac7f4c0e149b06c16f1cd3c14d7fac1016867 | C++ | deadzora/Zorlock | /Zorlock/src/Zorlock/Core/Math.cpp | UTF-8 | 5,048 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | #include "ZLpch.h"
#include "Math.h"
#include "Zorlock/Renderer/Color.h"
namespace Zorlock
{
Vector3::Vector3(ColorRGB& c) : x(c.x), y(c.y), z(c.z)
{
}
Vector3 Vector3::lerp(float t, const Vector3& a, const Vector3& b)
{
t = MathF::clamp(t, 0, 1);
return (1.0f - t) * a + t * b;
}
Vector4::Vector4(ColorRGB& c) : x(c.x), y(c.y), z(c.z), w(1.0f)
{
}
Vector4::Vector4(ColorRGBA& c) : x(c.x), y(c.y), z(c.z), w(c.w)
{
}
void Quaternion::fromRotationMatrix(const Matrix& mata)
{
// Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
// article "Quaternion Calculus and Fast Animation".
MATRIX3ARRAY& mat = Matrix(mata).ToArray();
float trace = mat[0][0] + mat[1][1] + mat[2][2];
float root;
if (trace > 0.0f)
{
// |w| > 1/2, may as well choose w > 1/2
root = sqrt(trace + 1.0f); // 2w
w = 0.5f * root;
root = 0.5f / root; // 1/(4w)
x = (mat[2][1] - mat[1][2]) * root;
y = (mat[0][2] - mat[2][0]) * root;
z = (mat[1][0] - mat[0][1]) * root;
}
else
{
// |w| <= 1/2
static UINT32 nextLookup[3] = { 1, 2, 0 };
UINT32 i = 0;
if (mat[1][1] > mat[0][0])
i = 1;
if (mat[2][2] > mat[i][i])
i = 2;
UINT32 j = nextLookup[i];
UINT32 k = nextLookup[j];
root = sqrt(mat[i][i] - mat[j][j] - mat[k][k] + 1.0f);
float* cmpntLookup[3] = { &x, &y, &z };
*cmpntLookup[i] = 0.5f * root;
root = 0.5f / root;
w = (mat[k][j] - mat[j][k]) * root;
*cmpntLookup[j] = (mat[j][i] + mat[i][j]) * root;
*cmpntLookup[k] = (mat[k][i] + mat[i][k]) * root;
}
normalize();
}
Quaternion Quaternion::normalize(const Quaternion& q, float tolerance)
{
float sqrdLen = dot(q, q);
if (sqrdLen > tolerance)
return q * MathF::invSqrt(sqrdLen);
return q;
}
Quaternion Quaternion::slerp(float t, const Quaternion& p, const Quaternion& q, bool shortestPath)
{
float cos = p.dot(q);
Quaternion quat;
if (cos < 0.0f && shortestPath)
{
cos = -cos;
quat = -q;
}
else
{
quat = q;
}
if (abs(cos) < 1 - EPSILON)
{
// Standard case (slerp)
float sin = sqrtf(1 - MathF::sqr(cos));
float angle = MathF::RadiansFromDegrees(atan2(sin, cos));
float invSin = 1.0f / sin;
float coeff0 = sinf((1.0f - t) * angle) * invSin;
float coeff1 = sinf(t * angle) * invSin;
return coeff0 * p + coeff1 * quat;
}
else
{
// There are two situations:
// 1. "p" and "q" are very close (fCos ~= +1), so we can do a linear
// interpolation safely.
// 2. "p" and "q" are almost inverse of each other (fCos ~= -1), there
// are an infinite number of possibilities interpolation. but we haven't
// have method to fix this case, so just use linear interpolation here.
Quaternion ret = (1.0f - t) * p + t * quat;
// Taking the complement requires renormalization
ret.normalize();
return ret;
}
}
void Matrix::QDUDecomposition(Matrix& matQ, Vector3& vecD, Vector3& vecU) const
{
// Build orthogonal matrix Q
float invLength = MathF::invSqrt(i.x * i.x + j.x * j.x + k.x * k.x);
matQ.i.x = i.x * invLength;
matQ.j.x = j.x * invLength;
matQ.k.x = k.x * invLength;
float dot = matQ.i.x * i.y + matQ.j.x * j.y + matQ.k.x * k.y;
matQ.i.y = i.y - dot * matQ.i.x;
matQ.j.y = j.y - dot * matQ.j.x;
matQ.k.y = k.y - dot * matQ.k.x;
invLength = MathF::invSqrt(matQ.i.y * matQ.i.y + matQ.j.y * matQ.j.y + matQ.k.y * matQ.k.y);
matQ.i.y *= invLength;
matQ.j.y *= invLength;
matQ.k.y *= invLength;
dot = matQ.i.x * i.z + matQ.j.x * j.z + matQ.k.x * k.z;
matQ.i.z = i.z - dot * matQ.i.x;
matQ.j.z = j.z - dot * matQ.j.x;
matQ.k.z = k.z - dot * matQ.k.x;
dot = matQ.i.y * i.z + matQ.j.y * j.z + matQ.k.y * k.z;
matQ.i.z -= dot * matQ.i.y;
matQ.j.z -= dot * matQ.j.y;
matQ.k.z -= dot * matQ.k.y;
invLength = MathF::invSqrt(matQ.i.z * matQ.i.z + matQ.j.z * matQ.j.z + matQ.k.z * matQ.k.z);
matQ.i.z *= invLength;
matQ.j.z *= invLength;
matQ.k.z *= invLength;
// Guarantee that orthogonal matrix has determinant 1 (no reflections)
float fDet = matQ.i.x * matQ.j.y * matQ.k.z + matQ.i.y * matQ.j.z * matQ.k.x +
matQ.i.z * matQ.j.x * matQ.k.y - matQ.i.z * matQ.j.y * matQ.k.x -
matQ.i.y * matQ.j.x * matQ.k.z - matQ.i.x * matQ.j.z * matQ.k.y;
if (fDet < 0.0f)
{
matQ.inverse();
}
// Build "right" matrix R
Matrix matRight;
matRight.i.x = matQ.i.x * i.x + matQ.j.x * j.x +
matQ.k.x * k.x;
matRight.i.y = matQ.i.x * i.y + matQ.j.x * j.y +
matQ.k.x * k.y;
matRight.j.y = matQ.i.y * i.y + matQ.j.y * j.y +
matQ.k.y * k.y;
matRight.i.z = matQ.i.x * i.z + matQ.j.x * j.z +
matQ.k.x * k.z;
matRight.j.z = matQ.i.y * i.z + matQ.j.y * j.z +
matQ.k.y * k.z;
matRight.k.z = matQ.i.z * i.z + matQ.j.z * j.z +
matQ.k.z * k.z;
// The scaling component
vecD.x = matRight.i.x;
vecD.y = matRight.j.y;
vecD.z = matRight.k.z;
// The shear component
float invD0 = 1.0f / vecD.x;
vecU.x = matRight.i.y * invD0;
vecU.y = matRight.i.z * invD0;
vecU.z = matRight.j.z / vecD.y;
}
}
| true |
2535904023c3b1fc79900e50ea9954a9de80bc30 | C++ | asteroid-612/BattleShip | /GameManager.cpp | UTF-8 | 3,558 | 3.015625 | 3 | [] | no_license | #include "GameManager.h"
#include "Player.h"
#include "Ship.h"
#include "Aircraft.h"
#include "Battleship.h"
#include "Cruiser.h"
#include "Destroyer.h"
#include <iostream>
using namespace std;
GameManager::GameManager()
{
m_Attacker = NULL;
m_Defender = NULL;
}
GameManager::~GameManager()
{
if(m_Attacker)
{
delete m_Attacker;
m_Attacker = NULL;
}
if(m_Defender)
{
delete m_Defender;
m_Defender = NULL;
}
}
void GameManager::Init()
{
m_Attacker = new Player();
m_Defender = new Player();
// 여기가 다형성. ship 을 상속받은 abcd는 ship의 자리에 들어갈 수 있다.
std::vector<Ship*> vecShip;
vecShip.push_back(new Aircraft());
vecShip.push_back(new Battleship());
vecShip.push_back(new Cruiser());
vecShip.push_back(new Destroyer());
vecShip.push_back(new Destroyer());
// vector를 하나하나 돌면서 delete 해줘야하고, 그 이후에 clear가능.
/*
// 부모는 자식의 자리에 들어갈 수 없다.
vecShip[0]; // 의 타입은 무엇이지 ? Ship이다.
vecShip[1]; // 얘도 물론 ship이다.
Aircraft* pAircraft = (Aircraft*)vecShip[0]; // 할당된 메모리가 부모의 type으로 바뀌어서 들어와있는것 > 다형성.
Battleship* pBS = (Battleship*)vecShip[1]; // 여기까지 된다.
// 근데 잘못해서 형번환을 다른애들이랑 (숫자를 바꿔서) 해버려도 된다. 왜냐면 형번환은 졸라 강력해서 강제로 개통해버림.
// 할땐 마음대로였겠지만 발을 뱰 수 없다.
*/
// for문 안에 원래 auto pShip : vecShip 할 수 있음.
// for(unsigned int i=0; i<vecShip.size(); i++)
// {
// // 만약 얘가 cruiser이면 출력 -> 포인터만 가지고는 판단할 수 없다.
// // 나중에 이것을 식별하기 위해서 식별자를 가지게 된다.
// if(vecShip[i]->GetType() == CRUISER)
// {
// Cruiser* pCruiser = (Cruiser*)vecShip[i];
// }
// else if(vecShip[i]->GetType() == AIRCRAFT)
// {
// Aircraft* pAircraft = (Aircraft*)vecShip[i];
// }
// else if(vecShip[i]->GetType() == BATTLESHIP)
// {
// Battleship* pBattleship = (Battleship*)vecShip[i];
// }
// else if(vecShip[i]->GetType() == DESTROYER)
// {
// Destroyer* pDestroyer = (Destroyer*) vecShip[i];
// }
// }
m_Defender->SetupShips(vecShip);
}
void GameManager::Play()
{
// 모든 배가 파괴될때까지 attacker에게 getAttackPos 하게 한다.
// 모든 배가 파괴되면 attacker가 공격을 중지한다. while True에서 break를 한다.
int Destroy_number = 0; // DESTROY 됐을때 얘를 증가시키는 방향으로,
while(Destroy_number < 5) {
Position attack_to;
attack_to = m_Attacker->GetAttackPos();
HitResult defend_result;
defend_result = m_Defender->HitCheck(attack_to);
if(defend_result == 0){
cout << "미스." << endl;
}
else if(defend_result == 1){
cout << "배가 뭔가 맞았다." << endl;
}
else{
// 뭐가 맞았는지는 MAP에서 get data 해서 알 수 있음.
Destroy_number += 1;
cout << "파괴되었습니다." << endl;
}
}
cout << "게임이 끝났습니다." << endl;
}
Map* GameManager::Defendermap()
{
return m_Defender->getMap();
} | true |
96cd27033533ccdbd3453cc21a69446b263dcd9a | C++ | DanteRARA/STUST | /max and min.cpp | UTF-8 | 464 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
using namespace std;
int main(){
int size;
cin >> size;
for(int i = 0; i < size; i++){
float tmp, max, min;
for(int j = 0; j < 10; j++){
cin >> tmp;
if(j == 0) max = min = tmp;
if(tmp > max) max = tmp;
if(tmp < min) min = tmp;
}
cout << "maximum:" << setprecision(2) << fixed << max << endl;
cout << "minimum:" << setprecision(2) << fixed << min << endl;
}
return 0;
}
| true |
0f044c06d4cce3c62ab55f0eb2ff6dd6eed54fa4 | C++ | scanberg/particle-skinning | /src/Camera.h | UTF-8 | 444 | 2.734375 | 3 | [] | no_license | #pragma once
#include "Entity.h"
class Camera : public Entity
{
public:
Camera(float fov = 60.0f, float near = 0.1f, float far = 100.0f, float aspectRatio = 4.0/3.0);
void lookAt(const glm::vec3 & position);
glm::mat4 getViewMatrix();
glm::mat4 getInvViewMatrix();
glm::mat4 getProjMatrix();
glm::mat4 getInvProjMatrix();
private:
glm::mat4 m_projMatrix;
float m_fov;
float m_near;
float m_far;
float m_aspectRatio;
}; | true |
06baaaac80cb19ad8bbf9a6fe9ee470d229de456 | C++ | shifuxiang/NvrControl | /NvrControl/NvrControl/Server/C_FileCopyProtocolServer.h | GB18030 | 2,137 | 2.59375 | 3 | [] | no_license | /****************************************************************************
*@file: C_FileCopyProtocolServer.h
*@brief: AQ33_CSԵȷļͨЭʵ
*
*@author: zhangchao@oristartech.com
*@dade: 2015-11-12
****************************************************************************/
#ifndef C_FILECOPYPROTOCOLSERVER_H
#define C_FILECOPYPROTOCOLSERVER_H
#include <string>
#include <map>
#include "C_ITcpSserver.h"
#include "C_RecvDataObserverImp.h"
#include "ConstDef.h"
#include "C_WriteDataThread.h"
namespace FileCopyProtocol
{
class CFileCopyProtocolServer
{
public:
CFileCopyProtocolServer();
~CFileCopyProtocolServer();
public:
void SetServerPort(const unsigned short& port );
void SetLogPath(const std::string& path );
bool Start();
bool Close();
public:
void Process(const NetData& data );
private:
void Init();
/**
*briefڶԵȻϴļ
*/
void CreateFile(const NetData& data );
/**
*briefļ
*/
void TransferFile(const NetData& data );
/**
*briefļɹرļ
*/
void TransferFileFinish(const NetData& data );
/**
*briefļʱɾ·
*/
void RemoveDirectoryAll(const NetData& data );
/**
*briefɾĿ¼µļ
*/
void RemoveDirectory(const NetData& data );
/**
*briefĿ¼ĿĿ¼ٴ
*/
void CreateDirectoryNotRm(const NetData& data );
/**
*briefĿ¼,ɾٴ
*/
void CreateDirectoryRm(const NetData& data );
/**
*briefĿ¼Ȩ
*/
void ChangeDirectoryOwn(const NetData& data );
/**
*briefĽ
*/
void RecToClient(const unsigned int& typeNo, const Errorno& erno );
private:
ICTcpServer *m_pTcpServer;
CRecvDataObserverImp *m_pRecvDataObserver;
unsigned short m_serverPort;
std::string m_curpath;//ǰļ·
std::map<int, std::string> m_errNoErrMsgMap;
std::string m_LogPath;//־ļļ
CWriteDataThread *m_pWriteThread;
};
}
#endif // C_FILECOPYPROTOCOLSERVER_H
| true |
e91940e91a66c31cbdc860aca623e81e737eafd0 | C++ | iamsourav37/C_plus_plus_program_practice | /intemediate/question_2.cpp | UTF-8 | 404 | 3.953125 | 4 | [] | no_license | // C++ Program to Reverse a Number
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter any number : ";
cin >> number;
int reverseNumber = 0;
while (number != 0)
{
int rem = number % 10;
number /= 10;
reverseNumber = (reverseNumber * 10) + rem;
}
cout << "Reverse number is : " << reverseNumber;
return 0;
} | true |
4829677e367b168e534c2e32e1cbc4425feac862 | C++ | mdegirolami/sing | /test/tests_results/siege.cpp | UTF-8 | 1,094 | 3.3125 | 3 | [
"BSD-3-Clause"
] | permissive | #include "siege.h"
static uint32_t uint32_sqrt(uint32_t x);
void print_primes_to(int32_t top)
{
std::vector<int32_t> primes;
// note: for all the numbers in the range excluing even numbers
for(int32_t totry = 3, totry__top = top; totry < totry__top; totry += 2) {
const int32_t max_val = (int32_t)uint32_sqrt((uint32_t)totry); // max divisor who need to check
bool isprime = true;
for(auto &value : primes) {
if (value > max_val) {
break;
}
if (totry % value == 0) {
isprime = false;
break;
}
}
if (isprime) {
primes.push_back(totry);
}
}
}
// bisection
static uint32_t uint32_sqrt(uint32_t x)
{
uint32_t res = (uint32_t)0;
uint32_t add = (uint32_t)0x8000;
for(int32_t ii = 0; ii < 16; ++ii) {
const uint32_t temp = res | add;
if (x >= temp * temp) {
res = temp;
}
add >>= (uint32_t)1;
}
return (res);
}
| true |
edff87bbd5dbcc8c945e1537fc2fac56e98dac82 | C++ | ShahJabeen/Exception-handling | /sajs2720/TextBox.cc | UTF-8 | 1,337 | 3.5625 | 4 | [] | no_license | //
// CS 2720 Assignment 1 Solution
//
/// \author Howard Cheng
/// \date Sep 13, 2017
///
///
/// The TextBox class is an abstraction of a rectangular box containing
/// a text string that can be drawn on a Screen.
///
#include "TextBox.h"
// constructs a TextBox
//
// \param[in] row the row of the first character
// \param[in] column the column of the first character
// \param[in] ch the drawing character for the box
// \param[in] str the string
TextBox::TextBox(int row, int column, char ch, const string &str)
: Text{row, column, str},
Box{row-1, column-1,
row+1, column+static_cast<int>(str.length()), ch}
{
}
// draws the TextBox on the given Screen
//
// \param[in,out] screen the screen to draw in
void TextBox::draw(Screen &screen)
{
Text::draw(screen);
Box::draw(screen);
}
// reads a description of the TextBox from input stream. The row
// and column of the first character, the drawing character of the
// box, as well as the string are specified on one line of input
// separated by spaces.
//
// \param[in,out] is the input stream to read from
void TextBox::read(istream &is)
{
char ch;
is >> m_row >> m_col >> ch >> m_text;
while (is.peek() != '\n') {
// eats until the end of line
is.ignore(1);
}
is.ignore();
constructLines(m_row-1, m_col-1, m_row+1, m_col + m_text.length(), ch);
}
| true |
62cf77b108981cfb795bc28994a77b13fa22a25a | C++ | sagarmohanty2k00/DSA-450 | /recursion/TOH.cpp | UTF-8 | 633 | 3.546875 | 4 | [] | no_license | // Tower of Hanoi - Recursive solution
// By Sagar Mohanty
#include <bits/stdc++.h>
using namespace std;
void solve(int n, string s, string h, string d, int* step){
if(n == 1){
*step += 1;
cout << "One plate moved from \"" << s << "\" to \"" << d << "\"\n";
return;
}
else{
solve(n-1, s, d, h, step);
solve(1, s, h, d, step);
solve(n-1, h, d, s, step);
}
}
int main(){
int n;
string s="source", h="helper", d="destination";
cin >> n;
int number_of_steps=0;
solve(n, s, h, d, &number_of_steps);
cout << "The total number of steps taken to move \"" << n << "\" number of plates is : " << number_of_steps << " .\n";
}
| true |
b1d5465f7432157103cd901fc097a64a29e1acab | C++ | jmellorcrummey/llvm-openmp-5 | /runtime/src/extractExternal.cpp | UTF-8 | 15,217 | 2.78125 | 3 | [
"MIT",
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LicenseRef-scancode-arm-llvm-sga",
"LicenseRef-scancode-generic-cla"
] | permissive | /*
* extractExternal.cpp
*/
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <fstream>
#include <iostream>
#include <map>
#include <set>
#include <stdlib.h>
#include <string>
#include <strstream>
/* Given a set of n object files h ('external' object files) and a set of m
object files o ('internal' object files),
1. Determines r, the subset of h that o depends on, directly or indirectly
2. Removes the files in h - r from the file system
3. For each external symbol defined in some file in r, rename it in r U o
by prefixing it with "__kmp_external_"
Usage:
hide.exe <n> <filenames for h> <filenames for o>
Thus, the prefixed symbols become hidden in the sense that they now have a
special prefix.
*/
using namespace std;
void stop(char *errorMsg) {
printf("%s\n", errorMsg);
exit(1);
}
// an entry in the symbol table of a .OBJ file
class Symbol {
public:
__int64 name;
unsigned value;
unsigned short sectionNum, type;
char storageClass, nAux;
};
class _rstream : public istrstream {
private:
const char *buf;
protected:
_rstream(pair<const char *, streamsize> p)
: istrstream(p.first, p.second), buf(p.first) {}
~_rstream() { delete[] buf; }
};
// A stream encapuslating the content of a file or the content of a string,
// overriding the >> operator to read various integer types in binary form,
// as well as a symbol table entry.
class rstream : public _rstream {
private:
template <class T> inline rstream &doRead(T &x) {
read((char *)&x, sizeof(T));
return *this;
}
static pair<const char *, streamsize> getBuf(const char *fileName) {
ifstream raw(fileName, ios::binary | ios::in);
if (!raw.is_open())
stop("rstream.getBuf: Error opening file");
raw.seekg(0, ios::end);
streampos fileSize = raw.tellg();
if (fileSize < 0)
stop("rstream.getBuf: Error reading file");
char *buf = new char[fileSize];
raw.seekg(0, ios::beg);
raw.read(buf, fileSize);
return pair<const char *, streamsize>(buf, fileSize);
}
public:
// construct from a string
rstream(const char *buf, streamsize size)
: _rstream(pair<const char *, streamsize>(buf, size)) {}
// construct from a file whole content is fully read once to initialize the
// content of this stream
rstream(const char *fileName) : _rstream(getBuf(fileName)) {}
rstream &operator>>(int &x) { return doRead(x); }
rstream &operator>>(unsigned &x) { return doRead(x); }
rstream &operator>>(short &x) { return doRead(x); }
rstream &operator>>(unsigned short &x) { return doRead(x); }
rstream &operator>>(Symbol &e) {
read((char *)&e, 18);
return *this;
}
};
// string table in a .OBJ file
class StringTable {
private:
map<string, unsigned> directory;
size_t length;
char *data;
// make <directory> from <length> bytes in <data>
void makeDirectory(void) {
unsigned i = 4;
while (i < length) {
string s = string(data + i);
directory.insert(make_pair(s, i));
i += s.size() + 1;
}
}
// initialize <length> and <data> with contents specified by the arguments
void init(const char *_data) {
unsigned _length = *(unsigned *)_data;
if (_length < sizeof(unsigned) || _length != *(unsigned *)_data)
stop("StringTable.init: Invalid symbol table");
if (_data[_length - 1]) {
// to prevent runaway strings, make sure the data ends with a zero
data = new char[length = _length + 1];
data[_length] = 0;
} else {
data = new char[length = _length];
}
*(unsigned *)data = length;
KMP_MEMCPY(data + sizeof(unsigned), _data + sizeof(unsigned),
length - sizeof(unsigned));
makeDirectory();
}
public:
StringTable(rstream &f) {
// Construct string table by reading from f.
streampos s;
unsigned strSize;
char *strData;
s = f.tellg();
f >> strSize;
if (strSize < sizeof(unsigned))
stop("StringTable: Invalid string table");
strData = new char[strSize];
*(unsigned *)strData = strSize;
// read the raw data into <strData>
f.read(strData + sizeof(unsigned), strSize - sizeof(unsigned));
s = f.tellg() - s;
if (s < strSize)
stop("StringTable: Unexpected EOF");
init(strData);
delete[] strData;
}
StringTable(const set<string> &strings) {
// Construct string table from given strings.
char *p;
set<string>::const_iterator it;
size_t s;
// count required size for data
for (length = sizeof(unsigned), it = strings.begin(); it != strings.end();
++it) {
size_t l = (*it).size();
if (l > (unsigned)0xFFFFFFFF)
stop("StringTable: String too long");
if (l > 8) {
length += l + 1;
if (length > (unsigned)0xFFFFFFFF)
stop("StringTable: Symbol table too long");
}
}
data = new char[length];
*(unsigned *)data = length;
// populate data and directory
for (p = data + sizeof(unsigned), it = strings.begin(); it != strings.end();
++it) {
const string &str = *it;
size_t l = str.size();
if (l > 8) {
directory.insert(make_pair(str, p - data));
KMP_MEMCPY(p, str.c_str(), l);
p[l] = 0;
p += l + 1;
}
}
}
~StringTable() { delete[] data; }
// Returns encoding for given string based on this string table. Error if
// string length is greater than 8 but string is not in the string table
// -- returns 0.
__int64 encode(const string &str) {
__int64 r;
if (str.size() <= 8) {
// encoded directly
((char *)&r)[7] = 0;
KMP_STRNCPY_S((char *)&r, sizeof(r), str.c_str(), 8);
return r;
} else {
// represented as index into table
map<string, unsigned>::const_iterator it = directory.find(str);
if (it == directory.end())
stop("StringTable::encode: String now found in string table");
((unsigned *)&r)[0] = 0;
((unsigned *)&r)[1] = (*it).second;
return r;
}
}
// Returns string represented by x based on this string table. Error if x
// references an invalid position in the table--returns the empty string.
string decode(__int64 x) const {
if (*(unsigned *)&x == 0) {
// represented as index into table
unsigned &p = ((unsigned *)&x)[1];
if (p >= length)
stop("StringTable::decode: Invalid string table lookup");
return string(data + p);
} else {
// encoded directly
char *p = (char *)&x;
int i;
for (i = 0; i < 8 && p[i]; ++i)
;
return string(p, i);
}
}
void write(ostream &os) { os.write(data, length); }
};
// for the named object file, determines the set of defined symbols and the set
// of undefined external symbols and writes them to <defined> and <undefined>
// respectively
void computeExternalSymbols(const char *fileName, set<string> *defined,
set<string> *undefined) {
streampos fileSize;
size_t strTabStart;
unsigned symTabStart, symNEntries;
rstream f(fileName);
f.seekg(0, ios::end);
fileSize = f.tellg();
f.seekg(8);
f >> symTabStart >> symNEntries;
// seek to the string table
f.seekg(strTabStart = symTabStart + 18 * (size_t)symNEntries);
if (f.eof()) {
printf("computeExternalSymbols: fileName='%s', fileSize = %lu, symTabStart "
"= %u, symNEntries = %u\n",
fileName, (unsigned long)fileSize, symTabStart, symNEntries);
stop("computeExternalSymbols: Unexpected EOF 1");
}
StringTable stringTable(f); // read the string table
if (f.tellg() != fileSize)
stop("computeExternalSymbols: Unexpected data after string table");
f.clear();
f.seekg(symTabStart); // seek to the symbol table
defined->clear();
undefined->clear();
for (int i = 0; i < symNEntries; ++i) {
// process each entry
Symbol e;
if (f.eof())
stop("computeExternalSymbols: Unexpected EOF 2");
f >> e;
if (f.fail())
stop("computeExternalSymbols: File read error");
if (e.nAux) { // auxiliary entry: skip
f.seekg(e.nAux * 18, ios::cur);
i += e.nAux;
}
// if symbol is extern and defined in the current file, insert it
if (e.storageClass == 2)
if (e.sectionNum)
defined->insert(stringTable.decode(e.name));
else
undefined->insert(stringTable.decode(e.name));
}
}
// For each occurrence of an external symbol in the object file named by
// by <fileName> that is a member of <hide>, renames it by prefixing
// with "__kmp_external_", writing back the file in-place
void hideSymbols(char *fileName, const set<string> &hide) {
static const string prefix("__kmp_external_");
set<string> strings; // set of all occurring symbols, appropriately prefixed
streampos fileSize;
size_t strTabStart;
unsigned symTabStart, symNEntries;
int i;
rstream in(fileName);
in.seekg(0, ios::end);
fileSize = in.tellg();
in.seekg(8);
in >> symTabStart >> symNEntries;
in.seekg(strTabStart = symTabStart + 18 * (size_t)symNEntries);
if (in.eof())
stop("hideSymbols: Unexpected EOF");
StringTable stringTableOld(in); // read original string table
if (in.tellg() != fileSize)
stop("hideSymbols: Unexpected data after string table");
// compute set of occurring strings with prefix added
for (i = 0; i < symNEntries; ++i) {
Symbol e;
in.seekg(symTabStart + i * 18);
if (in.eof())
stop("hideSymbols: Unexpected EOF");
in >> e;
if (in.fail())
stop("hideSymbols: File read error");
if (e.nAux)
i += e.nAux;
const string &s = stringTableOld.decode(e.name);
// if symbol is extern and found in <hide>, prefix and insert into strings,
// otherwise, just insert into strings without prefix
strings.insert(
(e.storageClass == 2 && hide.find(s) != hide.end()) ? prefix + s : s);
}
ofstream out(fileName, ios::trunc | ios::out | ios::binary);
if (!out.is_open())
stop("hideSymbols: Error opening output file");
// make new string table from string set
StringTable stringTableNew = StringTable(strings);
// copy input file to output file up to just before the symbol table
in.seekg(0);
char *buf = new char[symTabStart];
in.read(buf, symTabStart);
out.write(buf, symTabStart);
delete[] buf;
// copy input symbol table to output symbol table with name translation
for (i = 0; i < symNEntries; ++i) {
Symbol e;
in.seekg(symTabStart + i * 18);
if (in.eof())
stop("hideSymbols: Unexpected EOF");
in >> e;
if (in.fail())
stop("hideSymbols: File read error");
const string &s = stringTableOld.decode(e.name);
out.seekp(symTabStart + i * 18);
e.name = stringTableNew.encode(
(e.storageClass == 2 && hide.find(s) != hide.end()) ? prefix + s : s);
out.write((char *)&e, 18);
if (out.fail())
stop("hideSymbols: File write error");
if (e.nAux) {
// copy auxiliary symbol table entries
int nAux = e.nAux;
for (int j = 1; j <= nAux; ++j) {
in >> e;
out.seekp(symTabStart + (i + j) * 18);
out.write((char *)&e, 18);
}
i += nAux;
}
}
// output string table
stringTableNew.write(out);
}
// returns true iff <a> and <b> have no common element
template <class T> bool isDisjoint(const set<T> &a, const set<T> &b) {
set<T>::const_iterator ita, itb;
for (ita = a.begin(), itb = b.begin(); ita != a.end() && itb != b.end();) {
const T &ta = *ita, &tb = *itb;
if (ta < tb)
++ita;
else if (tb < ta)
++itb;
else
return false;
}
return true;
}
// PRE: <defined> and <undefined> are arrays with <nTotal> elements where
// <nTotal> >= <nExternal>. The first <nExternal> elements correspond to the
// external object files and the rest correspond to the internal object files.
// POST: file x is said to depend on file y if undefined[x] and defined[y] are
// not disjoint. Returns the transitive closure of the set of internal object
// files, as a set of file indexes, under the 'depends on' relation, minus the
// set of internal object files.
set<int> *findRequiredExternal(int nExternal, int nTotal, set<string> *defined,
set<string> *undefined) {
set<int> *required = new set<int>;
set<int> fresh[2];
int i, cur = 0;
bool changed;
for (i = nTotal - 1; i >= nExternal; --i)
fresh[cur].insert(i);
do {
changed = false;
for (set<int>::iterator it = fresh[cur].begin(); it != fresh[cur].end();
++it) {
set<string> &s = undefined[*it];
for (i = 0; i < nExternal; ++i) {
if (required->find(i) == required->end()) {
if (!isDisjoint(defined[i], s)) {
// found a new qualifying element
required->insert(i);
fresh[1 - cur].insert(i);
changed = true;
}
}
}
}
fresh[cur].clear();
cur = 1 - cur;
} while (changed);
return required;
}
int main(int argc, char **argv) {
int nExternal, nInternal, i;
set<string> *defined, *undefined;
set<int>::iterator it;
if (argc < 3)
stop("Please specify a positive integer followed by a list of object "
"filenames");
nExternal = atoi(argv[1]);
if (nExternal <= 0)
stop("Please specify a positive integer followed by a list of object "
"filenames");
if (nExternal + 2 > argc)
stop("Too few external objects");
nInternal = argc - nExternal - 2;
defined = new set<string>[argc - 2];
undefined = new set<string>[argc - 2];
// determine the set of defined and undefined external symbols
for (i = 2; i < argc; ++i)
computeExternalSymbols(argv[i], defined + i - 2, undefined + i - 2);
// determine the set of required external files
set<int> *requiredExternal =
findRequiredExternal(nExternal, argc - 2, defined, undefined);
set<string> hide;
// determine the set of symbols to hide--namely defined external symbols of
// the required external files
for (it = requiredExternal->begin(); it != requiredExternal->end(); ++it) {
int idx = *it;
set<string>::iterator it2;
// We have to insert one element at a time instead of inserting a range
// because the insert member function taking a range doesn't exist on
// Windows* OS, at least at the time of this writing.
for (it2 = defined[idx].begin(); it2 != defined[idx].end(); ++it2)
hide.insert(*it2);
}
// process the external files--removing those that are not required and hiding
// the appropriate symbols in the others
for (i = 0; i < nExternal; ++i)
if (requiredExternal->find(i) != requiredExternal->end())
hideSymbols(argv[2 + i], hide);
else
remove(argv[2 + i]);
// hide the appropriate symbols in the internal files
for (i = nExternal + 2; i < argc; ++i)
hideSymbols(argv[i], hide);
return 0;
}
| true |
22e01f056eb7f4cff0ff451e37fcbcc497a7197b | C++ | acadboostcpp/CPP- | /skillBoost/C++/binarySearch.cpp | UTF-8 | 598 | 3.984375 | 4 | [] | no_license | #include<iostream>
using namespace std;
int BinarySearch(int arr[], int size, int ele) {
int ans = -1;
int start = 0;
int end = size - 1;
while(start <= end) {
int mid = (start + end) / 2;
if(arr[mid] == ele) {
ans = mid;
break;
}
else if(arr[mid] > ele) {
end = mid - 1;
}
else {
start = mid + 1;
}
}
return ans;
}
int main() {
// 0 1 2 3 4 5 6 7
int arr[] = {12, 13, 14, 15, 16, 17, 89, 96};
int ele;
cout << "Enter the element to search: ";
cin >> ele;
int ans = BinarySearch(arr, 8, ele);
cout << "Element found at pos: " << ans << endl;
} | true |
6abbc32694420a532c3c31802d30bbbda6aae052 | C++ | OKullmann/oklibrary | /Satisfiability/Transformers/Generators/Ramsey.hpp | UTF-8 | 8,086 | 2.5625 | 3 | [] | no_license | // Oliver Kullmann, 26.7.2004 (Turin)
/* Copyright 2004 - 2007, 2009, 2010, 2012 Oliver Kullmann
This file is part of the OKlibrary. OKlibrary 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 and included in this library; either version 3 of the
License, or any later version. */
/*!
\file Satisfiability/Transformers/Generators/Ramsey.hpp
\brief Fundamental components for creating Ramsey instances
\deprecated Needs a complete update.
\details
Currently the code in here is rather outdated.
*/
#ifndef RAMSEY_hhfzqwk15183Gfzx
#define RAMSEY_hhfzqwk15183Gfzx
#include <stdexcept>
#include <cassert>
#include <string>
#include <ostream>
#include <vector>
#include <utility>
#include <algorithm>
#include <functional>
#include <cmath>
#include <sstream>
#include <boost/lexical_cast.hpp>
#include <OKlib/General/Combinatorics.hpp>
#include <OKlib/General/IteratorHandling.hpp>
#include <OKlib/General/Numerics.hpp>
namespace Ramsey {
/*!
\class Enumerate_hyperedges
\brief Computing the hypergraphs underlying Ramsey-instances
The procedural specification is given by ramsey_ohg(q,r,n) in
ComputerAlgebra/Hypergraphs/Lisp/Generators/Ramsey.mac.
That is, vertices are the r-subsets of {1, ..., n}, and for every
q-subset T of {1, ..., n} there is the hyperedge of r-subsets of T.
Precondition: n >= q >= r >= 0.
\todo See ComputerAlgebra/Hypergraphs/Lisp/Generators/plans/Ramsey.hpp
\todo Update the underlying notion of "hypergraph"
*/
template <typename Int = int>
class Enumerate_hyperedges {
public :
typedef Int size_type;
const size_type q; // size of monochromatic subset
const size_type r; // size of edges
const size_type n; // number of vertices in underlying graph
const size_type number_vertices_hypergraph;
const size_type size_hyperedges;
const size_type number_hyperedges;
typedef typename std::vector<size_type> edge_type; // const size of vectors = r
typedef typename std::vector<edge_type> hyperedge_type; // const size of vectors = size_hyperedges
hyperedge_type current_hyperedge;
private :
typedef std::vector<size_type> subset_type; // const size of vectors = q
subset_type current_subset;
public :
Enumerate_hyperedges
(const size_type q, const size_type r, const size_type n)
: q(q), r(r), n(n), number_vertices_hypergraph(compute_number_vertices_hypergraph()), size_hyperedges(compute_size_hyperedges()), number_hyperedges(compute_number_hyperedges()), current_hyperedge(size_hyperedges, edge_type(r)), current_subset(IteratorHandling::count_iterator(size_type()), IteratorHandling::count_iterator(q)) {
assert(current_hyperedge.size() == size_hyperedges);
update_current_hyperedge();
}
void next() {
if (Combinatorics::choose_next(n, q, current_subset.begin(), current_subset.end()) != Combinatorics::no_further_subsets)
update_current_hyperedge();
}
private :
void update_current_hyperedge() {
typedef std::vector<typename subset_type::size_type> index_subset_type;
index_subset_type s(IteratorHandling::count_iterator(size_type()), IteratorHandling::count_iterator(r));
for (typename hyperedge_type::iterator i = current_hyperedge.begin(); i != current_hyperedge.end(); ++i, Combinatorics::choose_next(q, r, s.begin(), s.end()))
for (typename edge_type::size_type j = 0; j != r; ++j) {
assert(i -> size() == r);
(*i)[j] = current_subset[s[j]];
}
}
size_type compute_number_vertices_hypergraph() const {
assert(n >= 0);
assert(r >= 0);
assert(n >= r);
return Combinatorics::binom(n,r); }
size_type compute_size_hyperedges() const {
assert(q >= r);
return Combinatorics::binom(q,r);
}
size_type compute_number_hyperedges() const {
assert(n >= q);
return Combinatorics::binom(n,q);
}
};
/*!
\class Ramsey_TwoColours_1
\brief Outputs a Ramsey SAT-instance for two colours and arbitrary
hyperedge size
For the diagonal case (q1=q2=q) this corresponds to
output_ramsey2_stdname(q,r,N) in
ComputerAlgebra/Satisfiability/Lisp/Generators/RamseyTheory/RamseyProblems.mac.
\todo Use components from module InputOutput.
*/
template <typename Int = unsigned int>
class Ramsey_TwoColours_1 {
typedef Enumerate_hyperedges<Int> enumeration_type;
public :
typedef typename enumeration_type::size_type size_type;
const size_type q1, q2;
const size_type r;
const size_type N;
private :
std::ostream& out;
enumeration_type H1, H2;
public :
const size_type number_vertices_hypergraph;
const size_type size_hyperedges1, size_hyperedges2;
const size_type number_hyperedges1, number_hyperedges2;
const size_type n;
const size_type c;
Ramsey_TwoColours_1
(const size_type q1, const size_type q2, const size_type r, const size_type N, std::ostream& out) :
q1(q1), q2(q2), r(r), N(N), out(out), H1(q1, r, N), H2(q2, r, N), number_vertices_hypergraph(H1.number_vertices_hypergraph), size_hyperedges1(H1.size_hyperedges), size_hyperedges2(H2.size_hyperedges), number_hyperedges1(H1.number_hyperedges), number_hyperedges2(H2.number_hyperedges), n(number_vertices_hypergraph), c(number_hyperedges1 + number_hyperedges2) {
assert(H1.number_vertices_hypergraph == H2.number_vertices_hypergraph);
}
void operator() () {
comment();
clauses();
}
virtual ~Ramsey_TwoColours_1() {}
private :
void virtual comment() const {
out << "c Ramsey numbers with partitioning into s = 2 parts; generator written by Oliver Kullmann, Swansea, July 2004\n";
out << "c Size of first monochromatic set q_1 = " << boost::lexical_cast<std::string>(q1) << "\n";
out << "c Size of second monochromatic set q_2 = " << boost::lexical_cast<std::string>(q2) << "\n";
out << "c Hyperedge size r = " << boost::lexical_cast<std::string>(r) << "\n";
out << "c Number of vertices N = " << boost::lexical_cast<std::string>(N) << "\n";
out << "c (The clause-set is satisfiable iff the hyperedges of the complete hypergraph K_N^r (N vertices, every hyperedge has size r) can be labelled red or blue such that neither there is a red set of q_1 many vertices nor a blue set of q_2 many vertices, where a set of vertices is called \"red\" respectively \"blue\" iff all hyperedges consisting only of vertices out of this set are marked red respectively blue. For all fixed q1, q2, r there exists a natural number N_0, such that for all N >= N_0 the clause-sets with parameters q_1, q_2, r and N are unsatisfiable; the smallest such N_0 is the Ramsey-number N(q_1, q_2, r).)\n";
out << "p cnf " << boost::lexical_cast<std::string>(n) << " " << boost::lexical_cast<std::string>(c) << "\n";
}
void clauses() {
if (c == 0) return;
// excluding "red"
for (size_type i = 0; i < number_hyperedges1; ++i, H1.next()) {
for (typename hyperedge_type::const_iterator j = H1.current_hyperedge.begin(); j != H1.current_hyperedge.end(); ++j)
out << " " << var(*j);
out << eoc();
}
// excluding "blue"
for (size_type i = 0; i < number_hyperedges2; ++i, H2.next()) {
for (typename hyperedge_type::const_iterator j = H2.current_hyperedge.begin(); j != H2.current_hyperedge.end(); ++j)
out << " " << neg(var(*j));
out << eoc();
}
}
protected :
typedef typename enumeration_type::hyperedge_type hyperedge_type;
typedef typename enumeration_type::edge_type edge_type;
std::string var(const edge_type& v) const {
assert(v.size() == r);
std::stringstream s("V");
typename edge_type::const_iterator i = v.begin();
s << *(i++) + 1;
for (; i != v.end(); ++i)
s << "S" << *i + 1;
return s.str();
}
virtual std::string neg(const std::string& var) const {
return "-" + var;
}
virtual std::string eoc() const {
return " 0\n";
}
};
}
#endif
| true |
98ba7247af05591a5a436a822f506d58f72822f7 | C++ | LaurentStar/SFNV-Game-Testing | /Joker.h | UTF-8 | 709 | 2.65625 | 3 | [] | no_license | #ifndef JOKER_H_INCLUDED
#define JOKER_H_INCLUDED
//#include "Character.h"
class Joker
{
//The king is not the joker's friend. Joker accesses nothing!
friend class King;
private:
/* ALL DATA CURRENTLY NEEDED FROM THE CHARACTER CLASS.
*Character_state
* X Y Z Coords
*/
float x_coord, y_coord, z_coord;
int character_state_of_being;
int character_collision_sides, character_collision_fronts, character_collision_tops;
Square character_base;
Square character_cornice;
public:
Joker();
//Defining
// void Character_variable_definer(Character &data);
//Giving to the king
// void King_Character_variable_giving(King &data);
};
#endif | true |
7bc182aa780cd60ff18c6ba11adcf8f805544701 | C++ | rvillegasm/iot-mock-app | /src/main.cpp | UTF-8 | 153 | 2.78125 | 3 | [] | no_license | #include <iostream>
#include "Calculator.hpp"
int main() {
std::cout << "The cube of 5 is " << Calculator::cube(5.0f) << std::endl;
return 0;
} | true |
b431f38cb0d158b7d551aca64ae72292af37da16 | C++ | cqw5/Algorithms_CPP | /Algorithms/divede_and_conquer_method/minmax_recursive.cpp | UTF-8 | 2,713 | 4.0625 | 4 | [] | no_license | /*! Author: qwchen
*! Date : 2016-10-20
*
* 求一组数中的最大值和最小值(递归解法)
* 思路:用递归的分治算法可以求解
*/
#include <iostream>
#include <vector>
using namespace std;
/*
* 递归函数
* Parament:
* a: 待查找的数组
* low: 第一个元素
* high: 最后一个元素的下一个位置
* indexOfMin: 最小元素的索引
* indexOfMax: 最大元素的索引
* return:
* 通过形参数传引用的方式返回indexOfMin和indexOfMax
*/
template <class T>
void findMinmax(vector<T> a, int low, int high, int &indexOfMin, int &indexOfMax) {
if (high - low == 1){ // 递归终止条件:只有一个元素时,该元素既为最小又为最大
indexOfMin = low;
indexOfMax = low;
return;
}
if (high - low == 2){ // 递归终止条件:有两个元素时,一个是最大,另一个是最小
if (a[low] < a[high - 1]){
indexOfMin = low;
indexOfMax = high - 1;
} else {
indexOfMin = high - 1;
indexOfMax = low;
}
return;
}
// 父节点的最大元素是左子树和右子树中最大元素的大者,最小元素为左子树和右子树中最小元素的小者
int mid = (low + high) / 2;
int indexOfLeftMin = low, indexOfLeftMax = low;
int indexOfRightMin = mid, indexOfRightMax = mid;
findMinmax(a, low, mid, indexOfLeftMin, indexOfLeftMax);
findMinmax(a, mid, high, indexOfRightMin, indexOfRightMax);
indexOfMin = a[indexOfLeftMin] <= a[indexOfRightMin]? indexOfLeftMin : indexOfRightMin;
indexOfMax = a[indexOfLeftMax] >= a[indexOfRightMax]? indexOfLeftMax : indexOfRightMax;
}
/*
* Parament:
* a: 待查找的数组
* n: 数组元素的个数(即最后一个元素的下一个位置)
* indexOfMin: 最小元素的索引
* indexOfMax: 最大元素的索引
* return:
* 通过形参传引用的方式返回indexOfMin和indexOfMax
*/
template <class T>
bool minmax(vector<T> a, int n, int &indexOfMin, int &indexOfMax) {
if (n < 1){ // 如果数组为空,返回false
return false;
}
findMinmax(a, 0, n, indexOfMin, indexOfMax);
return true;
}
testMinmax(){
// index 0 1 2 3 4 5 6 7 8 9 10 11
vector<int> a = {9, 2, 4, 6, 2, 1, 7, 5, 9, 10, 3, 3};
vector<int> b;
int min = 0;
int max = 0;
if(minmax(a, a.size(), min, max)) {
cout << "min = " << a[min] << " it's index = " << min << endl;
cout << "max = " << a[max] << " it's index = " << max << endl;
} else {
cout << "Error" << endl;
}
}
int main(){
testMinmax();
return 0;
}
| true |
54f25e4d6d585d4ebe1a6b45704b42d734e958ad | C++ | hgorjiara/ComputerNetworks | /validator.cpp | UTF-8 | 21,809 | 2.6875 | 3 | [] | no_license | #include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <time.h>
#include <errno.h>
#include "utilities.h"
#include "cryptogram.h"
/*{
return 0;
}
int process_server_comm(vector<string> tokens, int num_of_tokens, char res[MAX_STR_SIZE], char* dirnm)
{
return 0;
}
int process_command(char command[MAX_STR_SIZE], char res[MAX_STR_SIZE], char* dirnm)
{
int num_of_tokens;
//char tokens[MAX_ARRAY_SIZE][MAX_STR_SIZE];
vector<string> tokens = mytokenizer(command, " \n");
cerr<<tokens[0]<<" DD voter/server DD"<<endl;
//if(num_of_tokens < 0)
//return -1;
if(tokens[0] == "server"){
cerr<<"FAHMIDE SERVER E"<<endl;
return process_server_comm(tokens, num_of_tokens, res, dirnm);
}
else if(tokens[0] == "voter"){
cerr<<"fahmide vvvvvoter e"<<endl;
return process_voter_comm(tokens, num_of_tokens, res, dirnm);
}
return -1;
}*/
/*int process_command(char command[MAX_STR_SIZE], char res[MAX_STR_SIZE], char* dirnm)
{
return 0;
}*/
int main(int argn, char** args)
{
if(argn < 2){
cout<<"Valid format is :\n./validator port_number"<<endl;
return 0;
}
int port_number = atoi(args[1]);
//save_ca_port(args[1].c_str());
if(found_in(args[1], read_available_ca_ports()) < 0)
{
int fd_to_save_port = open("./DB/validators.txt", O_APPEND | O_RDWR);
cerr<<"args[1] is: "<<args[1]<< " in " <<strlen(args[1])<<endl;
int dumm = write(fd_to_save_port, args[1], strlen(args[1]));
dumm = write(fd_to_save_port, "\n", strlen("\n"));
if(dumm <0)
write(STDOUTFD, "Error while writing port\n", sizeof("Error while writing port\n"));
close(fd_to_save_port);
}
const int num_of_connection = 5;
// make directories
char directory_name[] = "DB";
int mkdir_status = create_directories(directory_name);
if(mkdir_status != 0){
cout<<"Error while creating directory"<<endl;
return 0;
}
cout<<"Directory created"<<endl;
//creating socket
int server_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(port_number);
struct sockaddr_in client_addr;
//binding
int binding_st = bind(server_fd,(struct sockaddr*) &server_addr, sizeof(server_addr));
if(binding_st == -1)
{
write(STDOUTFD, "binding error\n", sizeof("binding error\n"));
return -1;
//exit
}
else
write(STDOUTFD, "binding successful\n", sizeof("binding successful\n"));
//listenning
int listening_st = listen(server_fd, num_of_connection);
if(listening_st == -1)
write(STDOUTFD, "listening error\n", sizeof("listening error"));
else
write(STDOUTFD, "listening successful\n", sizeof("listening successful"));
fd_set read_fdset, temp_fdset;
struct timeval tv;
int ret_val;
int new_sock_fd, it_fd;
/* Watch stdin (fd 0) to see when it has input. */
FD_ZERO(&read_fdset);
FD_SET(server_fd, &read_fdset);
FD_SET(STDINFD, &read_fdset);
char publicPath[MAX_STR_SIZE];
clear_buff(publicPath,MAX_STR_SIZE);
char privatePath[MAX_STR_SIZE];
clear_buff(privatePath,MAX_STR_SIZE);
strcat( publicPath,"./DB/");
strcat( privatePath,"./DB/");
struct stat st;
if (stat(publicPath, &st) == -1) {
mkdir(publicPath, 0700);
}
strcat( publicPath,"publicCA");
strcat( privatePath,"privateCA");
if( !create_RSA_key(publicPath,privatePath)) {
cout<<"error in creating key" << endl;
}else{
cout << "key create successfully! " << endl;
}
/* Wait up to five seconds. */
tv.tv_sec = 10 * 60;
tv.tv_usec = 0;
unsigned int size_of_client_addr = sizeof(client_addr);
int status;
while(1)
{
memcpy(&temp_fdset, &read_fdset, sizeof(temp_fdset));
status = select(FD_SETSIZE, &temp_fdset, (fd_set *)0, (fd_set *)0, (struct timeval*) &tv);
if(status < 1)
{
write(STDOUTFD, "Select Error\n", sizeof("Select error\n"));
break;
}
for(it_fd = 0; it_fd<FD_SETSIZE; it_fd++)
{
if(FD_ISSET(it_fd, &temp_fdset))
{
if(it_fd == STDINFD)
{
char buff_read [MAX_STR_SIZE], response_buff[MAX_STR_SIZE];
clear_buff(buff_read, MAX_STR_SIZE);
clear_buff(response_buff, MAX_STR_SIZE);
read(it_fd, buff_read, MAX_STR_SIZE-1);
//process_server_command(buff_read, response_buff, directory_name);
write(STDOUTFD, buff_read, MAX_STR_SIZE);
write(STDOUTFD, "OK", strlen("OK"));
}
if(it_fd == server_fd)
{
new_sock_fd = accept(server_fd, NULL, NULL);
if(new_sock_fd < 0)
{
write(STDOUTFD,"Error on accepting\n", sizeof("Error on accepting\n"));
break;
}
else write(STDOUTFD,"accepting successful\n", sizeof("accepting successful\n"));
FD_SET(new_sock_fd, &read_fdset);
}
else
{
int n, m;
char buff_read [MAX_STR_SIZE], response_buff[MAX_STR_SIZE];
clear_buff(buff_read, MAX_STR_SIZE);
clear_buff(response_buff, MAX_STR_SIZE);
n = read(it_fd, buff_read, MAX_STR_SIZE-1);
if(n == 0)
{
close(it_fd);
FD_CLR(it_fd, &read_fdset);
write(STDOUTFD, "Removing One Client_fd\n", sizeof("Removing One Client_fd\n"));
}
else if(n < 0)
{
write(STDOUTFD, "Error on reading\n", sizeof("Error on reading\n"));
}
//after reading successfully
else
{
if(buff_read != "DC")
{
if( strncmp (buff_read,"Register",8)==0 ){
// char publicPath[MAX_STR_SIZE];
// clear_buff(publicPath,MAX_STR_SIZE);
// strcat( publicPath,"./DB/");
// struct stat st;
// if (stat(publicPath, &st) == -1) {
// mkdir(publicPath, 0700);
// }
// strcat( publicPath,"certificate/");
// if (stat(publicPath, &st) == -1) {
// mkdir(publicPath, 0700);
// }
vector<string> rcommand = mytokenizer(buff_read," ");
////open file
string s = "./DB/certificate/"+ rcommand[1];
int fd_c = creat(s.c_str(),O_RDWR| O_APPEND);
if(fd_c > 0){
chmod(s.c_str(),S_IRUSR | S_IWUSR);
}
close(fd_c);
show_encrypted_massage(publicPath,rcommand);
if( create_certificate(privatePath,rcommand[2],rcommand[1]))
{
int s = write(it_fd, "certificate created successfully\n", strlen("certificate created successfully\n"));
if(s < 0) write(STDOUTFD, "Error on writing\n", sizeof("Error on writing\n"));
}else{
int s = write(it_fd, "error in creating certificate\n", strlen("error in creating certificate\n"));
if(s < 0) write(STDOUTFD, "Error on writing\n", sizeof("Error on writing\n"));
}
//open file
// for(int i=0; i< rcommand.size(); i++)
// cerr << rcommand[i] << ' ';
// cerr << endl;
//open file
}
int s = write(it_fd, "OK\n", strlen("OK\n"));
if(s < 0) write(STDOUTFD, "Error on writing\n", sizeof("Error on writing\n"));
}
else //if(buff_read == "DC")
{
cerr<<"varede dasture DC DC DC shode"<<endl;
write(it_fd, "Disconnecting in Progress ...\n",
sizeof("Disconnecting in Progress ...\n"));
close(it_fd);
FD_CLR(it_fd, &read_fdset);
write(STDOUTFD, "Removing One Client_fd\n", sizeof("Removing One Client_fd\n"));
}
}
}
}
}
}
close(server_fd);
return 0;
}
/*
void set_compn_data(char* path_name, company* this_company)
{
int op_fd = open(path_name, O_RDWR | O_APPEND);
if(op_fd < 0) write(STDOUTFD, "Error In Opening File to Read Data!\n", sizeof("Error In Opening File to Read Data!\n"));
int path_tkn_num;
//char path_tkns[MAX_ARRAY_SIZE][MAX_STR_SIZE];
vector<string> pathtkns = mytokenizer(path_name, "./ \n");
strcpy(this_company->name, path_tkns[path_tkn_num - 2]);
char read_buff[MAX_STR_SIZE];
clear_buff(read_buff, MAX_STR_SIZE);
int rd_st = read(op_fd, read_buff, MAX_STR_SIZE-1);
if(rd_st > 0)
{
int tkn_num;
char tkns[MAX_ARRAY_SIZE][MAX_STR_SIZE];
tokenizer(read_buff, " \n", &tkn_num, tkns);
char tmp_stcknum[MAX_ARRAY_SIZE];
clear_buff(tmp_stcknum, MAX_ARRAY_SIZE);
strcpy(tmp_stcknum, tkns[3]);
this_company->stocks_number = atoi(tmp_stcknum);//set number of company's stocks
clear_buff(tmp_stcknum, MAX_ARRAY_SIZE);
strncpy(tmp_stcknum, tkns[6], strlength(tkns[6])-1);
this_company->price_of_stock = atoi(tmp_stcknum);//set price of each stock
this_company->budget = (this_company->stocks_number)*(this_company->price_of_stock);
int i = 7;
this_company->invstr_num = 0;
while(i<tkn_num && strlength(tkns[i])!=0)
{
strcpy(this_company->investors[(i-7)/6], tkns[i]);
i++; i++;//passing bought
this_company->investors_stocks_num[(i-7)/6] = atoi(tkns[i]);
i++; i++; i++;//passing stocks on
strcpy(this_company->investing_date[(i-7)/6], tkns[i]);
i++;
this_company->invstr_num++;
}
}
close(op_fd);
}*/
/*void record_company_data(char path_name[], company this_company)
{
int file_fd = open(path_name, O_RDWR);
if(file_fd < 0) write(STDOUTFD, "Error In Opening File to Write!\n", sizeof("Error In Opening File to Write!\n"));
int w_st = write(file_fd, "Main stocks Num ", sizeof("Main stocks Num "));
char strtmp[20];
clear_buff(strtmp, 20);
int_to_str(this_company.stocks_number, strtmp, 10);
write(file_fd, strtmp, strlength(strtmp));
write(file_fd, "\n", sizeof("\n"));
write(file_fd, "stocks Price ", sizeof("stocks Price "));
clear_buff(strtmp, 20);
int_to_str(this_company.price_of_stock, strtmp, 10);
write(file_fd, strtmp, strlength(strtmp));
write(file_fd, "$\n", sizeof("$\n"));
int i;
for(i=0; i<this_company.invstr_num; i++)
{
write(file_fd, this_company.investors[i], strlength(this_company.investors[i]));//investor name
write(file_fd, " bought ", sizeof(" bought "));
clear_buff(strtmp, 20);
int_to_str(this_company.investors_stocks_num[i], strtmp, 10);
write(file_fd, strtmp, strlength(strtmp));//number of stocks
write(file_fd, " stocks on ", sizeof(" stocks on "));
write(file_fd, this_company.investing_date[i], strlength(this_company.investing_date[i]));//date
write(file_fd, "\n", sizeof("\n"));
}
close(file_fd);
}*/
/* client* this_customer, char res[MAX_STR_SIZE], char* path_name)
{
clear_buff(res, MAX_STR_SIZE);
if(num_of_tokens >= 6 && mystrcmp(tokens[2], "Introduction") == 0 && mystrcmp(tokens[3], "Customer") == 0)
{
int cr_fd = creat(path_name, O_RDWR | O_APPEND);
if(cr_fd > 0)
{
chmod(path_name,S_IRUSR | S_IWUSR);
char w_buff[MAX_STR_SIZE];
clear_buff(w_buff, MAX_STR_SIZE);
strcpy(w_buff , "Main budget ");
strcat(w_buff, tokens[5]);
strcat(w_buff, "$\n");
int w_st = write(cr_fd, w_buff, strlength(w_buff));
if(w_st < 0)
{
write(STDOUTFD, "Error in Writing File!\n", sizeof("Error in Writing File!\n"));
return -1;
}
strcpy(res, "You Registered Successfully!\n");
}
else
return -1;
close(cr_fd);
}
else if( num_of_tokens >= 5 && mystrcmp(tokens[2], "Get") == 0 &&
mystrcmp(tokens[3], "Stocks") == 0 && mystrcmp(tokens[4], "List") == 0)
{
int file_num;
char file_names[MAX_ARRAY_SIZE][MAX_STR_SIZE];
char sources_path[MAX_STR_SIZE];
clear_buff(sources_path, MAX_STR_SIZE);
char old_path_tokens[MAX_ARRAY_SIZE][MAX_STR_SIZE];
int old_path_tokens_num;
tokenizer(path_name, "/", &old_path_tokens_num, old_path_tokens);
strcpy(sources_path, old_path_tokens[0]);
strcat(sources_path, "/Company/");
print(sources_path);
//list_files(sources_path, file_names, &file_num);
char date_p[30];
clear_buff(date_p, 30);
get_date(date_p);
strcpy(res, "------------Stocks List-------------\nTime:");
strcat(res, date_p);
strcat(res, "\nCompany---StocksNum-Price\n");
int fd, nread;
char buf[MAX_STR_SIZE];
struct linux_dirent *d;
int bpos;
char d_type;
fd = open(sources_path, O_RDONLY | O_DIRECTORY);
while(1)
{
nread = syscall(SYS_getdents, fd, buf, MAX_STR_SIZE);
if (nread == 0){
break;
}
for (bpos = 0; bpos < nread;)
{
d = (struct linux_dirent *) (buf + bpos);
print(d->d_name);
print("\n");
if(mystrcmp(d->d_name, ".") != 0 && mystrcmp(d->d_name, "..")){
company this_cmp;
char cmp_path[MAX_STR_SIZE];
clear_buff(cmp_path, MAX_STR_SIZE);
strcpy(cmp_path, sources_path);
strcat(cmp_path, d->d_name);
set_compn_data(cmp_path, &this_cmp);
strcat(res, this_cmp.name);
strcat(res, "\t");
char stcks [MAX_STR_SIZE];
int_to_str(this_cmp.stocks_number, stcks, 10);
strcat(res, stcks);
strcat(res, "\t");
int_to_str(this_cmp.price_of_stock, stcks, 10);
strcat(res, stcks);
strcat(res, "\n");
}
bpos += d->d_reclen;
}
break;
}
}
else if(num_of_tokens >= 5 && mystrcmp(tokens[2], "Buy") == 0 && this_customer != NULL)
{
return 1;
}
else if(num_of_tokens >= 4 && mystrcmp(tokens[2], "Get") == 0 && mystrcmp(tokens[3], "Status") == 0
&& this_customer != NULL)
{
char date_p[30];
clear_buff(date_p, 30);
get_date(date_p);
strcpy(res, "---------status---------\nTime : ");
strcat(res, date_p);
strcat(res, "\n");
strcat(res, "Budget : ");
char budget_str[20];
clear_buff(budget_str, 20);
int_to_str(this_customer->budget, budget_str, 10);
strcat(res, budget_str);
strcat(res, "$\n");
strcat(res, "Company---Stocks Num\n");
int i;
for(i = 0; i < this_customer -> invstd_num; i++){
strcat(res, this_customer -> invested[i]);
strcat(res, " ");
char tmp[20];
clear_buff(tmp, 20);
int_to_str(this_customer -> invested_stocks_num[i], tmp, 10);
strcat(res, tmp);
strcat(res, " stocks on ");
strcat(res, this_customer -> invested_date[i]);
strcat(res, "\n");
}
strcat(res, "\0");
}
else if(num_of_tokens >= 3 && mystrcmp(tokens[2], "Unregister") == 0 && this_customer != NULL)
{
unlink(path_name);
strcpy(res, "You Are Unregistered!\n");
}
else if(num_of_tokens >= 3 && mystrcmp(tokens[2], "DC") == 0)
{
}
else
return -1;
return 0;
}*/
/*int record_customer_data(char path_name[], client this_customer)
{
int file_fd = open(path_name, O_RDWR);
if(file_fd < 0) write(STDOUTFD, "Error In Opening File to Write!\n", sizeof("Error In Opening File to Write!\n"));
int w_st = write(file_fd, "Main budget ", sizeof("Main budget "));
char strtmp[20];
clear_buff(strtmp, 20);
int_to_str(this_customer.budget, strtmp, 10);
write(file_fd, strtmp, strlength(strtmp));
write(file_fd, "$\n", sizeof("$\n"));
int i;
for(i=0; i<this_customer.invstd_num; i++)
{
write(file_fd, this_customer.invested[i], strlength(this_customer.invested[i]));//company name
write(file_fd, " ", sizeof(" "));
clear_buff(strtmp, 20);
int_to_str(this_customer.invested_stocks_num[i], strtmp,10);
write(file_fd, strtmp, strlength(strtmp));//number of stocks
write(file_fd, this_customer.invested_date[i], strlength(this_customer.invested_date[i]));//date
write(file_fd, "\nbudget ", sizeof("\nbudget "));
clear_buff(strtmp, 20);
int_to_str(this_customer.remained_budget[i], strtmp, 10);
write(file_fd, strtmp, strlength(strtmp));//remained budget after buying above stocks
write(file_fd, "$\n", sizeof("$\n"));
}
close(file_fd);
return 0;
}*/
/*int process_customer_comm(char tokens[MAX_ARRAY_SIZE][MAX_STR_SIZE], int num_of_tokens, char res[MAX_STR_SIZE], char* dirnm){
client this_customer;
strcpy(this_customer.name, tokens[1]);
char path_name[MAX_STR_SIZE];
clear_buff(path_name, MAX_STR_SIZE);
strcpy(path_name, dirnm);
strcat(path_name, "/Customer/");
strcat(path_name, tokens[1]);
strcat(path_name, ".txt");
int file_fd = open(path_name, O_RDWR | O_APPEND);
if(file_fd < 0)
{
return (customer_response(tokens, num_of_tokens, NULL , res, path_name));
}
else
{
char read_buff[MAX_STR_SIZE];
clear_buff(read_buff, MAX_STR_SIZE);
int r_st = read(file_fd, read_buff, MAX_STR_SIZE-1);
//tokenize read_file_lines
if(r_st > 0)
{
int tkn_num;
char tkns[MAX_ARRAY_SIZE][MAX_STR_SIZE];
tokenizer(read_buff, " \n", &tkn_num, tkns);
char tmp_budget[MAX_ARRAY_SIZE];
clear_buff(tmp_budget, MAX_ARRAY_SIZE);
strncpy(tmp_budget, tkns[2], strlength(tkns[2])-1);
this_customer.budget = atoi(tmp_budget);
int i = 3;
this_customer.invstd_num = 0;
while(i < tkn_num && strlength(tkns[i]) != 0)
{
strcpy(this_customer.invested[(i-3)/7], tkns[i]);//company name
print("company name:");
print (tkns[i]);
i++;
this_customer.invested_stocks_num[(i-3)/7] = atoi(tkns[i]);//num of stocks
print("\n num of stocks:");
print (tkns[i]);
i++; i++; i++;// for passing stocks on
strcpy(this_customer.invested_date[(i-3)/7], tkns[i]);//date
print("\n date:");
print (tkns[i]);
i++; i++;//passing budget
char tmp_budget[MAX_ARRAY_SIZE];
clear_buff(tmp_budget, MAX_ARRAY_SIZE);
strncpy(tmp_budget, tkns[i], strlength(tkns[i])-1);
this_customer.remained_budget[(i-3)/7] = atoi(tmp_budget);
print("\n budget:");
print (tkns[i]);
i++;
this_customer.invstd_num++;
}
close(file_fd);
int response_stat = customer_response(tokens, tkn_num, &this_customer, res, path_name);
if(response_stat == 1)
record_customer_data(path_name, this_customer);
return response_stat;
}
else
close(file_fd);
}
return -1;
}*/
/*int company_response(char tokens[MAX_ARRAY_SIZE][MAX_STR_SIZE], int num_of_tokens,
company* this_company, char res[MAX_STR_SIZE], char* path_name)
{
clear_buff(res, MAX_STR_SIZE);
if(num_of_tokens >= 7 && mystrcmp(tokens[2], "Introduction") == 0 && mystrcmp(tokens[3], "Company") == 0)
{
int cr_fd = creat(path_name, O_RDWR | O_APPEND);
if(cr_fd > 0)
{
chmod(path_name, S_IRUSR | S_IWUSR );
char w_buff[MAX_STR_SIZE];
clear_buff(w_buff, MAX_STR_SIZE);
strcpy(w_buff, "Main stocks Num ");
strcat(w_buff, tokens[5]);
strcat(w_buff, "\n");
strcat(w_buff, "stocks Price ");
strcat(w_buff, tokens[6]);
strcat(w_buff, "$\n");
int w_st = write(cr_fd, w_buff, strlength(w_buff));
if(w_st < 0)
{
write(STDOUTFD, "Error in Writing File!\n", sizeof("Error in Writing File!\n"));
return -1;
}
strcpy(res, "You Registered Successfully!\n");
}
else
return -1;
}
else if(num_of_tokens >= 4 && mystrcmp(tokens[2], "Get") == 0 && mystrcmp(tokens[3], "Status") == 0
&& this_company != NULL)
{
clear_buff(res, MAX_ARRAY_SIZE);
char date_p[30];
clear_buff(date_p, 30);
get_date(date_p);//get date
strcpy(res, "------------Company Status -------------\nCompanyName : ");
strcat(res, this_company->name);
strcat(res, "\nStatus Time : ");
strcat(res, date_p);
strcat(res, "\nBudget ");
char tmp_str[20];
clear_buff(tmp_str, 20);
int_to_str(this_company->budget, tmp_str, 10);
strcat(res, tmp_str);
strcat(res, "$\nPrice of each stock : ");
clear_buff(tmp_str, 20);
int_to_str(this_company->price_of_stock,tmp_str, 10);
strcat(res, tmp_str);
strcat(res, "$\nRemaining stocks num : ");
clear_buff(tmp_str, 20);
int_to_str(this_company->stocks_number, tmp_str, 10);
strcat(res, tmp_str);
strcat(res, "\n");
int i;
for(i=0; i<this_company->invstr_num; i++)
{
strcat(res, this_company->investors[i]);
strcat(res, " bought ");
clear_buff(tmp_str, 20);
int_to_str(this_company->investors_stocks_num[i], tmp_str, 10);
strcat(res, tmp_str);
strcat(res, " stocks on ");
strcat(res, this_company->investing_date[i]);
strcat(res, "\n");
}
strcat(res, "\0");
}
else
return -1;
return 0;
}*/
/*int process_company_comm(char tokens[MAX_ARRAY_SIZE][MAX_STR_SIZE], int num_of_tokens, char res[MAX_STR_SIZE], char* dirnm)
{
company this_company;
strcpy(this_company.name, tokens[1]);
char path_name[MAX_STR_SIZE];
clear_buff(path_name, MAX_STR_SIZE);
strcpy(path_name, dirnm);
strcat(path_name, "/Company/");
strcat(path_name, tokens[1]);
strcat(path_name, ".txt");
int file_fd = open(path_name, O_RDWR | O_APPEND);
if(file_fd < 0)
{
return company_response(tokens, num_of_tokens, NULL, res, path_name);
}
else
{
set_compn_data(path_name, &this_company);
return company_response(tokens, num_of_tokens, &this_company, res, path_name);
}
}*/
/*int process_command(char command[MAX_STR_SIZE], char res[MAX_STR_SIZE], char* dirnm)
{
int num_of_tokens;
char tokens[MAX_ARRAY_SIZE][MAX_STR_SIZE];
tokenizer(command, " \n", &num_of_tokens, tokens);
if(num_of_tokens < 0)
return -1;
if(mystrcmp(tokens[0], "company") == 0)
return process_company_comm(tokens, num_of_tokens, res, dirnm);
else if(mystrcmp(tokens[0], "customer") == 0)
return process_customer_comm(tokens, num_of_tokens, res, dirnm);
return -1;
}*/
/*int process_server_command(char buff_read[MAX_STR_SIZE], char response_buff[MAX_STR_SIZE], char* dirnm){
int num_of_tokens;
clear_buff(response_buff, MAX_STR_SIZE);
char tokens[MAX_ARRAY_SIZE][MAX_STR_SIZE];
tokenizer(buff_read, " \n", &num_of_tokens, tokens);
if(num_of_tokens < 4)
return -1;
char pathname[MAX_STR_SIZE];
clear_buff(pathname, MAX_STR_SIZE);
strcpy(pathname, dirnm);
strcat(pathname, "/");
strcat(pathname, tokens[2]);
strcat(pathname, "/");
strcat(pathname, tokens[3]);
strcat(pathname, ".txt");
if(mystrcmp(tokens[0],"Change") == 0 && mystrcmp(tokens[1], "FileOwner") == 0){
if(chmod(pathname, S_IRUSR | S_IWUSR | S_IWOTH | S_IROTH) != 0) strcpy(response_buff, "File address Incorrect\n");
else strcpy(response_buff, "File mode changed\n");
}
else if(mystrcmp(tokens[0],"Show") == 0 && mystrcmp(tokens[1], "FileOwner") == 0){
struct stat sb;
if (stat(pathname, &sb) == -1) strcpy(response_buff, "Stat can not be recognized\n");
else
{
char modestr[MAX_STR_SIZE] ;
int_to_str(sb.st_mode, modestr, 10);
strcpy(response_buff, modestr);
}
}
return 0;
}*/
| true |
cc46da1fdb232b794229975c3b5da89e89912778 | C++ | KimTNguyen/Introduction-3D-Game-Programming | /workshop1/framework/RendererOpenGL.cpp | UTF-8 | 10,131 | 3.203125 | 3 | [] | no_license | // Implementation of RendererOpenGL.h
// Aim: To encapsulate all OpenGL specifics into one class
// to enable easy replacement of OpenGL with other
// graphics APIs (and enable placement of the renderer class into other programs)
//
// Created: 31 May 2005
// Modified: 3rd August 2005
// Author: Martin Masek - SCIS, Edith Cowan University
// Modified: 17 Feb 2010 - Kim Thy Nguyen - SCIS, Edith Cowan University.
#include <windows.h>
#include "RendererOpenGL.h" // include the definition of the class
RendererOpenGL* RendererOpenGL::renderer = NULL; // initialise the pointer to the class to NULL
RendererOpenGL* RendererOpenGL::Instance() // for returning a pointer to the renderer class (also instantiates it if it does not exist)
{
// the class is implemented as a singleton, so create a new instance only if one does not exist already
if (renderer==NULL)
{
// call the constructor (it was declared 'protected' in the header file (RendererOpenGL.h)
// so users of the class cant instantiate new objects from this class (constructor can only be called from within the class)
renderer = new RendererOpenGL;
}
return renderer; // return the pointer to the renderer (to see how this is used, see the message processing function in windowCreator.cpp)
}
RendererOpenGL::RendererOpenGL() // constructor
{
hWnd = NULL; // current window handle
hRC = NULL; // rendering context handle (drawing context for OpenGL
hDC = NULL; // device context handle (device that is displaying the current window)
rendererWidth = GLsizei(640);
rendererHeight = GLsizei(480);
fieldOfViewAngle = 45.0f;
nearClippingPlane = 0.1f;
farClippingPlane = 1000.0f;
}
RendererOpenGL::~RendererOpenGL() // destructor
{
}
void RendererOpenGL::Render() // this does the drawing
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
// Insert rendering code here!
glEnable(GL_TEXTURE_2D); // enable 2D texture mapping
// draw texture mapped objects - code to load and use textures not implemented yet so nothing to do here ;)
glDisable(GL_TEXTURE_2D); // disable 2D texture mapping
// draw non-texture mapped objects
static GLfloat angle = 0.0;
angle += 0.1f;
glTranslatef(0,0.0f,-5.0f); // translate along x,y,z axis
glRotatef(angle,0.0,1.0,0.0); // rotate
// draw a triangles
GLfloat top = 1.0;
GLfloat bottom = -1.0;
GLfloat left = -1.0;
GLfloat right = 1.0;
GLfloat middle = 0.0;
glBegin(GL_TRIANGLES); // this indicates that the verticies we specify are coordinates of triangles
// triangle 1
glColor3f(1.0,0.0,0.0); //specify the current vertex colour (1,0,0 = red)
glVertex3f(left,bottom,0.0); // specify x, y, and z coordinates of vertex 1
glColor3f(0.0,1.0,0.0); //specify the current vertex colour (0,1,0 = green)
glVertex3f(middle,top,0.0); // cordinates of vertex 2
glColor3f(0.0,0.0,1.0); //specify the current vertex colour (0,0,1 = blue)
glVertex3f(right,bottom,0.0); // coordinates of vertex 3
// 3 vertices (as specified above) make a triangle - any subsuquent vertices specified before glEnd() will be
// used to draw another triangle
// eg. draw another triangle, this time all green (un-comment the following lines to see it):
//glColor3f(0.0,1.0,0.0);
//glVertex3f(-1.0,0.0,0.0);
//glVertex3f(-1.0,0.0,-1.0);
//glVertex3f(0.0,top,-0.5);
glEnd();
// End of inserted rendering code
SwapBuffers(hDC); //swap the buffer that OpenGL has been drawing into with the frame buffer (buffer the screen is drawn from)
}
void RendererOpenGL::setUpViewingFrustum() // set up the viewing volume
{
// Select projection matrix and reset it to identity, subsequent operations are then performed on this matrix (gluPerspective)
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// set up the perspective of the window
GLdouble aspectRatio = (GLfloat)rendererWidth/(GLfloat)rendererHeight;
gluPerspective(fieldOfViewAngle, aspectRatio, nearClippingPlane, farClippingPlane);
// select the model-view matrix (to de-select the projection matrix) and reset it to identity
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
bool RendererOpenGL::bindToWindow(HWND &windowHandle)
{
//set up pixel format, rendering context
// NOTE: this method uses 'wgl' commands - the MS Windows Operating system binding for OpenGL.
// it must be over-written when porting this renderer to another OS.
// Need to do 5 things before we can use OpenGL
// First - get the device context of the game window (ie. what is the window being shown on eg. graphics adapter)
// Second - set that device to some desired pixel format
// Third - create a rendering context for OpenGL (something OpenGL draws to and maps to the device)
// Fourth - make the rendering context 'current'
// Fifth - Set the size of the OpenGL window.
// First - get the device context of the game window
hWnd = windowHandle;
hDC = GetDC(hWnd); // get the device context of the window
// Second - set the device to some desired pixel format
// This is done be filling out a pixel format descriptor structure
static PIXELFORMATDESCRIPTOR pfd; // pixel format descriptor
// The pixel format discriptor has a lot of memembers (26) !
// luckily we dont need most of them and set them to zero
// we could go through the structure member by member and set them to zero
// but a shortcut way is to use memset to initialise everything to zero
memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR)); // sets all memmbers of pfd to 0
// now we change only the relevant pfd members
pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.cColorBits = 16;
pfd.cDepthBits = 16;
// based on the descriptor, choose the closest supported pixel format.
int PixelFormat = ChoosePixelFormat(hDC, &pfd);
if (PixelFormat==0)
{
// error
MessageBox (NULL,"Could not choose pixel format","Error",MB_OK);
return (false);
}
// set the display device (device context) to the pixel format
if (SetPixelFormat(hDC, PixelFormat, &pfd)==0)
{
// error
MessageBox (NULL,"Could not set pixel format","Error",MB_OK);
return (false);
}
// Third - create rendering context
hRC = wglCreateContext(hDC); // windows dependent OpenGL function (wgl)
if (hRC==NULL)
{
MessageBox (NULL,"Could not create GL rendering context","Error",MB_OK);
return (false);
}
// Fourth - Make the rendering context current
if (!wglMakeCurrent(hDC, hRC))
{
MessageBox (NULL,"Could not make rendering context current","Error",MB_OK);
return (false);
}
// Fifth - set the size of the OpenGL window
/*
***** Note: this step is important, not setting an initial size
can cause the whole OS to crash (computer is re-set)
*/
RECT rect; // structure to store the coordinates of the 4 corners of the window
GetClientRect (hWnd, &rect); // put the window coordinates in the structure
ResizeCanvas(long(rect.right-rect.left), long(rect.bottom-rect.top));
return (true);
}
void RendererOpenGL::getGLvendor()
{
char *info;
info = (char *)glGetString(GL_VENDOR);
MessageBox (NULL,info,"Vendor",MB_OK);
}
void RendererOpenGL::getGLrenderer()
{
char *info;
info = (char *)glGetString(GL_RENDERER);
MessageBox (NULL,info,"Renderer",MB_OK);
}
void RendererOpenGL::getGLversion()
{
char *info;
info = (char *)glGetString(GL_VERSION);
MessageBox (NULL,info,"Version",MB_OK);
}
void RendererOpenGL::getGLextensions()
{
char *info;
info = (char *)glGetString(GL_EXTENSIONS);
MessageBox (NULL,info,"Extensions",MB_OK);
}
void RendererOpenGL::initialise()
{
glClearColor(0.0,0.0,0.0,0.0); // select what colour the background is (here set to black)
glClearDepth(1.0f); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enables Depth Testing (using Z-buffer)
glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do
glShadeModel(GL_SMOOTH); // Enable Smooth Shading
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // give OpenGL a hint on which perspective calculation to use (here suggesting the nicest)
SwapBuffers(hDC); // draw the screen (will draw a black blank screen as no drawing has been done yet)
// examples of other operations that could be good here in the future:
//glEnable(GL_TEXTURE_2D); // enable 2D texture mapping
//glFrontFace(GL_CW); // indicate which side of a polygon is the front (defined in terms of the order vertices are given)
//glEnable(GL_CULL_FACE); // enable back-face culling
}
bool RendererOpenGL::releaseFromWindow()
{
if (hDC == NULL || hRC == NULL)
{
MessageBox (NULL,"hDC or hRC already NULL!","Error",MB_OK);
return (false);
}
if (wglMakeCurrent(NULL, NULL) == false)
{
// error
MessageBox (NULL,"Could not set hDC to NULL","Error",MB_OK);
return (false);
}
if (wglDeleteContext(hRC) == false)
{
// error deleting rendering context
MessageBox (NULL,"Could not delete rendering context","Error",MB_OK);
return (false);
}
// Windows releases the DC in the default message handler, if not passing all messages through it,
// the releaseDC function must be called (we are, so its commented out - otherwise allways get the message box error)
//if (releaseDC(hWnd,hDC)==false)
//{
// MessageBox (NULL,"Could not release device context","Error",MB_OK);
// return (false);
//}
hRC = NULL;
hDC = NULL;
// delete the renderer and set it to NULL (this is how the singleton gets deleted)
delete renderer;
renderer = NULL;
return (true);
}
// re-size the viewport
void RendererOpenGL::ResizeCanvas(long widthRequest, long heightRequest)
{
rendererWidth = (GLsizei)widthRequest;
rendererHeight = (GLsizei)heightRequest;
glViewport(0, 0, rendererWidth, rendererHeight);
setUpViewingFrustum();
}
| true |
d24c5b7f890854506e6aa8f9dcb300b67de44efa | C++ | cz78/BST | /bstmain.cpp | UTF-8 | 954 | 3.59375 | 4 | [] | no_license | #include "bst.h"
int main()
{
BST tree;
cout << "inserting 7" << endl;
tree.insert("7");
cout << "inserting 4" << endl;
tree.insert("4");
// cout << "inserting 12" << endl;
// tree.insert("12");
cout << "inserting 1" << endl;
tree.insert("1");
cout << "inserting 6" << endl;
tree.insert("6");
cout << "inserting 8" << endl;
tree.insert("8");
// cout << "inserting 14" << endl;
// tree.insert("14");
cout << "inserting 3" << endl;
tree.insert("3");
cout << "inserting 2" << endl;
tree.insert("2");
cout << "inserting 5" << endl;
tree.insert("5");
tree.remove("2");
int size = tree.size();
int height = tree.height();
if (tree.contains("5"))
{
cout << "Found 5 in tree" << endl;
}
cout << "The size is: " << size << endl;
cout << "The height is: " << height << endl;
cout << "Pre order: ";
tree.print_preorder();
cout << "In order: ";
tree.print_inorder();
cout << "Post order: ";
tree.print_postorder();
return 0;
}
| true |
a9045a7442d522d72a212c4f0ef75f231d36dee5 | C++ | ThatOtherOtherBob/Solitaire | /ButtonEventCreator.cpp | UTF-8 | 1,660 | 2.921875 | 3 | [
"MIT"
] | permissive | #include "ButtonEventCreator.hpp"
ButtonEventCreator::ButtonEventCreator()
{
for (size_t buttonNumber = (int)ButtonsEnum::First; buttonNumber < (int)ButtonsEnum::Size; buttonNumber++)
{
oldButtons[buttonNumber] = false;
newButtons[buttonNumber] = false;
}
}
std::vector<ButtonsEnum> ButtonEventCreator::GenerateEvents(blit::ButtonState buttons)
{
setOldButtons();
setNewButtons(buttons);
return createPressedEvents();
}
void ButtonEventCreator::setOldButtons()
{
for (size_t buttonNumber = (int)ButtonsEnum::First; buttonNumber < (int)ButtonsEnum::Size; buttonNumber++)
oldButtons[buttonNumber] = newButtons[buttonNumber];
}
void ButtonEventCreator::setNewButtons(blit::ButtonState buttons)
{
newButtons[(int)ButtonsEnum::Up] = buttons & blit::Button::DPAD_UP;
newButtons[(int)ButtonsEnum::Down] = buttons & blit::Button::DPAD_DOWN;
newButtons[(int)ButtonsEnum::Left] = buttons & blit::Button::DPAD_LEFT;
newButtons[(int)ButtonsEnum::Right] = buttons & blit::Button::DPAD_RIGHT;
newButtons[(int)ButtonsEnum::A] = buttons & blit::Button::A;
newButtons[(int)ButtonsEnum::B] = buttons & blit::Button::B;
newButtons[(int)ButtonsEnum::X] = buttons & blit::Button::X;
newButtons[(int)ButtonsEnum::Y] = buttons & blit::Button::Y;
newButtons[(int)ButtonsEnum::Menu] = buttons & blit::Button::MENU;
}
std::vector<ButtonsEnum> ButtonEventCreator::createPressedEvents()
{
std::vector<ButtonsEnum> events;
for (size_t buttonNumber = (int)ButtonsEnum::First; buttonNumber < (int)ButtonsEnum::Size; buttonNumber++)
if (newButtons[buttonNumber] && !oldButtons[buttonNumber])
events.push_back((ButtonsEnum)buttonNumber);
return events;
} | true |
6a79d29c61c448c1e6d13b9045e04b7662ec03fb | C++ | ipang21/ip1 | /hr/eight/stockmax.cpp | UTF-8 | 835 | 2.90625 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
unsigned long long getMax(vector<unsigned long long> *x) {
unsigned long long max = 0;
vector<unsigned long long>::iterator peak;
while (x->size() > 0) {
peak = max_element(x->begin(), x->end());
for (vector<unsigned long long>::iterator it = x->begin(); it != peak; it++) {
max += (*peak - *it);
}
x->erase(x->begin(), peak+1);
}
return max;
}
int main() {
/* Enter your code here. Read input from STDIN. Prunsigned long long output to STDOUT */
unsigned long long T, N, in;
vector<unsigned long long> prices;
cin >> T;
while (T--) {
cin >> N;
for (int i = 0; i<N; i++) {
cin >> in;
prices.push_back(in);
}
cout << getMax(&prices)<<endl;
prices.clear();
}
return 0;
}
| true |
cbcd32a324cb1a6448278eddcffddcbc24376496 | C++ | shoaib0657/Competitive-Programming-Problems-2020 | /Queue/Implement Queue using one stack.cpp | UTF-8 | 774 | 3.8125 | 4 | [] | no_license | //implement queue using only one stack
#include<iostream>
#include<stack>
using namespace std;
template<class X>
class Queue {
private:
stack<X> s;
public:
Queue() {
}
void enQueue(X d) {
s.push(d);
}
X deQueue() {
if (s.empty()) {
return -1;
}
X temp = s.top();
s.pop();
if (s.empty())
return temp;
X item = deQueue();
s.push(temp);
return item;
}
X peek() {
return s.top();
}
X empty() {
return s.empty();
}
int main() {
Queue<int> q1;
q1.enQueue(5);
q1.enQueue(10);
q1.enQueue(15);
cout << "Front of the queue:" << q1.peek() << endl;
cout << "Check whether queue is empty:" << q1.empty() << endl;
cout << "Dequeuing queue :-" << endl;
cout << q1.deQueue() << " ";
cout << q1.deQueue() << " ";
return 0;
}
};
| true |
aa645728d42681364f06ac56ce9ac9f9a77a4af4 | C++ | IllgamhoDuck/42SiliconValley | /c++_piscine/education/Day02/Integer.cpp | UTF-8 | 1,760 | 3.21875 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Integer.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hypark <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/01/15 21:01:07 by hypark #+# #+# */
/* Updated: 2020/01/15 21:35:47 by hypark ### ########.fr */
/* */
/* ************************************************************************** */
#include <iostream>
#include "Integer.hpp"
Integer::Integer(int const n) : _n(n)
{
std::cout << "Constructor called with value " << n << std::endl;
return ;
}
Integer::~Integer(void)
{
std::cout << "Destructor called with value " << this->_n << std::endl;
return ;
}
int Integer::getValue(void) const
{
return this->_n;
}
Integer & Integer::operator=(Integer const & rhs)
{
std::cout << "Assignation operator called from " << this->_n;
std::cout << " to " << rhs.getValue() << std::endl;
this->_n = rhs.getValue();
return *this;
}
Integer Integer::operator+(Integer const & rhs) const
{
std::cout << "Addition operator called with " << this->_n;
std::cout << " and " << rhs.getValue() << std::endl;
return Integer(this->_n + rhs.getValue());
}
std::ostream & operator<<(std::ostream & o, Integer const & rhs)
{
o << rhs.getValue();
return o;
}
| true |
51cf958fb2fb3607c8f10644506b3345ec2b5818 | C++ | opQuack/CPfiles | /POLYREL.cpp | UTF-8 | 476 | 2.78125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int findSides(int N){
if(N==3) return 3;
else if(N==4) return 4;
else if(N==5) return 5;
else{
return N+findSides(N/2);
}
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(NULL);
int T, N;
long int x;
scanf("%d", &T);
while(T--){
scanf("%d", &N);
for(int i=0; i<N; i++) scanf("%d%d", &x, &x);
printf("%d\n", findSides(N));
}
return 0;
}
| true |
02a122341571760c54a24fabf83d9b2dacb2970a | C++ | RedGry/ITMO | /Algorithms/Part_4/Task O.cpp | UTF-8 | 1,090 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool dfs (int i, vector <vector <int>> ¶, int *trade, bool start = true){
trade[i] = !start;
bool answer;
for (auto p : para[i]){
if (trade[p] == -1){
answer = dfs(p, para, trade, !start);
} else if (trade[i] == trade[p]){
return false;
}
}
return answer;
}
void solve(){
int n, m;
cin >> n >> m;
bool answer;
vector <vector <int>> para (n);
int trade[n];
memset(trade, -1, sizeof(trade));
while (m != 0){
int p1, p2;
cin >> p1 >> p2;
para[--p1].push_back(--p2);
para[p2].push_back(p1);
m--;
}
int i = 0;
while (n != 0){
if (trade[i] == -1){
answer = dfs(i, para, trade);
}
i++;
n--;
}
if (answer){
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
solve();
return 0;
}
| true |
855cced7e7eb24daa1bbf2486b00c69a1aa2d340 | C++ | yfqiu98/QFSDK | /ver_1/separa_data.cpp | UTF-8 | 2,272 | 3.15625 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include <windows.h>
int Decoder(FILE *File, int window_size, int feature_size, int dataLen, double *inputBox, double *outputBox);
int normalizer(double *input, double *output, int method);
int main(){
int dataLen = 2048;
int feature_size = 4;
int window_size = 9;
FILE *produce_USDCAD = fopen("USDCAD.csv", "r");
double *input = (double *)malloc(dataLen * feature_size * window_size *sizeof(double));
double *output = (double *)malloc(dataLen * feature_size * sizeof(double));
if(Decoder(produce_USDCAD, window_size, feature_size, dataLen, input, output)== 1){
printf("load data to input and ouput array successfully ");
}else{
printf("Nope,nope,nope....");
}
fclose(produce_USDCAD);
int d;
scanf("%d",&d);
}
// this file is all about data preprocessing
// first this is used to transform CSV into different arrange.
int Decoder(FILE *File, int window_size, int feature_size, int dataLen, double *inputBox, double *outputBox){
if(File == NULL){
return 0;
}
// to get all the data inside the File
double *longList = (double *)malloc(2050 * 20 * sizeof(double));
char temp[500];
char *words;
int daysize = 0;
int attributes = 0;
fgets(&temp[0],200,File);
while(fgets(&temp[0],200,File)!= NULL){
words = strtok(temp, ",");// seperate word by identifing ","
while( words != NULL){
longList[daysize * 20 + attributes] = strtod(words,NULL);
words = strtok(NULL, ",");// seperate word by identifing ","
attributes++;
}
attributes = 0;
daysize++;
}
//sliding window to input and ouput
int indexOfInput = 0;
int indexOfOutput = 0;
for(int x = 0;x < daysize-window_size-1;x++){
//load to input array
for(int y = 0;y < window_size;y++){
//x
for(int z = 0;z < feature_size;z++){
inputBox[indexOfInput] = longList[(x+y)*20+z+3];
indexOfInput++;
}
}
// load to output array
for(int z = 0;z < feature_size;z++){
outputBox[indexOfOutput] = longList[(x+window_size)*20+z+3];
indexOfOutput++;
}
}
free(longList);
return 1 ;
}
// and then, this is used to normalize
int normalizer(double *input, double *output, int method){
return 0;
} | true |
986d8a25600659ef4cf0ae25138160018690e959 | C++ | yogendrarp/udemyc- | /stl/queue.cpp | UTF-8 | 615 | 3.859375 | 4 | [] | no_license |
#include <iostream>
#include <string>
#include <queue>
class Test
{
std::string name;
public:
explicit Test(std::string name) : name(name)
{
}
~Test()
{
}
void print() const
{
std::cout << name << std::endl;
}
};
int main()
{
std::queue<Test> test_queue;
test_queue.push(Test("Mike"));
test_queue.push(Test("John"));
test_queue.push(Test("Sue"));
test_queue.back().print();
while (test_queue.size() > 0)
{
Test &test = test_queue.front();
test.print();
test_queue.pop();
}
std::cout << std::endl;
} | true |
f3861451755d1d6c5be48221c676ee961f6d2c72 | C++ | Dwgjjdxq/Offer2017 | /sorts/heapSort.cpp | GB18030 | 3,087 | 3.828125 | 4 | [] | no_license | #include <iostream>
using namespace std;
void swap(int &a, int &b) {
a ^= b;
b ^= a;
a ^= b;
}
/*
1. ʵ "ǰڵ" "ӽĽ" Ƚϣ
2. "ǰڵ" ģôҪֱbreak
3. "ֵ" ǵ "ǰڵ"ͬʱ "ֵ" λø "ǰڵ"
"ǰڵ"Ѱȷλã "ֵ" "ӽ" ȥȽϣ
(ûһӴȥǸӵĺȥȽϣֱҵӶλã
ûкӵʱͽȻøλ)
4. ѭֱ "ǰڵ" µλñˣûӽˣʱ˳ȥ
"ǰڵ" ֵŵ "ǰλ"
*/
void maxHeap(int *arr, int curPos, int length) {
int temp = arr[curPos];
// int maxPos = (curPos << 1) + 1; // curPos, ˾forѭڣmaxposλϢȥ
/*ӽǽtempȽϣtempѾʱˣֱtempѾûӽΪֹ*/
for (int maxPos = (curPos << 1) + 1; maxPos <= length; maxPos = 2 * maxPos + 1) { /* maxPos = maxPos * 2 + 1,½ӽıȽ */
/*Ѱӽ*/ // ˴maxPos < length ܵڣڣmaxPos+1
if (maxPos < length && arr[maxPos] < arr[maxPos + 1])
maxPos++; // curPos
/*ڵֵģôֹͣ*/
if (temp >= arr[maxPos]) /*ʾӽ֮ûеǰڵ˳ѭ*/
break;
/*ڵ㱻ӽ㸲*/
arr[curPos] = arr[maxPos];
/*ͬʱӽλΪڵܴŵλãѰҸڵմŵλ*/
curPos = maxPos;
}
/*λþǸڵŵλã*/
arr[curPos] = temp;
}
void HeapSort(int arr[], int length) {
if (arr == NULL || length <= 0)
return;
/*һ齨һѣڵӽڵ㶼*/
/*Ԫص±Ǵ0length - 1*/
/*ΪĶȫ˼ʵֵģԣ˴ length/2 - 1 λǴϣһҶӽ*/
for (int curPos = (length >> 1) - 1; curPos >= 0; --curPos) {
maxHeap(arr, curPos, length - 1); // length - 1 Ϊʵʵıֵ
}
/*ѭ滻ѶԪһԪ(һֱpos - 1),µ*/
for (int pos = length - 1; pos > 0; --pos) {
swap(arr[0], arr[pos]);
maxHeap(arr, 0, pos - 1);
}
}
int main() {
int arr[] = { 2, 1, 4, 3, 7, 8, 4, 2, 6, 9, 0};
HeapSort(arr, 11);
for (int i = 0; i < 11; ++i)
cout << arr[i] << " ";
cout << endl;
return 0;
} | true |
612415784b30cc3f5a8cce79bb37196332196984 | C++ | Chuncheonian/oop-tutorial | /05_largeDataProcessing-1.cpp | UTF-8 | 3,485 | 3.828125 | 4 | [] | no_license | /**
* @file 05_largeDataProcessing-1.cpp
* @author Dongyoung Kwon (ehddud2468@gmail.com)
* @brief string, file stream
* @date 2020-04-07
*/
#include <iostream>
#include <fstream> // ofstream, ifstream Class 사용
#include <string>
using namespace std;
// 1. string
int main() {
// string: string class or string object
// s: Object or Instance
string s = "fred"; // string class로부터 s라는 instance(객체) 생성
cout << "s: " << s << endl;
cout << s.size() << endl << endl; // s라는 객체는 size() method를 가지고 있다. [s.length() == s.size()]
cout << "s: " << s << endl;
cout << s.empty() << endl; // 문자열이 차 있으면 false
s.clear(); // s= "";
cout << "s: " << s << endl;
cout << s.empty() << endl << endl; // 문자열이 비어 있으면 true
s = "Good";
s += "-bye";
cout << "s: " << s << endl;
cout << s[4] << ", " << s.at(4) << endl << endl; // s[i]가 구동속도가 빠름, s.at은 at함수를 꺼내써야되서 느림, 그러나 안전상 s.at를 주로 씀
cout << s.substr(5, 2) << endl; // (시작 index, 추출할 문자열의 길이)
cout << s.substr(5, 3) << endl << endl;
cout << s.find("od") << endl;
cout << s.find("od", 5) << ", " << string::npos << endl; // 5자리수부터 찾기 시작
// 찾는 문자열이 없는 경우 string::npos를 반환한다.
// if (s.find("od", 5) == string::npos) { "od가 없는 경우..."}
s += "-od";
// Good-bye-od
string key = "od";
cout << "s: " << s << endl;
int idx = s.find(key);
cout << idx << endl;
cout << s.find("od", idx+key.size()) << endl;
cout << (s == "Good-bye-od") << endl;
return 0;
}
/*
// 2. file stream - getline()
int main() {
ofstream fout; // fout은 ofstream의 인스턴스이다. 다른 이름으로 해도 된다. e.g. ofstream tmp;
fout.open("example.txt"); // 덮어쓰기
// fout.open("example.txt", ios::app); // 이어쓰기
string s = "Object Oriented Programming";
fout << s << endl;
fout << "Linear Algebra" << endl;
fout << "Random Process" << endl;
fout.close();
ifstream fin;
fin.open("example.txt");
if (!fin) { // fin: 파일을 제대로 열지 못했거나 EOF를 읽으면 false
cout << "File Open Error" << endl;
exit(100); // 강제 프로그램 종료
}
// getline(ifstream instance, string instance): 한줄씩 읽는다.
// 한줄: 줄바꿈 문자로 문자열을 구분
while (getline(fin, s)) {
cout << s << endl;
}
fin.close();
return 0;
}
*/
// "한 문자"(문자열 x)를 쓰기: fout.put()
// "한 문자"(문자열 x)를 읽기: fin.get()
// | ifstream | ofstream
// ----------------------| ------------- | ------------
// char | fin.get(ch) | fout.put(ch)
// word(공백, 줄바꿈) | fin >> s | fout << s
// line(줄바꿈) | getline(fin,s)| fout << s
// 중요 1) fout/fin 사용시 반드시 시작 open(), 끝 close()
// 2) ifstream fin에서, 파일 open 실패, EOF까지 읽으면, fin == false (!fin == true)
/*
// 3. file stream - get(), put()
int main() {
char ch;
ofstream fout("char.txt"); // fout.open() 생략
while (true) {
cin >> ch;
if (ch == 'q')
break;
fout.put(ch); // 문자를 파일에 쓰기
}
fout.close();
ifstream fin("char.txt");
cout << endl << endl;
while (true) {
fin.get(ch);
if (!fin)
break;
cout << ch << endl;
}
fin.close();
return 0;
}
*/ | true |
a6f2fc3adf2f0d2444fe83cdd796b5af52a80896 | C++ | CannyLab/tsne-cuda | /src/include/util/random_utils.h | UTF-8 | 1,204 | 2.6875 | 3 | [
"BSD-3-Clause"
] | permissive | /**
* @brief Utilities for handling random numbers
*
* @file random_utils.h
* @author David Chan
* @date 2018-04-04
* Copyright (c) 2018, Regents of the University of California
*/
#ifndef SRC_INCLUDE_UTIL_RANDOM_UTILS_H_
#define SRC_INCLUDE_UTIL_RANDOM_UTILS_H_
#include "include/common.h"
#include "include/util/cuda_utils.h"
namespace tsnecuda {
namespace util {
/**
* @brief Returns a uniform-random float device vector in range [0,1]
*
* @param vector_size The length of the vector to return
* @return thrust::device_vector<float>
*/
thrust::device_vector<float> RandomDeviceUniformZeroOneVector(
std::default_random_engine &generator, const int vector_size);
/**
* @brief Returns a uniform random device vector in the specified range
*
* @param vector_size The size of the device vector to return
* @param lower_bound The lower bound
* @param upper_bound The upper bound
* @return thrust::device_vector<float> The random vector
*/
thrust::device_vector<float> RandomDeviceVectorInRange(
std::default_random_engine &generator,
const int vector_size,
float lower_bound,
float upper_bound);
}
}
#endif // SRC_INCLUDE_UTIL_RANDOM_UTILS_H_
| true |
181a9c59725c54882f086535b7524a7ef9882450 | C++ | cualquiercosa327/Wii-U-Firmware-Emulator | /src/hardware/pi.cpp | UTF-8 | 3,232 | 2.59375 | 3 | [
"MIT"
] | permissive |
#include "hardware/pi.h"
#include "hardware.h"
#include "physicalmemory.h"
WGController::WGController(PhysicalMemory *physmem) {
this->physmem = physmem;
}
void WGController::reset() {
base = 0;
top = 0;
ptr = 0;
threshold = 0;
index = 0;
}
uint32_t WGController::read(uint32_t addr) {
switch (addr) {
case WG_BASE: return base;
case WG_TOP: return top;
case WG_PTR: return ptr;
case WG_THRESHOLD: return threshold;
}
Logger::warning("Unknown wg read: 0x%X", addr);
return 0;
}
void WGController::write(uint32_t addr, uint32_t value) {
if (addr == WG_BASE) base = value;
else if (addr == WG_TOP) top = value;
else if (addr == WG_PTR) ptr = value;
else if (addr == WG_THRESHOLD) threshold = value;
else {
Logger::warning("Unknown wg write: 0x%X (0x%08X)", addr, value);
}
}
void WGController::write_data(uint32_t value) {
buffer[index++] = value;
if (index == 8) {
for (int i = 0; i < 8; i++) {
physmem->write<uint32_t>(ptr, buffer[i]);
ptr += 4;
}
index = 0;
if (ptr >= threshold) {
ptr = base;
}
}
}
void PIInterruptController::reset() {
intsr = 0;
intmr = 0;
}
uint32_t PIInterruptController::read(uint32_t addr) {
switch (addr) {
case PI_INTSR: return intsr;
case PI_INTMR: return intmr;
}
Logger::warning("Unknown pi interrupt read: 0x%X", addr);
return 0;
}
void PIInterruptController::write(uint32_t addr, uint32_t value) {
if (addr == PI_INTSR) intsr &= ~value;
else if (addr == PI_INTMR) intmr = value;
else {
Logger::warning("Unknown pi interrupt write: 0x%X (0x%08X)", addr, value);
}
}
void PIInterruptController::set_irq(int irq, bool state) {
if (state) {
intsr |= 1 << irq;
}
else {
intsr &= ~(1 << irq);
}
}
bool PIInterruptController::check_interrupts() {
return intsr & intmr;
}
PIController::PIController(PhysicalMemory *physmem) :
wg {physmem, physmem, physmem}
{}
void PIController::reset() {
for (int i = 0; i < 3; i++) wg[i].reset();
for (int i = 0; i < 3; i++) interrupt[i].reset();
}
uint32_t PIController::read(uint32_t addr) {
if (PI_WG_START <= addr && addr < PI_WG_END) {
addr -= PI_WG_START;
return wg[addr / 0x10].read(addr % 0x10);
}
if (PI_INTERRUPT_START <= addr && addr < PI_INTERRUPT_END) {
addr -= PI_INTERRUPT_START;
return interrupt[addr / 8].read(addr % 8);
}
Logger::warning("Unknown pi read: 0x%X", addr);
return 0;
}
void PIController::write(uint32_t addr, uint32_t value) {
if (PI_WG_START <= addr && addr < PI_WG_END) {
addr -= PI_WG_START;
wg[addr / 0x10].write(addr % 0x10, value);
}
else if (PI_INTERRUPT_START <= addr && addr < PI_INTERRUPT_END) {
addr -= PI_INTERRUPT_START;
interrupt[addr / 8].write(addr % 8, value);
}
else {
Logger::warning("Unknown pi write: 0x%X (0x%08X)", addr, value);
}
}
void PIController::set_irq(int irq, bool state) {
for (int i = 0; i < 3; i++) {
interrupt[i].set_irq(irq, state);
}
}
void PIController::set_irq(int core, int irq, bool state) {
interrupt[core].set_irq(irq, state);
}
bool PIController::check_interrupts(int core) {
return interrupt[core].check_interrupts();
}
| true |
cf2c5a9e4ab29b8dcb41f88f2668146a4a6183bc | C++ | rabispedro/SFML | /Space Invaders++/code/LevelManager.h | UTF-8 | 1,015 | 2.734375 | 3 | [
"MIT"
] | permissive | #pragma once
#include<SFML/Graphics.hpp>
#include<vector>
#include<string>
#include"GameObject.h"
#include"GameObjectSharer.h"
using namespace std;
using namespace sf;
class LevelManager : public GameObjectSharer{
private:
vector<GameObject> m_GameObjects;
const string WORLD_FOLDER = "../world";
const string SLASH = "/";
void runStartPhase();
void activateAllGameObjects();
public:
vector<GameObject>& getGameObjects();
void loadGameObjectsForPlayMode(string screenToLoad);
/*
* From GameObjectSharer INTERFACE
*/
vector<GameObject>& GameObjectSharer::getGameObjectsWithGOS(){
return m_GameObjects;
}
GameObject& GameObjectSharer::findFirstObjectWithTag(string tag){
auto it = m_GameObjects.begin();
auto end = m_GameObjects.end();
for(it; it!=end; it++){
if((*it).getTag() == tag){
return (*it);
}
}
}
#ifdef debuggingErrors
cout<<"LevelManager.h findFirstGameObjectWithTag() - TAG NOT FOUND ERROR!\n";
#endif
return m_GameObjects[0];
}; | true |
e6f06ada2966a3109adbb103e577237b0ce8d257 | C++ | vinothsid/vino-cache | /Cache.cpp | UTF-8 | 27,279 | 2.875 | 3 | [] | no_license | #include <iostream>
//#include<limits>
#include "limits.h"
#include "stdlib.h"
#include <fstream>
#include <sstream>
#include "string.h"
#include <iomanip>
//#define DEBUG 0
#define VICTIM_NONE 0
#define VICTIM_REPLACE 1
#define VICTIM_WB 2
#define CACHE_MISS 0
#define CACHE_HIT 1
using namespace std;
typedef unsigned int TAG;
long int numOpers;
class Block {
bool valid;
bool dirty;
int lruCounter;
TAG tag;
public:
Block() ;
int setValid(bool value);
int setDirty(bool value);
int setTag( TAG tagAddr);
bool isValid();
bool isDirty();
bool checkTag(TAG tagAddr);
int setLru(int i);
int getLru();
int incrLru(int assoc);
TAG getTag();
};
Block::Block() {
valid = false;
dirty = false;
lruCounter=-1;
}
int Block::setLru(int i) {
lruCounter = i;
}
int Block::getLru() {
return lruCounter;
}
TAG Block::getTag() {
return tag;
}
int Block::incrLru(int assoc) {
lruCounter = ( lruCounter + 1 )%assoc ;
}
int Block::setValid(bool value) {
valid = value;
}
int Block::setDirty(bool value) {
dirty = value;
}
int Block::setTag( TAG tagAddr) {
tag = tagAddr;
}
bool Block::isValid() {
return (valid==true);
}
bool Block::isDirty() {
return (dirty==true);
}
bool Block::checkTag(TAG tagAddr) {
return isValid() && (tag==tagAddr);
}
//Set class which holds the #ASSOC blocks;
class Set {
Block *blk;
int setAssoc;
long int * prefReadCounter;
public:
// Set(int assoc); since array of set have to be created default constructor can only be called
Set();
int init(int assoc );
int getLRU(); // Returns the index of LRU block in the set
int place(TAG tag,char oper, TAG & wbTag ); // places the tag at corresponding position;
int updateRank(int i);//sets blk[i]'s rank to 0 and updates the rank of other blocks in the set
bool search(TAG tag,char oper); //searches in the entire set and if tag is present returns true else return false
void print();
void printLru();
};
Set::Set() {
}
void Set::printLru() {
for(int i=0;i<setAssoc;i++)
cout << blk[i].getLru() << " " ;
cout << endl;
}
void Set::print() {
char dirtyFlag;
for(int i=0;i<setAssoc;i++) {
for(int j=0;j<setAssoc;j++) {
if(blk[j].getLru() == i ) {
if(blk[j].isDirty())
dirtyFlag = 'D';
else
dirtyFlag = ' ';
if(blk[j].isValid())
cout << "\t" << hex << blk[j].getTag() << " " << dirtyFlag ;
else
cout << "\t-" ;
}
}
}
cout << endl;
}
int Set::init(int assoc) {
setAssoc = assoc;
blk = new Block[assoc];
for(int i=0;i<setAssoc;i++) {
blk[i].setLru(i);
// blk[i-1].setLru(0);
}
}
int Set::getLRU() {
int max=INT_MIN;
int index=-1;
for(int i=0;i<setAssoc;i++) {
if( blk[i].getLru() > max ) {
max = blk[i].getLru();
index = i;
}
}
return index;
}
int Set::place(TAG tag,char oper,TAG & wbTag ) {
int status;
int placeIndex=-1;
for(int i=0;i<setAssoc;i++) {
if(blk[i].isValid()==false) {
placeIndex = i;
break;
}
}
if(placeIndex==-1) {
placeIndex = getLRU();
#ifdef DEBUG
cout << "victim: tag " << hex << blk[placeIndex].getTag() << endl ;
#endif
status = VICTIM_REPLACE;
} else {
#ifdef DEBUG
cout << "victim: none" << endl ;
#endif
blk[placeIndex].setValid(true);
status = VICTIM_NONE;
}
if (blk[placeIndex].isDirty() ) {
// issue a write to next level
//nextLevel.write(tag);
#ifdef DEBUG
cout << "Dirty block " << hex << blk[placeIndex].getTag() << " evicted" << endl;
#endif
status = VICTIM_WB;
wbTag = blk[placeIndex].getTag();
blk[placeIndex].setDirty(false);
#ifdef DEBUG
cout << ", dirty" << endl ;
#endif
}
if (oper == 'w') {
blk[placeIndex].setDirty(true);
#ifdef DEBUG
cout << " set dirty" << endl;
#endif
}
blk[placeIndex].setTag(tag);
updateRank(placeIndex);
return status;
}
int Set::updateRank(int i) {
#ifdef DEBUG
cout << "Update LRU" << endl;
#endif
int tmp = blk[i].getLru();
for(int j=0;j<setAssoc;j++) {
if(j==i) {
blk[j].setLru(0);
} else if( blk[j].getLru() < tmp ) {
blk[j].incrLru( setAssoc );
}
}
}
bool Set::search(TAG tag,char oper) {
for(int i=0;i<setAssoc;i++) {
if (blk[i].checkTag(tag) ) {
if(oper == 'w')
blk[i].setDirty(true);
updateRank(i);
#ifdef DEBUG
// cout << "Hit" << endl;
// cout << "Update LRU" << endl;
#endif
return true;
}
}
#ifdef DEBUG
// cout << "Miss" << endl;
#endif
//if not found in the entire set , its MISS
/* i = getLRU();
blk[i].setValid(true);
blk[i].setTag(tag);
updateRank(i);
*/
//Collect stats
/* if(oper == 'r')
numReadMisses++;
else
numWriteMisses++;
*/
return false;
}
class Cache;
class StreamBuffer {
Block *blk;
// bool *dirty;
int blkSize;
int numBlks;
int head;
int tail;
int lruCounter;
int numOffsetBits;
Cache *nextLevel;
long int *prefReadCounter;
public:
// StreamBuffer(int numBlocks) ;
StreamBuffer();
int init(int numBlocks,int blockSize , Cache *c , long int * statNum );
bool search(TAG blockNumber); // Reads the address tag
int shift();//Shift the entire block up once , and set the new last block
bool makeDirty(TAG blockNumber); // Forgot what to do
int fetch(TAG blockNumber); // Fetches next numBlks blocks into buffer . (blockNumber +1 .... blockNumber + numBlks )
TAG getHead();
int setLru(int i);
int getLru();
int incrLru(int N);
void print();
};
StreamBuffer::StreamBuffer() {
}
void StreamBuffer::print() {
#ifdef DEBUG
cout << "Head :" << head << " Tail : " << tail << endl;
#endif
if(head == -1)
return;
int i=head;
do {
cout << "\t" << hex << (blk[i].getTag() << numOffsetBits) ;
i=(i+1)%numBlks;
} while(i!=head);
cout << endl;
}
int StreamBuffer::init(int numBlocks,int blockSize , Cache *c , long int *statNum) {
blk = new Block[numBlocks];
numBlks = numBlocks;
blkSize = blockSize;
nextLevel = c;
prefReadCounter = statNum;
int tmp = blkSize;
while(tmp) {
tmp = tmp >> 1;
numOffsetBits++;
}
numOffsetBits--;
head=-1;
tail=-1;
}
int StreamBuffer::setLru(int i) {
lruCounter = i;
}
int StreamBuffer::getLru() {
return lruCounter;
}
int StreamBuffer::incrLru(int N) {
lruCounter = (lruCounter+1)%N ;
}
TAG StreamBuffer::getHead() {
return blk[head].getTag();
}
bool StreamBuffer::search(TAG blockNumber) {
if( blk[head].isDirty() == false && blk[head].getTag( ) == blockNumber) {
#ifdef DEBUG
cout << "ST HIT"<< endl;
#endif
return true;
}
return false;
}
bool StreamBuffer::makeDirty(TAG blockNumber) {
if(head == -1)
return false;
int i=head;
do {
if(blk[i].getTag() == blockNumber) {
#ifdef DEBUG
cout << "Block : " << hex << blockNumber << " is set dirty in stream buffer" << endl;
#endif
blk[i].setDirty(true);
return true;
}
i=(i+1)%numBlks;
} while(i!=head);
return false;
}
class PrefetchUnit {
int M; // number of blocks
int N; // number of stream buffers
int blkSize;
Cache *nextLevel;
StreamBuffer *stBuf;
public:
PrefetchUnit(int mBlocks,int nBufs,int bSize,Cache *c, long int *statNum) ;
int updateRank(int i);
int getLRU();
int prefetch(TAG blockAddr);
bool search(TAG blockAddr);
bool makeDirty(TAG blockAddr);
void print();
};
PrefetchUnit::PrefetchUnit(int nBufs,int mBlocks,int bSize,Cache *c,long int *statNum) {
M= mBlocks;
N = nBufs;
blkSize = bSize;
nextLevel = c;
stBuf = new StreamBuffer[N];
for(int i=0;i<N;i++) {
stBuf[i].init(M,blkSize,c,statNum);
stBuf[i].setLru(i);
}
}
void PrefetchUnit::print() {
for(int i=0;i<N;i++) {
#ifdef DEBUG
// cout << i << " " << stBuf[i].getLru() << endl ;
#endif
for(int j=0;j<N;j++) {
if (stBuf[j].getLru() == i)
stBuf[j].print();
}
}
}
bool PrefetchUnit::makeDirty( TAG blockAddr ) {
// eventhough makeDirty is called for all stream buffer , it will be present in any one and will be made dirty
for(int i=0;i<N;i++) {
if ( stBuf[i].makeDirty(blockAddr) ) {
#ifdef DEBUG
// cout << "Block in stream buffer : " << i << " is made dirty" << endl;
#endif
return true;
}
}
return false;
}
int PrefetchUnit::getLRU() {
int max=INT_MIN;
int index=-1;
for(int i=0;i<N;i++) {
if( stBuf[i].getLru() > max ) {
max = stBuf[i].getLru();
index = i;
}
}
return index;
}
int PrefetchUnit::updateRank(int i) {
int tmp = stBuf[i].getLru();
for(int j=0;j<N;j++) {
if ( j==i) {
stBuf[j].setLru(0);
} else if( stBuf[j].getLru() < tmp ) {
stBuf[j].incrLru(N);
}
}
}
int PrefetchUnit::prefetch(TAG blockAddr) {
int index = getLRU();
#ifdef DEBUG
cout << "select LRU buffer #" << index << ", update LRU" << endl;
#endif
stBuf[index].fetch(blockAddr);
updateRank(index);
}
bool PrefetchUnit::search(TAG blockAddr) {
for(int i=0;i<N;i++) {
if(stBuf[i].search(blockAddr) ) {
#ifdef DEBUG
cout << "#" << i << " pop first entry update LRU," << endl;
#endif
stBuf[i].shift();
updateRank(i);
return true;
}
}
// if not found
return false;
}
class Cache {
int blkSize;
int assoc;
int cacheSize;
int numStreamBuf;
int numBlocksInStreamBuf;
int numSets;
int numOffsetBits;
int numSetsBits;
unsigned int setsMask;
Set *s;
PrefetchUnit *preUnit;
int stBufLru;
Cache *nextLevel;
// Stats variables
/*
long int numReads;
long int numReadMisses;
long int numWrites;
long int numWriteMisses;
long int numWriteBacks;
*/
/*********** Stats *****************/
public:
long int numReads;
long int numReadMisses;
long int numReadHits;
long int numWrites;
long int numWriteMisses;
long int numWriteHits;
long int numWriteBacks;
long int numReadFromPreUnit;
long int numL2readMissNotFromPre;
string cacheName;
Cache(int blockSize,int numAssoc,int totalSize,int numStBufs,int numBlocksInStBuf,Cache *c,string name);
int read(TAG addr);
int write(TAG addr);
int fetchInstruction(char *fileName); // May not be necessary . read in the run function possible
int getIndexOfSet(TAG address); // From the whole address mask and return the index of set alone
int run(char *fileName); // Start the simulation
int debugRun(); // For debugging with local values
void printMembers();
void printContent();
void printStats();
};
Cache::Cache(int blockSize,int numAssoc,int totalSize,int numStBufs,int numBlocksInStBuf,Cache *c,string name) {
blkSize = blockSize;
assoc = numAssoc;
cacheSize = totalSize;
numStreamBuf = numStBufs;
numSets = cacheSize/(blkSize * assoc);
numBlocksInStreamBuf = numBlocksInStBuf;
numReads=0;
numReadMisses=0;
numWrites=0;
numWriteMisses=0;
numWriteBacks=0;
numReadFromPreUnit = 0;
numL2readMissNotFromPre = 0;
cacheName = name;
s = new Set[numSets];
int i=0;
for(i=0;i<numSets;i++)
s[i].init(assoc );
nextLevel = c;
if(numStBufs != 0 )
preUnit = new PrefetchUnit(numStBufs,numBlocksInStBuf,blockSize,nextLevel,&numReadFromPreUnit);
else
preUnit = NULL;
numOffsetBits=0;
int tmp = blkSize;
while(tmp) {
tmp = tmp >> 1;
numOffsetBits++;
}
numOffsetBits--;
tmp = numSets;
numSetsBits = 0;
while(tmp) {
tmp = tmp >> 1;
numSetsBits++;
}
numSetsBits--;
setsMask = ( numSets-1 ) << numOffsetBits;
}
void Cache::printContent() {
cout << "===== " << cacheName << " contents =====" << endl;
for(int i=0;i<numSets;i++) {
cout << "Set\t" << dec << i <<":";
// s[i].sort();
s[i].print();
}
if (preUnit != NULL ) {
cout << "===== " << cacheName << "-SB contents =====" << endl;
preUnit->print();
}
/*
for(int i=0;i<numSets;i++) {
cout << "Set :" << dec << i << " ";
s[i].printLru();
}
*/
}
void Cache::printStats() {
string nlcName = "L2"; // Next level cache name is by default L2
double clMissRate;
clMissRate = ((double)(numReadMisses + numWriteMisses))/((double)(numReads+numWrites));
long int nlNumReadsNotFromPre = 0; // next level number of reads not from prefetches
long int nlNumReadMissFromPre = 0; // next level number of read misses from prefetches
long int nlNumWrites = 0;
long int nlNumWriteMiss = 0;
long int nlNumWriteBacks = 0;
long int nlNumPre = 0;
long int nlNumReads = 0;
long int nlNumReadMiss = 0;
double nlMissRate = 0;
long int totalMemTraffic = 0;
if (nextLevel != NULL) {
nlcName = nextLevel->cacheName;
nlNumReadsNotFromPre = nextLevel->numReads - numReadFromPreUnit ;
nlNumReadMissFromPre = nextLevel->numReadMisses - numL2readMissNotFromPre ;
nlNumWrites = nextLevel->numWrites;
nlNumWriteMiss = nextLevel->numWriteMisses;
nlNumReads = nextLevel->numReads;
nlNumReadMiss = nextLevel->numReadMisses;
nlNumPre = nextLevel->numReadFromPreUnit;
nlMissRate = ((double)(numL2readMissNotFromPre))/((double)(nlNumReadsNotFromPre));
nlNumPre = nextLevel->numReadFromPreUnit;
nlNumWriteBacks = nextLevel->numWriteBacks;
totalMemTraffic = nlNumReadMiss + nlNumWriteMiss + nlNumWriteBacks + nlNumPre ;
} else {
totalMemTraffic = numReadMisses + numWriteMisses + numWriteBacks + numReadFromPreUnit ;
}
cout << "===== Simulation results (raw) =====" << endl;
cout << "a. number of " << cacheName <<" reads:\t" << dec << numReads << endl;
cout << "b. number of " << cacheName <<" read misses:\t" << numReadMisses << endl;
cout << "c. number of " << cacheName << " writes:\t" << numWrites << endl;
cout << "d. number of " << cacheName << " write misses:\t" << numWriteMisses << endl;
cout << "e. " << cacheName << " miss rate:\t" << fixed << setprecision(6) << clMissRate << endl;
cout << "f. number of " << cacheName << " writebacks:\t" << numWriteBacks << endl;
cout << "g. number of " << cacheName << " prefetches:\t" << numReadFromPreUnit << endl;
cout << "h. number of " << nlcName << " reads that did not originate from " << cacheName << " prefetches:\t" << nlNumReadsNotFromPre << endl ;
cout << "i. number of " << nlcName << " read misses that did not originate from " << cacheName << " prefetches:\t" << numL2readMissNotFromPre << endl ;
cout << "j. number of " << nlcName << " reads that originated from " << cacheName << " prefetches:\t" << numReadFromPreUnit << endl;
cout << "k. number of " << nlcName << " read misses that originated from " << cacheName << " prefetches:\t" << nlNumReadMissFromPre << endl;
cout << "l. number of " << nlcName << " writes:\t" << nlNumWrites << endl;
cout << "m. number of " << nlcName << " write misses:\t" << nlNumWriteMiss << endl;
if(nextLevel == NULL)
cout << "n. " << nlcName << " miss rate:\t0" << endl;
else
cout << "n. " << nlcName << " miss rate:\t" << nlMissRate << endl;
cout << "o. number of " << nlcName <<" writebacks:\t" << nlNumWriteBacks << endl;
cout << "p. number of " << nlcName << " prefetches:\t" << nlNumPre << endl;
cout << "q. total memory traffic:\t" << totalMemTraffic << endl;
/*
cout << "a. number of " << cacheName << " reads\t" << dec << numReads << endl;
cout << "b. number of " << cacheName << " read misses \t" << dec << numReadMisses << endl;
cout << "c. number of " << cacheName << " writes\t" << dec << numWrites << endl;
cout << "d. number of " << cacheName << " write misses\t" << dec << numWriteMisses << endl;
cout << "f. number of " << cacheName << " writebacks\t" << dec << numWriteBacks << endl;
cout << "number of " << cacheName << " prefetches\t" << dec << numReadFromPreUnit << endl;
cout << "number of " << cacheName << "L2 reads because prefetches\t" << dec << numReadFromPreUnit << endl;
cout << "number of " << cacheName << "L2 read misses that did not originate from prefetches\t" << dec << numL2readMissNotFromPre << endl;
*/
}
int Cache::read(TAG addr) {
int index = getIndexOfSet(addr);
unsigned int tagAddr = addr >> (numOffsetBits+numSetsBits);
unsigned int blockAddr = addr >> numOffsetBits;
numReads++;
int result=-1;
#ifdef DEBUG
cout << " read " << hex << addr<< endl;
cout << cacheName << " read : " << hex << (addr >> numOffsetBits) << "(tag " << tagAddr << ", index " << dec << index << ")" << endl ;
#endif
if(s[index].search(tagAddr,'r')) {
#ifdef DEBUG
cout << cacheName <<" hit" << endl;
#endif
numReadHits++;
result = CACHE_HIT;
} else {
//The following is simultated for retrieval from next level of cache or memory
/***** When replacing if write back is done then make block in prefetch unit as dirty ****/
TAG wbTag;
if ( s[index].place(tagAddr,'r',wbTag ) == VICTIM_WB) {
#ifdef DEBUG
cout << "VICTIM_WB : tag : " << hex << wbTag << endl;
#endif
unsigned int wbBlockNum;
wbBlockNum = ( wbTag << numSetsBits ) | index ;
#ifdef DEBUG
cout << "VICTIM_WB : block : " << hex << wbBlockNum << " in set : " << dec << index << endl;
#endif
numWriteBacks++;
// issue a write to next level cache
if ( preUnit!=NULL) {
if ( preUnit->makeDirty(wbBlockNum) == false ) {
#ifdef DEBUG
cout << "Evicted block not found in stream buffer" << endl;
#endif
}
}
TAG wbAddr;
wbAddr = wbBlockNum << numOffsetBits;
if(nextLevel!=NULL)
nextLevel->write(wbAddr);
}
/***** Check in prefetch unit *****/
if(preUnit != NULL) {
if(preUnit->search(blockAddr)) {
#ifdef DEBUG
cout << cacheName << "-SB" ;
#endif
numReadFromPreUnit++; // one read will be sent to next level from prefetch unit
result = CACHE_HIT;
} else {
#ifdef DEBUG
cout << cacheName << " miss" << endl;
cout << cacheName <<"-SB miss" << endl ;
#endif
numReadMisses++;
if(nextLevel != NULL) {
if ( nextLevel->read(addr) == CACHE_MISS )
numL2readMissNotFromPre++;
}
preUnit->prefetch(blockAddr);
numReadFromPreUnit += numBlocksInStreamBuf;
result = CACHE_MISS;
}
} else {
#ifdef DEBUG
cout << cacheName << " miss" << endl;
#endif
numReadMisses++;
if(nextLevel!=NULL) {
if ( nextLevel->read(addr) == CACHE_MISS )
numL2readMissNotFromPre++;
}
result = CACHE_MISS;
// if(nextLevel!=NULL)
// nextLevel->read(addr);
// get it from next level cache
}
// s[index].print();
// cout<<endl;
//preUnit->print();
}
return result;
}
int Cache::write(TAG addr) {
unsigned int index = getIndexOfSet(addr);
unsigned int tagAddr = addr >> (numOffsetBits+numSetsBits);
unsigned int blockAddr = addr >> numOffsetBits;
numWrites++;
int result = -1;
#ifdef DEBUG
cout << " write " << hex << addr<< endl;
cout << cacheName << " write : " << hex << (addr >> numOffsetBits) << "(tag " << tagAddr << ", index " << dec << index << ")" << endl ;
#endif
if(s[index].search(tagAddr,'w')) {
#ifdef DEBUG
cout << cacheName <<" hit" << endl;
#endif
numWriteHits++;
result = CACHE_HIT;
} else {
/***** When replacing if write back is done then make block in prefetch unit as dirty ****/
TAG wbTag;
// s[index].place(blockAddr,'w',wbTag);
if ( s[index].place(tagAddr,'w',wbTag ) == VICTIM_WB) {
#ifdef DEBUG
cout << "VICTIM_WB : tag : " << hex << wbTag << endl;
#endif
unsigned int wbBlockNum;
wbBlockNum = ( wbTag << numSetsBits ) | index ;
#ifdef DEBUG
cout << "VICTIM_WB : block : " << hex << wbBlockNum << " in set : " << dec << index << endl;
#endif
// issue a write to next level
numWriteBacks++;
if(preUnit != NULL ) {
if ( preUnit->makeDirty(wbBlockNum) == false ) {
#ifdef DEBUG
cout << "Evicted block not found in stream buffer" << endl;
#endif
}
}
TAG wbAddr;
wbAddr = wbBlockNum << numOffsetBits;
if(nextLevel!=NULL)
nextLevel->write(wbAddr);
}
/***** Check in prefetch unit *****/
if(preUnit != NULL) {
if(preUnit->search(blockAddr)) {
#ifdef DEBUG
cout << cacheName << "-SB" ;
#endif
// cout << "found in prefetch unit" << endl;
numReadFromPreUnit++;
result = CACHE_HIT;
} else {
#ifdef DEBUG
cout << cacheName << " miss" << endl;
cout << cacheName <<"-SB miss" << endl ;
#endif
// cout << "not found in prefetch unit.fetching from next level" << endl;
numWriteMisses++;
if(nextLevel != NULL) {
if ( nextLevel->read(addr) == CACHE_MISS ) // l2 cache read that is not from prefetch unit
numL2readMissNotFromPre++;
}
preUnit->prefetch(blockAddr); // it will fetch blockAddr+1 to blockAddr+M
numReadFromPreUnit += numBlocksInStreamBuf;
result = CACHE_MISS;
}
} else {
#ifdef DEBUG
cout << cacheName << " miss" << endl;
#endif
numWriteMisses++;
if(nextLevel!=NULL) {
if ( nextLevel->read(addr) == CACHE_MISS )
numL2readMissNotFromPre++;
}
result = CACHE_MISS;
// get it from next level cache
}
// s[index].print();
// cout<<endl;
//preUnit->print();
//s[index].print();
//cout<<endl;
}
return result;
}
int Cache::fetchInstruction(char *fileName) {
}
int Cache::getIndexOfSet(TAG address) {
unsigned int tmp = address;
tmp = tmp & setsMask;
// cout<<"After masking : " << tmp << endl;
tmp = tmp >> numOffsetBits;
return tmp;
}
int Cache::debugRun() {
TAG seqAddr[9] = { 0x40007a48, 0x40007a4c ,0x40007a58 ,0x40007a48,0x40007a68,0x40007a48 ,0x40007a58 ,0x40007a5c ,0x40007a64 };
char *oper = "wwwwwrrr";
for(int i=0;i<9;i++ ) {
if(oper[i]== 'r')
read(seqAddr[i]);
else
write(seqAddr[i]);
}
}
int Cache::run(char * fileName) {
string line;
ifstream myfile(fileName);
// myfile.open( fileName );
char oper;
char address[9];
// memset(address,0,9);
/*
string s("400382BA");
istringstream iss(s);
TAG addr;
iss >> hex >> addr;
cout << "address : " << hex << addr << endl;*/
TAG addr;
// myfile.open( "gcc_trace.txt" , ios_base::binary);
if (myfile.is_open()) {
// do {
while ( getline (myfile,line) ) {
// getline (myfile,line);
oper = line.at(0);
line.copy(address,(line.size()-2),2);
// cout << line << endl;
istringstream iss(address);
numOpers++;
iss >> hex >> addr;
#ifdef DEBUG
// cout << oper << " " << addr << endl;
cout << "----------------------------------------"<<endl;
cout << "# " << numOpers ;
#endif
if (oper == 'r' )
read(addr);
else if (oper == 'w')
write(addr);
else {
cout << "Error : Invalid operation encountered" << endl;
}
memset(address,0,9);
} //while ( myfile.good() );
myfile.close();
} else
cout << "Unable to open file";
// cout << line << endl;
// cout << "END of Run" << endl;
}
void Cache::printMembers() {
/* cout<< "Block Size : " << blkSize << endl;
cout << "Assoc : " << assoc << endl;
cout << "Cache Size : " << cacheSize << endl;
cout << "Number of stream buffer : " << numStreamBuf << endl;
cout << "Number of sets : " << numSets << endl;
cout << "Number of offset bits : " << numOffsetBits << endl ;
cout << "Number of sets bits : " << numSetsBits << endl;
cout << "Mask to get the set index : " << setsMask << endl;
*/
cout << "===== Simulator configuration =====" << endl;
cout << "BLOCKSIZE:\t" << blkSize << endl;
cout << "L1_SIZE:\t" << cacheSize << endl;
cout << "L1_ASSOC:\t" << assoc << endl;
cout << "L1_PREF_N: 0" << endl;
cout << "L1_PREF_M: 0" << endl;
cout << "L2_SIZE: 0" << endl;
cout << "L2_ASSOC: 0" << endl;
cout << "L2_PREF_N: 0" << endl;
cout << "L2_PREF_M: 0" << endl;
cout << "trace_file:\t" << "gcc_trace.txt" << endl;
}
int StreamBuffer::shift() {
head=(head+1)%numBlks;
TAG nextBlock = blk[tail].getTag() + 1 ;
tail = (tail+1)%numBlks;
nextBlock = nextBlock << numOffsetBits ;
if(nextLevel != NULL) {
#ifdef DEBUG
cout << " prefetch " << nextBlock;
#endif
nextLevel->read( nextBlock );
// *prefReadCounter = (*prefReadCounter) + 1;
}
//Simulating fetching of next block
blk[tail].setTag(nextBlock >> numOffsetBits );
}
int StreamBuffer::fetch(TAG blockNumber) {
TAG bNum;
head=0;
for(tail=0; tail<numBlks; tail++) {
bNum = blockNumber + (tail +1);
bNum = bNum << numOffsetBits ;
#ifdef DEBUG
cout << "prefetch " << hex << bNum << endl;
#endif
if( nextLevel != NULL) {
// *prefReadCounter = (*prefReadCounter) + 1;
nextLevel->read( bNum );
}
blk[tail].setTag( bNum >> numOffsetBits );
blk[tail].setDirty(false);
}
tail--;
}
int main(int argc,char *argv[]) {
int BLOCKSIZE = 0;
int L1_SIZE = 0;
int L1_ASSOC = 0;
int L1_PREF_N = 0;
int L1_PREF_M =0;
int L2_SIZE = 0;
int L2_ASSOC = 0;
int L2_PREF_N = 0;
int L2_PREF_M =0;
char trace_file[50];
if(argc!= 11) {
printf("Error: Need 10 args.\nUsage:./sim_cache <BLOCKSIZE> <L1_SIZE> <L1_ASSOC> <L1_PREF_N> <L1_PREF_M> <L2_SIZE> <L2_ASSOC> <L2_PREF_N> <L2_PREF_M> <trace_file>\n");
return 0 ;
}
BLOCKSIZE = atoi(argv[1]);
L1_SIZE = atoi(argv[2]);
L1_ASSOC = atoi(argv[3]);
L1_PREF_N = atoi(argv[4]);
L1_PREF_M = atoi(argv[5]);
L2_SIZE = atoi(argv[6]);
L2_ASSOC = atoi(argv[7]);
L2_PREF_N = atoi(argv[8]);
L2_PREF_M = atoi(argv[9]);
strcpy(trace_file,argv[10]);
cout << "===== Simulator configuration =====" << endl;
cout << "BLOCKSIZE:\t" << BLOCKSIZE << endl;
cout << "L1_SIZE:\t" << L1_SIZE << endl;
cout << "L1_ASSOC:\t" << L1_ASSOC << endl;
cout << "L1_PREF_N:\t" << L1_PREF_N << endl;
cout << "L1_PREF_M:\t" << L1_PREF_M << endl;
cout << "L2_SIZE:\t" << L2_SIZE << endl;
cout << "L2_ASSOC:\t" << L2_ASSOC << endl;
cout << "L2_PREF_N:\t" << L2_PREF_N << endl;
cout << "L2_PREF_M:\t" << L2_PREF_M << endl;
cout << "trace_file:\t" << trace_file << endl;
/* Cache l2(16,4,8192,4,4,NULL,"L2");
Cache l1(16,1,1024,2,4,&l2,"L1") ;
*/
Cache *l1,*l2;
if ( L2_SIZE != 0 ) {
l2 = new Cache(BLOCKSIZE,L2_ASSOC,L2_SIZE,L2_PREF_N,L2_PREF_M,NULL,"L2");
l1 = new Cache(BLOCKSIZE,L1_ASSOC,L1_SIZE,L1_PREF_N,L1_PREF_M,l2,"L1");
} else {
l1 = new Cache(BLOCKSIZE,L1_ASSOC,L1_SIZE,L1_PREF_N,L1_PREF_M,NULL,"L1");
}
//Cache l1(16,2,1024,0,0,NULL,"L1") ;
//For debugging
// Cache l1(4,2,32,2,8,NULL,"L1") ;
//End of debugging
// cout<< l1.getIndexOfSet(0x40007a64) << endl;
l1->run( trace_file );
// l1.debugRun();
l1->printContent();
if ( L2_SIZE != 0 )
l2->printContent();
l1->printStats();
// l2.printStats();
// cout<<"chk" << endl;
//sleep(1);
}
| true |
370fff0baf6eb0c78621ab61b0a6faa98cc031de | C++ | naprelsky/ame.example | /NaucaFile/Coefficient.cpp | UTF-8 | 1,084 | 3.03125 | 3 | [] | no_license | #include "stdafx.h"
#include "Coefficient.h"
Coefficient::Coefficient(double min, double max, double freq)
{
secondsPass = 0;
value = 0;
threadWorking = false;
aborted = false;
minValue = min;
maxValue = max;
frequency = freq;
std::thread valueThread(&Coefficient::ChangeValueThread, this);
valueThread.detach();
}
Coefficient::~Coefficient()
{
aborted = true;
}
void Coefficient::StartChanging()
{
threadWorking = true;
}
void Coefficient::StopChanging()
{
threadWorking = false;
}
void Coefficient::SetValue(double val)
{
if (threadWorking) {
throw "";
}
else {
value = val;
}
}
bool Coefficient::IsWorking()
{
return threadWorking;
}
double Coefficient::GetValue()
{
return value;
}
void Coefficient::ChangeValueThread()
{
while (true) {
if (aborted) {
return;
}
if (threadWorking) {
double p = (maxValue - minValue) / 2;
value = p * sin(frequency * secondsPass) + (minValue + p);
secondsPass++;
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
} | true |
c59e519e41044de65fa70f512dff16582f046399 | C++ | theSquaredError/Algorithms | /backtracking/N-queens.cpp | UTF-8 | 1,194 | 3.296875 | 3 | [] | no_license | /*
https://www.geeksforgeeks.org/n-queen-problem-backtracking-3/
*/
#include <iostream>
#include <vector>
using namespace std;
void printBoard(int n, int board[][20]){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<board[i][j]<<" ";
}
cout<<endl;
}
}
bool canPlace(int board[][20], int n, int x, int y){
//column
for(int k=0;k<x;k++){
if(board[k][y] == 1){
return false;
}
}
//left Diag
int i = x;
int j = y;
while(i>=0 and j>=0){
if(board[i][j] == 1){
return false;
}
i--;j--;
}
//Right Diag
i=x;
j=y;
while(i>=0 and j<n){
if(board[i][j] == 1){
return false;
}
i--;j++;
}
return true;
}
bool solveNQueen(int n, int board[][20], int i){
//base
if(i==n){
// print the board
printBoard(n, board);
return true;
}
//rec case
// try to place a queen in every row
for(int j=0;j<n;j++){
// whether the current i,j is safe or not
if(canPlace(board,n,i,j)){
board[i][j] = 1;
bool success = solveNQueen(n, board, i+1);
if(success){
return true;
}
//backtrack
board[i][j] = 0;
}
}
return false;
}
int main(){
int board[20][20] = {0};
int n;
//cin>>n;
solveNQueen(4,board,1);
return 0;
} | true |
b90ebe3e0ee783fccc0fdf92fdf6f7666e9d7173 | C++ | KevenGe/LeetCode-Solutions | /problemset/945. 使数组唯一的最小增量/solution.cpp | UTF-8 | 1,168 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <limits.h>
using namespace std;
// class Solution
// {
// public:
// int minIncrementForUnique(vector<int> &A)
// {
// sort(A.begin(), A.end());
// int stand = INT_MIN;
// int ans = 0;
// for (int i = 0; i < A.size(); ++i)
// {
// while (A[i] <= stand)
// {
// A[i]++;
// ans++;
// }
// stand = A[i];
// }
// return ans;
// }
// };
class Solution
{
public:
int minIncrementForUnique(vector<int> &A)
{
int dp[80000];
fill(dp, dp + 80000, 0);
for (int a : A)
{
dp[a]++;
}
int count = 0;
int ans = 0;
for (int i = 0; i < 80000; ++i)
{
if (dp[i] >= 2)
{
count += dp[i] - 1;
ans -= i * (dp[i] - 1);
}
else if (dp[i] == 0 && count >0)
{
count --;
ans += i;
}
}
return ans;
}
};
int main()
{
return 0;
} | true |
78389baa02940a871058dfcc3c08fa7eb73ab035 | C++ | C-B0T/FirmwarePropulsion2017 | /HardwareAbstraction/inc/GPIO.hpp | UTF-8 | 3,642 | 3.078125 | 3 | [] | no_license | /**
* @file GPIO.hpp
* @author Kevin WYSOCKI
* @date 8 nov. 2016
* @brief GPIO Abstraction Class
*/
#ifndef INC_GPIO_HPP_
#define INC_GPIO_HPP_
#include "stm32f4xx.h"
#include "Event.hpp"
/*----------------------------------------------------------------------------*/
/* Definitions */
/*----------------------------------------------------------------------------*/
/**
* @brief GPIO Definition structure
* Used to define GPIO port, pin, mode and, in case of input,
* specific necessary definitions to initialize external interrupt
*/
typedef struct
{
struct Pin
{
GPIO_TypeDef * PORT; /**< GPIO Port */
uint16_t PIN; /**< GPIO Pin number */
GPIOMode_TypeDef MODE; /**< GPIO Mode */
}IO;
// Interrupt definitions - INPUTS ONLY
struct Interrupt
{
uint8_t PORTSOURCE; /**< Interrupt Port */
uint8_t PINSOURCE; /**< Interrupt Pin */
uint32_t LINE; /**< Interrupt Line */
uint32_t TRIGGER; /**< Interrupt trigger */
uint8_t PRIORITY; /**< Interrupt priority, 0 to 15, 0 is the highest priority */
uint8_t CHANNEL; /**< Interrupt IRQ Channel */
}INT;
}GPIO_DEF;
/*----------------------------------------------------------------------------*/
/* Class */
/*----------------------------------------------------------------------------*/
/**
* @namespace HAL
*/
namespace HAL
{
/**
* @class GPIO
* @brief GPIO Abstraction class
*
* HOWTO :
* - Get GPIO instance with GPIO::GetInstance()
* - Get() and Set() can be use to retrieve or set GPIO state
* - InterruptCallback can be used to set a function called when interrupt is raised
*/
class GPIO
{
public:
/**
* @brief GPIO Identifier list
*/
enum ID
{
GPIO0, //!< DIG_IN2
GPIO1, //!< PWM_OUT1
GPIO2, //!< DIG_OUT7
GPIO3, //!< DIG_IN3
GPIO4, //!< PWM_OUT3
GPIO5, //!< DIG_OUT8
GPIO6, //!< LED1
GPIO7, //!< LED2
GPIO8, //!< LED3
GPIO9, //!< LED4
GPIO_MAX
};
/**
* @brief GPIO State
*/
enum State
{
Low = 0,//!< Logic '0'
High //!< Logic '1'
};
/**
* @brief Get instance method
* @param id : GPIO ID
* @return GPIO instance
*/
static GPIO* GetInstance (enum ID id);
/**
* @brief Return GPIO ID
* @return ID
*/
enum ID GetID()
{
return this->id;
}
/**
* @brief Return GPIO interrupt state
* @return true if interrupt is enabled, false else
*/
bool GetInterruptState ()
{
return this->intState;
}
/**
* @brief Return GPIO state
* @return Low if GPIO is '0' logic, High else
*/
enum State Get();
/**
* @brief Set GPIO state (if GPIO is an output)
* @param state : Low if GPIO must be '0' logic, High else
*/
void Set(enum State state);
/**
* @brief Toggle GPIO (if GPIO is an output)
*/
void Toggle();
/**
* @brief State changed event
* INPUT ONLY !
*/
Utils::Event StateChanged;
/**
* @private
* @brief Internal interrupt callback. DO NOT CALL !!
*/
void INTERNAL_InterruptCallback ();
private:
/**
* @private
* @brief GPIO private constructor
* @param id : GPIO ID
*/
GPIO (enum ID id);
/**
* @private
* @brief GPIO ID
*/
enum ID id;
/**
* @private
* @brief Interrupt state
*/
bool intState;
/**
* @private
* @brief GPIO definition
*/
GPIO_DEF def;
};
}
#endif /* INC_GPIO_HPP_ */
| true |
99b0e4d8cfe0130e7b40a22c9019f12845282aef | C++ | Polandr/DE_algo | /DE/src/parameters.cpp | UTF-8 | 1,476 | 2.890625 | 3 | [] | no_license | #include <parameters.h>
// Parameters for algorithm:
int Parameters::population_size = 1;
int Parameters::problem_dimension = 1;
Stop_condition Parameters::stop_condition = Iter_num;
int Parameters::max_iter_num = 1;
double Parameters::max_evolution_time = 0;
int Parameters::n_change_iter_num = 1;
Fitness_type Parameters::exact_solution = 0;
double Parameters::epsilon = 0;
// Parameters for operators:
Mutation Parameters::mutation = Default_mut;
Crossover Parameters::crossover = Default_cros;
F_type Parameters::F1 = 0;
F_type Parameters::F2 = 0;
std::vector<double> Parameters::A;
// Parameters for parallel algorithm:
// Part of population to be exchanged (in [0,1]):
double Parameters::exchange_part = 0;
// Number of iterations between exchanges, if it's 0 than there are no exchanges in the algorihm:
int Parameters::exchange_iter = 0;
Exchange_strategy Parameters::exchange_strategy = Rotation;
Exchange_select_strategy Parameters::exchange_select_strategy = Random;
void Parameters::init()
{
//population_size = 25;
population_size = 100;
problem_dimension = 1024;
stop_condition = Iter_num | Time_out;
max_iter_num = 100;
max_evolution_time = 3000;
n_change_iter_num = 100;
exact_solution = 0;
epsilon = 1e-1;
mutation = DE_1;
crossover = DE;
F1 = 0.55;
F2 = 0.55;
std::vector<double> alpha(problem_dimension,0.05);
A = alpha;
exchange_part = 0.5;
exchange_iter = 10;
exchange_strategy = Rotation;
exchange_select_strategy = Random;
}
| true |
df017c8c7dadd3652e636de14393f70e10619581 | C++ | yashparmar15/Cpp-Codes | /Repeated_String_Match.cpp | UTF-8 | 2,734 | 3.734375 | 4 | [] | no_license | /*Given two strings A and B, find the minimum number of times A has to be repeated such that B becomes a substring of the repeated A. If B cannot be a substring of A no matter how many times it is repeated, return -1.
Example 1:
Input: A = "abcd", B = "cdabcdab"
Output: 3
Explanation: After repeating A three times,
we get "abcdabcdabcd".
Example 2:
Input: A = "aa", B = "a"
Output: 1
Explanation: B is already a substring of A.
Your Task:
You don't need to read input or print anything. Complete the function repeatedStringMatch() which takes strings A and B as input parameters and returns the minimum number of operations to complete the task. If it is not possible then return -1.
Expected Time Complexity: O(|A| * |B|)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ |A|, |B| ≤ 103*/
class Solution{
public:
int repeatedStringMatch(string A, string B)
{
// Your code goes here
if(A == B) return 1;
bool temp = false;
if(B.size() < A.size()){
for(int i = 0 ; i <= A.size() - B.size() ; i++){
if(A[i] == B[0]){
int j = 0;
bool flag = true;
while(j < B.size()){
if(A[i + j] != B[j]){
flag = false;
break;
}
j++;
}
if(flag) return 1;
}
}
}
// int req = B.size() / A.size();
// if(B.size() % A.size()) req++;
// string temp = A;
int ans = INT_MAX;
for(int i = 0 ; i < A.size() ; i++){
if(A[i] == B[0]){
int j = 0;
bool flag = true;
while(i + j < A.size() and j < B.size()){
if(A[i + j] != B[j]){
flag = false;
break;
}
j++;
}
if(flag){
int res = 1;
bool check = false;
while(j < B.size()){
int k = 0;
while(k < A.size() and j < B.size()){
if(A[k] != B[j]){
check = true;
break;
}
k++;
j++;
}
if(check) break;
res++;
}
if(!check) ans = min(ans,res);
}
}
}
return ans == INT_MAX ? -1 : ans;
}
};
| true |
92e616ceab709851df0c3bd034da7ea31bced1aa | C++ | darienmiller88/Snake | /SnakeHead.cpp | UTF-8 | 2,026 | 3.5 | 4 | [] | no_license | #include "SnakeHead.h"
SnakeHead::SnakeHead(char snakeChar, int initX, int initY) : SnakeSegment(snakeChar, initX, initY), xSpeed(0), ySpeed(0){
}
void SnakeHead::update() {
xPrevious = x;
yPrevious = y;
//the x and y of the snakehead will change in accordance to an x and y speed value. So if the x speed is changed to 5,
//the snake will move along the x axis by 5 units every time update() is called.
x += xSpeed;
y += ySpeed;
}
//This function is simply for fun + cosmetics. Once the users game has ended, cause the head of the snake to flicker
//on and off
void SnakeHead::flickerSnakeHead(){
for (size_t i = 0; i < 3; i++) {
gotoxy(xPrevious, yPrevious);
std::cout << " ";
Sleep(200);
gotoxy(xPrevious, yPrevious);
std::cout << snakeChar;
Sleep(200);
}
}
void SnakeHead::phaseThroughWall(int rightBorder, int bottomBorder){
if (x == rightBorder)
x = 1;
else if (x == 0)
x = rightBorder - 1;
else if (y == bottomBorder)
y = 1;
else if (y == 0)
y = bottomBorder - 1;
}
void SnakeHead::move() {
char input = ' ';
if (_kbhit()) {
input = _getch();
//in order to prevent the user from going backwards, the snake head can only move in a given direction so long as
//the direction the user inputs isn't opposite of where the snake is moving. For example, a snake head can only move
//down as long as it IS NOT currently moving up.
if (input == UP and direction != DOWN)
ySpeed = -1, xSpeed = 0, direction = UP;
else if (input == DOWN and direction != UP)
ySpeed = 1, xSpeed = 0, direction = DOWN;
else if (input == RIGHT and direction != LEFT)
xSpeed = 1, ySpeed = 0, direction = RIGHT;
else if (input == LEFT and direction != RIGHT)
xSpeed = -1, ySpeed = 0, direction = LEFT;
}
update();
}
bool SnakeHead::collidedWithWall(int rightBorder, int bottomBorder){
if (x >= rightBorder or x == 0 or y == 0 or y > bottomBorder) {
flickerSnakeHead();
return true;
}
return false;
}
| true |
8424dc2646712b6985ebae2009c41eb22c89b6ba | C++ | liadeliyahu11/LiadnRaz | /LiadnRaz/checkValid.cpp | UTF-8 | 338 | 2.796875 | 3 | [] | no_license | #include<iostream>
#include<string>
#include "valid.h"
using namespace std;
void main()
{
Valid check;
string username = "Admin";
string password = "Aa231";
cout << "username is correct ?" << check.isUsernameValid(username) << endl;
cout << "password is correct ?" << check.isPasswordValid(password) << endl;
system("pause");
} | true |
3ed4350769ca800b7f1ad7d030ab7629c186277f | C++ | LuckPsyduck/Data-Structure-Example | /数据结构-C/Other/Example&矩阵的压缩存储.cpp | GB18030 | 1,050 | 3.015625 | 3 | [] | no_license | // ѹ洢.cpp : ̨Ӧóڵ㡣
//
#include "stdafx.h"
#include"Matrix.h"
int main()
{
TSMtrix A, B, C;
printf("A: ");
CreateSMatrix(A);
PrintSMatrix(A);
CopySMatrix(A, B);
printf("ɾAƾB:\n");
PrintSMatrix(B);
DestroySMatrix(B);
printf("پB: \n");
PrintSMatrix(B);
printf("B2:(AУͬУзֱΪ%d,%d)\n", A.mu, A.nu);
CreateSMatrix(B);
PrintSMatrix(B);
AddSMatrix(A, B, C);
printf("C1(A+B):\n");
PrintSMatrix(C);
SubSMatrix(A, B, C);
printf("C2(A-B):\n");
PrintSMatrix(C);
TransposeSMatrix(A, C);
printf("C3(Aת):\n");
PrintSMatrix(C);
printf("A2: ");
CreateSMatrix(A);
PrintSMatrix(A);
printf("B3:(ӦA2ͬ=%d)\n", A.nu);
CreateSMatrix(B);
PrintSMatrix(B);
#ifndef FLAG
MultSMatrix(A, B, C);
#else
MultSMatrix1(A, B, C);
#endif // !FLAG
printf("C5(A*B):\n");
PrintSMatrix(C);
return 0;
}
| true |
c2c615a065b4eedb0760973752db5096fd46f22d | C++ | Yandren/Pet | /Scrap/Log.h | UTF-8 | 563 | 2.609375 | 3 | [] | no_license | #ifndef LOG_H
#define LOG_H
#include <Windows.h>
#include "MemManager.h"
#include <fstream>
const int LOG_APP=1;
const int LOG_CLIENT=2;
const int LOG_SERVER=4;
const int LOG_USER=8;
#define MAX_LOG_STRINGS 256
class CLog
{
protected:
CLog();
std::ofstream appLog;
std::ofstream clientLog;
std::ofstream serverLog;
std::string logStrings[MAX_LOG_STRINGS];
bool LoadStrings();
public:
static CLog &Get();
bool Init();
void Shutdown();
void Write(int target, const char *msg, ...);
void Write(int target, unsigned long msgID, ...);
};
#endif | true |