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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
b06929e766f910e6a00909896073dbdec1528d14 | C++ | yunfei-he/Udacity | /CarND-Path-Planning-Project/src/PathPlanner.cpp | UTF-8 | 7,322 | 2.953125 | 3 | [
"MIT"
] | permissive | #include "PathPlanner.h"
#include <iostream>
#include "const.h"
#include "Helper.h"
#include "spline.h"
PathPlanner::PathPlanner() {
reference_car_.speed_ = 0.0;
reference_car_.d_ = 1.5 * LANE_WIDTH; //put car in the middle
}
void PathPlanner::SetWayPoints(const std::vector<double>& xs, const std::vector<double>& ys, const std::vector<double>& ss,
const std::vector<double>& dxs, const std::vector<double>& dys) {
waypoint_xs_ = xs;
waypoint_ys_ = ys;
waypoint_ss_ = ss;
waypoint_dxs_ = dxs;
waypoint_dys_ = dys;
}
void PathPlanner::GetPath(const std::vector<Vehicle>& traffic, const Vehicle& ego_car,
const std::vector<double>& previous_xs, const std::vector<double>& previous_ys,
double previous_end_s, double previous_end_d,
std::vector<double> *xs, std::vector<double> *ys) {
traffic_ = traffic;
pre_xs_ = previous_xs;
pre_ys_ = previous_ys;
if (previous_xs.empty()) {
reference_car_ = ego_car;
//reference_car_.speed_ = SPEED_LIMIT / 2;
} else {
reference_car_.s_ = previous_end_s;
reference_car_.d_ = previous_end_d;
}
// take previous leftover
for (int i = 0; i < previous_xs.size(); ++i) {
xs->push_back(previous_xs[i]);
ys->push_back(previous_ys[i]);
}
// calcualte new points
CalcNewPoint(xs, ys);
}
void PathPlanner::CalcNewPoint(std::vector<double> *xs, std::vector<double> *ys) {
// calculate new speed and new lane
double new_speed = reference_car_.speed_;
int new_lane = GetLaneNumber(reference_car_.d_);
Vehicle v = FindNearestVehicleAhead(new_lane);
double delta_s = v.s_ - reference_car_.s_;
// if safe to go straight
if (delta_s > SAFETY_GAP_STRAIGHT_VEHICLE_AHEAD) {
new_speed = std::min(new_speed + SPEED_CHANGE_PER_CIRCLE, SPEED_LIMIT);
} else {
double left_s;
bool can_change_to_left = CanChangeToLeftLane(&left_s);
double right_s;
bool can_change_to_right = CanChangeToRightLane(&right_s);
if (can_change_to_left && can_change_to_right) {
if (left_s > right_s) {
new_lane -= 1;
} else {
new_lane += 1;
}
} else if (can_change_to_left) {
new_lane -= 1;
} else if (can_change_to_right) {
new_lane += 1;
} else if (delta_s < SAFETY_GAP_STRAIGHT_VEHICLE_AHEAD / 2) {
new_speed -= SPEED_CHANGE_PER_CIRCLE;
} else {
if (new_speed >= v.speed_) {
new_speed -= std::min((new_speed - v.speed_), SPEED_CHANGE_PER_CIRCLE);
}
}
}
std::cout << std::endl << "new speed:" << new_speed << std::endl;
reference_car_.speed_ = new_speed;
// calculate spline line starting x, y and yaw
double start_x = reference_car_.x_;
double start_y = reference_car_.y_;
double start_yaw = reference_car_.yaw_;
std::vector<double> v_x;
std::vector<double> v_y;
if (pre_xs_.size() < 2) {
v_x.push_back(start_x - cos(start_yaw));
v_x.push_back(start_x);
v_y.push_back(start_y - sin(start_yaw));
v_y.push_back(start_y);
} else {
size_t pre_size = pre_xs_.size();
v_x.push_back(pre_xs_[pre_size-2]);
v_x.push_back(pre_xs_[pre_size-1]);
v_y.push_back(pre_ys_[pre_size-2]);
v_y.push_back(pre_ys_[pre_size-1]);
start_x = pre_xs_.back();
start_y = pre_ys_.back();
start_yaw = atan2(pre_ys_[pre_size-1] - pre_ys_[pre_size-2], pre_xs_[pre_size-1] - pre_xs_[pre_size-2]);
}
// add evenly 30 spaces points from starting point
for (int i = 1; i <= 3; ++i) {
std::vector<double> xy = Helper::getXY(reference_car_.s_ + 30.0 * i, LANE_WIDTH * (0.5 + new_lane),
waypoint_ss_, waypoint_xs_, waypoint_ys_);
v_x.push_back(xy[0]);
v_y.push_back(xy[1]);
}
// shift x,y to car local frame
for (int i = 0; i < v_x.size(); ++i) {
double shift_x = v_x[i] - start_x;
double shift_y = v_y[i] - start_y;
v_x[i] = shift_x * cos(-start_yaw) - shift_y * sin(-start_yaw);
v_y[i] = shift_x * sin(-start_yaw) + shift_y * cos(-start_yaw);
}
tk::spline ts;
ts.set_points(v_x, v_y);
// add new points until it reachs 50
double target_x = 30.0;
double target_y = ts(target_x);
double target_dist = std::hypot(target_x, target_y);
double N = target_dist / (TIME_PER_CIRCLE * new_speed);
double delta_x = target_x / N;
for (int i = 1; i <= POINT_TO_PREDICT - pre_xs_.size(); ++i) {
double x = delta_x * i;
double y = ts(x);
// transfer local frame to global frame
double new_x = start_x + x * cos(start_yaw) - y * sin(start_yaw);
double new_y = start_y + x * sin(start_yaw) + y * cos(start_yaw);
std::cout << "new x, y: " << new_x << "," << new_y << std::endl;
xs->push_back(new_x);
ys->push_back(new_y);
}
}
Vehicle PathPlanner::FindNearestVehicleAhead(int lane) {
Vehicle ans;
ans.s_ = std::numeric_limits<float>::max();
ans.speed_ = 0;
for (const auto& v : traffic_) {
if (lane == GetLaneNumber(v.d_)) {
double s = v.s_;
s += v.speed_ * TIME_PER_CIRCLE * pre_xs_.size();
if (s > reference_car_.s_ && s < ans.s_) {
ans.s_ = s;
ans.speed_ = v.speed_;
}
}
}
return ans;
}
Vehicle PathPlanner::FindNearestVehicleBehind(int lane) {
Vehicle ans;
ans.s_ = -100;
ans.speed_ = 0;
for (const auto& v : traffic_) {
if (lane == GetLaneNumber(v.d_)) {
double s = v.s_;
s += v.speed_ * TIME_PER_CIRCLE * pre_xs_.size();
if (s < reference_car_.s_ && s > ans.s_) {
ans.s_ = s;
}
}
}
return ans;
}
int PathPlanner::GetLaneNumber(double d) {
if (d <= LANE_WIDTH) {
return 0;
} else if (d >= 2 * LANE_WIDTH) {
return 2;
} else {
return 1;
}
}
bool PathPlanner::CanGoStraight() {
int lane_num = GetLaneNumber(reference_car_.d_);
Vehicle v = FindNearestVehicleAhead(lane_num);
return (v.s_ - reference_car_.s_) >= SAFETY_GAP_STRAIGHT_VEHICLE_AHEAD;
}
bool PathPlanner::CanChangeToLeftLane(double *s) {
int lane_num = GetLaneNumber(reference_car_.d_);
if (lane_num == 0) {
return false;
}
Vehicle v = FindNearestVehicleAhead(lane_num-1);
if ((v.s_ - reference_car_.s_) < SAFETY_GAP_CHANGELANE_VEHICLE_AHEAD) {
return false;
}
*s = v.s_;
v = FindNearestVehicleBehind(lane_num-1);
return reference_car_.s_ - v.s_ >= SAFETY_GAP_VEHICLE_BEHIND;
}
bool PathPlanner::CanChangeToRightLane(double *s) {
int lane_num = GetLaneNumber(reference_car_.d_);
if (lane_num == 2) {
return false;
}
Vehicle v = FindNearestVehicleAhead(lane_num + 1);
if ((v.s_ - reference_car_.s_) < SAFETY_GAP_CHANGELANE_VEHICLE_AHEAD) {
return false;
}
*s = v.s_;
v = FindNearestVehicleBehind(lane_num + 1);
return reference_car_.s_ - v.s_ >= SAFETY_GAP_VEHICLE_BEHIND;
}
| true |
226520bd8dacb2ec58b5c16dc67e086345de3b8f | C++ | A-renderer/Viewing-and-Clipping | /main.cpp | UTF-8 | 4,984 | 2.59375 | 3 | [] | no_license | #include "FrameBuffer.cpp"
#include <cstring>
#include <termios.h>
#include <fstream>
#include "assets.h"
using namespace std;
FrameBuffer FB;
bool quit = false;
vector<Polygon> map;
Window window;
int key;
int kbhit(void);
Polygon matrixToPolygon(int object[][2], int col);
void drawMap();
void redraw();
void move(int key);
View view;
Polygon map_border = matrixToPolygon(border,sizeof(border)/sizeof(*border));
Polygon p_sumatra = matrixToPolygon(sumatra,sizeof(sumatra)/sizeof(*sumatra));
Polygon p_kalimantan = matrixToPolygon(kalimantan,sizeof(kalimantan)/sizeof(*kalimantan));
Polygon p_sulawesi = matrixToPolygon(sulawesi,sizeof(sulawesi)/sizeof(*sulawesi));
Polygon p_papua = matrixToPolygon(papua,sizeof(papua)/sizeof(*papua));
Polygon p_jawa = matrixToPolygon(jawa,sizeof(jawa)/sizeof(*jawa));
int main() {
// Adjust positions of the islands
p_sumatra.moveDown(10);
p_jawa.scale(1.8);
p_jawa.moveDown(265);
p_jawa.moveRight(170);
p_kalimantan.scale(1.55);
p_kalimantan.moveRight(150);
p_kalimantan.moveDown(50);
p_sulawesi.scale(1.25);
p_sulawesi.moveRight(320);
p_sulawesi.moveDown(100);
p_papua.scale(2);
p_papua.moveRight(430);
p_papua.moveDown(160);
map.push_back(p_sumatra);
map.push_back(p_jawa);
map.push_back(p_kalimantan);
map.push_back(p_sulawesi);
map.push_back(p_papua);
system("clear");
drawMap();
FB.cleararea(view.P1.x,view.P1.y,view.P2.x,view.P2.y);
FB.drawPolygon(view.pol,255,255,255,0);
FB.drawWindow(window,255,255,255,0);
redraw();
while(!quit){
if(kbhit()){
key=getchar();
//PANGGIL FUNGSI UNTUK REDRAW MOVEMENT
move(key);
}
}
//system("clear");
return 0;
}
int kbhit(void) {
struct termios oldt, newt;
int ch;
int oldf;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);
if(ch != EOF) {
ungetc(ch, stdin);
return 1;
}
return 0;
}
Polygon matrixToPolygon(int object[][2], int col) {
vector<Point> points;
points.clear();
for(int i=0;i<col;i++) {
points.push_back(Point(object[i][0],object[i][1]));
}
return Polygon(points);
}
void drawMap() {
//FUNGSI RASTER SCAN UDA MANGGIL DRAWPOLYGON JD GA PERLU 2 KALI
FB.rasterScan(map_border,135, 206, 235, 0, 0, 599);
FB.rasterScan(p_sumatra,0, 100, 0, 0, p_sumatra.getMinY(), p_sumatra.getMaxY());
//FB.drawPolygon(p_jawa,0,100,0,0);
FB.rasterScan(p_jawa,0, 100, 0, 0, p_jawa.getMinY(), p_jawa.getMaxY());
FB.rasterScan(p_kalimantan,0, 100, 0, 0, p_kalimantan.getMinY(), p_kalimantan.getMaxY());
FB.rasterScan(p_sulawesi,0, 100, 0, 0, p_sulawesi.getMinY(), p_sulawesi.getMaxY());
//FB.drawPolygon(p_papua,0,100,0,0);
FB.rasterScan(p_papua,0, 100, 0, 0, p_papua.getMinY(), p_papua.getMaxY());
}
void redraw() { //untuk redraw view
vector<Polygon> temp;
for(int i=0;i<map.size();i++) {
int j=0;
bool found = false;
while(j<map[i].e.size() && !found) {
if(not(map[i].e[j].x<window.getTopLeft().x || map[i].e[j].y<window.getTopLeft().y
|| map[i].e[j].y>window.getBottomRight().y || map[i].e[j].x>window.getBottomRight().x)) {
found = true;
temp.push_back(map[i]);
}
j++;
}
}
if(!window.lines.empty()) {
FB.cleararea(view.P1.x,view.P1.y,view.P2.x,view.P2.y);
}
if(!temp.empty()) {
window.clipAllPolygon(temp);
if(!window.lines.empty()) {
view.setViewLines(window);
//FB.drawView(view,0,100,0,0);
FB.renderView(window, view);
//FB.rasterView(view,0,100,0,0,1,401);
view.lines.clear();
window.lines.clear();
temp.clear();
}
}
}
void move(int key) {
//system("clear");
//int border[][2]={{0,0},{599,0},{599,400},{0,400}};
int i = 0;
if(key=='w'){
while(i < 10 && window.square.getMinY() > 0) {
window.moveUp(1);
i++;
}
}
else if(key=='a'){
while(i < 10 && window.square.getMinX() > 0) {
window.moveLeft(1);
i++;
}
}
else if(key=='d'){
while(i < 10 && window.square.getMaxX() < 599) {
window.moveRight(1);
i++;
}
}
else if(key=='s'){
while(i < 10 && window.square.getMaxY() < 400) {
window.moveDown(1);
i++;
}
}
else if(key=='m') {
if (window.square.getMinY()>0 && window.square.getMinX() > 0 && window.square.getMaxX() < 599 && window.square.getMaxY() < 400)
window.zoomOut(1.01);
}
else if(key=='k') {
if (window.square.getMinY()>0 && window.square.getMinX() > 0 && window.square.getMaxX() < 599 && window.square.getMaxY() < 400)
window.zoomIn(1.01);
}
else if(key=='q') {
// OTHER KEYS
quit=true;
system("clear");
}
if (key=='a' || key=='s' || key=='d' || key=='w' || key=='k' || key=='m'){
//menggambar ulang peta
drawMap();
//menggambar ulang window & view
FB.cleararea(view.P1.x,view.P1.y,view.P2.x,view.P2.y);
FB.drawPolygon(view.pol,255,255,255,0);
FB.drawWindow(window,255,255,255,0);
redraw();
}
} | true |
bcc521cc088e152d2d4d652abf84a2f5709fa742 | C++ | jessiepao14/CPSC350_Assignment5 | /Student.hpp | UTF-8 | 1,385 | 3.28125 | 3 | [] | no_license | #ifndef _STUDENT_HPP_
#define _STUDENT_HPP_
#include <iostream>
#include <fstream>
using namespace std;
class Student
{
private:
int id;
string name;
string level;
string major;
double gpa;
int advisorId;
public:
Student();
Student(int idNumber, string studentName, string studentLevel, string studentMajor, double studentGPA, int studentAdvisorID);
//getter
int getID() { return id; }
string getName() { return name; }
string getLevel() { return level; }
string getMajor() { return major; }
double getGPA() { return gpa; }
int getAdvisorID() { return advisorId; }
//setter
void setID(int studentID) { id = studentID; }
void setName(string studentName) { name = studentName; }
void setLevel(string studentLevel) { level = studentLevel; }
void setMajor(string studentMajor) { major = studentMajor; }
void setGPA(double studentGPA) { gpa = studentGPA; }
void setAdvisorID(int studentAdvisorID) { advisorId = studentAdvisorID; }
void writeToFile(string fileName);
//void printStudentInformation();
bool operator<(const Student &s);
bool operator>(const Student &s);
bool operator<=(const Student &s);
bool operator>=(const Student &s);
bool operator!=(const Student &s);
bool operator==(const Student &s);
int operator+(const Student &s1) const;
};
#endif | true |
7a81bf29eb520f23b8cc67ad85c1a3eae318d163 | C++ | anstjaos/KIT-Homeworks | /2학년/자료구조2/1차과제/3/main.cpp | UHC | 398 | 3 | 3 | [] | no_license | /* --- ڿ binary search tree --- */
/* --- ۼ: 蹮, й: 20130162 --- */
/* --- 333 lines, ۼ: 2017. 9. 9. --- */
#include "Tree.h"
void main()
{
Tree<string> t;
string input;
cout << "ڿ Էϼ ( 0) : ";
while (1)
{
cin >> input;
if (input == "0") break;
t.createNode(input);
}
t.showAll();
} | true |
7d05f7c7858d44fccb044ed09d31694456f3ae24 | C++ | Itsposs/cppprimer | /ch09/vector3.cc | UTF-8 | 624 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include <chrono>
#include <vector>
int main(int argc,char *argv[])
{
using namespace std::chrono;
auto begin = high_resolution_clock::now();
std::vector<int> ivec;
for(size_t ix = 0;ix != 24;++ix)
{
ivec.push_back(ix);
}
ivec.reserve(48);
std::cout << "size:" << ivec.size()
<< "capacity:" << ivec.capacity()
<< std::endl;
for(const auto &val : ivec)
{
std::cout << val << " ";
}
std::cout << std::endl;
// TODO
auto end = high_resolution_clock::now();
std::cout << "time:" << duration_cast<milliseconds> (end - begin).count()
<< "ms." << std::endl;
return 0;
}
| true |
9fe3fa543b2eee0cf426b15189919bbbfdd60037 | C++ | jainsourav43/DSA | /CP/jfhtf.cpp | UTF-8 | 1,801 | 3.15625 | 3 | [] | no_license | #include<iostream>
#include<time.h>
#include<cmath>
#include <stdlib.h>
using namespace std;
typedef
struct node
{
int data;
struct node *next;
} *lptr;
void display1(lptr l)
{
lptr t=l;
cout<<t->data<<" ";
t=t->next;
while(t!=l)
{
cout<<t->data<<" ";
t=t->next;
}cout<<endl;
}
void display(lptr l,int n)
{
lptr t=l;int j;
for(j=0;j<=n;j++)
{
cout<<t->data<<" ";
t=t->next;
}
cout<<endl;
}
void add_end(lptr l,int d)
{
lptr t=l;
while(t->next!=l)
{
t=t->next;
}
t->next=new struct node;
t=t->next;
t->data=d;
t->next=l;
}
void deleteatpos(lptr l,int p)
{
lptr t=l;int d;
while(t->next->data!=p)
t=t->next;
lptr t2=t->next;
t->next=t->next->next;
delete t2;
}
void create(lptr l)
{
int d;lptr t;
t=l;
cout<<"Enter the first element or -1 to exit\n";
cin>>d;
if(d!=-1)
{
t->data=d;
t->next=l;
}
while(d!=-1)
{
cout<<"Enter the element or -1 to exit\n";
cin>>d;
if(d!=-1)
add_end(l,d);
}
}
void deletebegin(lptr &l)
{
lptr t;
t=new struct node;
t=l;
l=l->next;
delete t;
}
void deletebefore(lptr l,int p)
{
lptr t,t2;
t=l;
while(t->next->next->data!=p)
{
t=t->next;
}
t2=t->next;
t->next=t->next->next;
delete t2;
}
void removedice(lptr &l,int n)
{
int i,j,k;
lptr t1=l;lptr t2;
int d;
srand(time(NULL));
for(j=1;j<n;j++)
{
d=rand()%10+1;
cout<<"RAND "<<d<<endl;
for(i=1;i<=d;i++)
{
t1=t1->next;
l=l->next;
} t1=t1->next;
deletebefore(l,t1->data);
}
display1(l);
}
int main()
{
lptr l;int n;
l=new node;
cout<<"Enter the no. of soilders\n";
cin>>n;
create(l);
display(l,n);
removedice(l,n);
// display1(l);
return 0;
}
| true |
270c3f496056478f014277b39b95421e97e57ac1 | C++ | mjyc/spencer_people_tracking | /detection/laser_detectors/srl_laser_features/src/srl_laser_features/features/feature09.cpp | UTF-8 | 839 | 2.578125 | 3 | [
"BSD-2-Clause"
] | permissive | #include <srl_laser_features/features/feature09.h>
namespace srl_laser_features {
void Feature09::evaluate(const Segment& segment, Eigen::VectorXd& result) const
{
result = Eigen::Vector1d::Zero();
const size_t numPoints = segment.points.size();
if (numPoints > 2) {
double std_x = 0.0;
double std_y = 0.0;
for (size_t pIndex = 0; pIndex < numPoints; ++pIndex) {
double dx = segment.mean(0) - segment.points[pIndex](0);
double dy = segment.mean(1) - segment.points[pIndex](1);
std_x += dx * dx;
std_y += dy * dy;
}
std_x = sqrt(std_x / (numPoints - 1));
std_y = sqrt(std_y / (numPoints - 1));
double min, max;
if (std_x < std_y) {
min = std_x;
max = std_y;
}
else {
min = std_y;
max = std_x;
}
result(0) = (1.0 + min) / (1.0 + max);
}
}
} // end of namespace srl_laser_features
| true |
55077213a98ba3abd11256ddcbb17b2b450f1714 | C++ | zll5267/save-daily-exercise | /cpp/trigraphs/Trigraphs.cpp | UTF-8 | 951 | 2.78125 | 3 | [] | no_license | /*
Before any other processing takes place, each occurrence of one of the following sequences of three characters
(“trigraph sequences”) is replaced by the single character indicated in Table 1.
----------------------------------------------------------------------------
| trigraph | replacement | trigraph | replacement | trigraph | replacement |
----------------------------------------------------------------------------
| ??= | # | ??( | [ | ??< | { |
| ??/ | \ | ??) | ] | ??> | } |
| ??’ | ˆ | ??! | | | ??- | ˜ |
----------------------------------------------------------------------------
*/
#include "iostream"
int main() {
std::cout << "??=" << std::endl;
std::cout << "\?\?=" << std::endl;
std::cout << "?\?\?/???" << std::endl;
return 0;
}
| true |
9bc1b30f872340fb3868e2f53a31b28bba4908b0 | C++ | sysfce2/Arcade_Bagman | /src/sys/ThreadSafeContainer.hpp | UTF-8 | 2,424 | 2.6875 | 3 | [] | no_license | /*---------------------------------------------------------------------------*
* (C) 2004 - JFF Software *
*---------------------------------------------------------------------------*/
#ifndef THREADSAFECONTAINER_H
#define THREADSAFECONTAINER_H
/*------------*
* Used units *
*------------*/
#include <map>
#include "ThreadSafe.hpp"
/*-----------------*
* Types & objects *
*-----------------*/
/**
*
* thread-safe object
*
* declare one static object ThreadSafeContainer<MyObject>, which is the
* global, thread-protected container for the MyObject objects
*
* there is 1 and only 1 MyObject object per thread
*
* @author Jean-Francois FABRE
*
*/
template <class CNT>
class ThreadSafeContainer : public ThreadSafe
{
public:
typedef typename ThreadSafe::ThreadId ThreadId;
typedef std::map<void *,CNT> ContainerType;
typedef typename ContainerType::const_iterator const_iterator;
/**
* protected per-thread access method
*/
CNT &get()
{
return find_or_create();
}
/**
* protected per-thread access method (constant)
*/
const CNT &get() const
{
ThreadSafeContainer *nonconst_hack = (ThreadSafeContainer*)this;
return nonconst_hack->find_or_create();
}
/**
* unprotected start iterator. use cs_start/cs_end
* to protect the begin/end loop
*/
const_iterator begin() const
{
return m_map.begin();
}
/**
* unprotected end iterator. use cs_start/cs_end
* to protect the begin/end loop
*/
const_iterator end() const
{
return m_map.end();
}
private:
CNT &find_or_create()
{
const ThreadId myid = me();
cs_start();
typename ContainerType::iterator rval = m_map.find((void*)myid);
if (rval == m_map.end())
{
// not found (first call to get() from this thread): create one
// in thread safe mode (list is shared by all threads)
std::pair<typename ContainerType::iterator, bool> success =
m_map.insert(std::make_pair((void*)myid,CNT()));
// update size while in thread protected context
m_size = m_map.size();
rval = success.first;
}
cs_end();
return rval->second;
}
mutable ContainerType m_map;
};
#endif /* -- End of unit, add nothing after this #endif -- */
| true |
b7ed97cd2de563ca1a453c734b895315b290d40d | C++ | leader120/USC-EE569 | /hw2/problem3/part1/problem3_part1.cpp | UTF-8 | 7,479 | 3.265625 | 3 | [] | no_license | /*
Name: Armin Bazarjani
USC ID: 4430621961
USC Email: bazarjan@usc.edu
Submission Date: 2-23-21
cpp file for Problem 3-part 1 (Separable Error Diffusion)
*/
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <vector>
#include <fstream>
#include <cmath>
#include <cstring>
#include "readwrite.h"
using namespace std;
/// Global Parameters ///
int fish_height = 426;
int fish_width = 640;
int fish_channels = 3;
const double fixed_threshold = 128.0;
// define normal and mirrored floyd-steinberg matrices
const double fs_normal[3][3] = {
{0.0, 0.0, 0.0},
{0.0, 0.0, 7.0},
{3.0, 5.0, 1.0}
};
const double fs_mirrored[3][3] = {
{0.0, 0.0, 0.0},
{7.0, 0.0, 0.0},
{1.0, 5.0, 3.0}
};
/// Useful Helper Functions ///
// Function to print out usage
void print_commands(){
cout << "The usage is as follows:" << endl;
cout << "./executable command_1 command_2" << endl;
cout << "where:" << endl;
cout << "command_1 is the input path to the raw file" << endl;
cout << "command_2 is the desired output path for the half-toned image" << endl;
}
// Function to make sure everything becomes a valid unsigned char
unsigned char round_and_clip(double value) {
int round_val = (int)round(value);
if (round_val > 0xFF) {
return 0xFF;
}
else if (round_val < 0x00) {
return 0x00;
}
else {
return (unsigned char)round_val;
}
}
// Function to zero pad the data
template<size_t size_x, size_t size_y, size_t size_channels, size_t height, size_t width>
void zero_pad(double (&output)[height][width][size_channels], unsigned char (&input)[size_x][size_y][size_channels], int pad_size){
// start by filling in the original areas
for (int i = 0; i < fish_height; i++){
for (int j = 0; j < fish_width; j++){
for (int k = 0; k < size_channels; k++){
output[i+pad_size][j+pad_size][k] = (double) input[i][j][k];
}
}
}
// top
for (int i = 0; i < pad_size; i++){
for (int j = 0; j < fish_width + 2 * pad_size; j++){
for (int k = 0; k < size_channels; k++){
output[i][j][k] = 0.0;
}
}
}
// bottom
for (int i = fish_height + pad_size; i < fish_height + 2*pad_size; i++){
for (int j = 0; j < fish_width + 2*pad_size; j++){
for (int k = 0; k < size_channels; k++){
output[i][j][k] = 0.0;
}
}
}
// left
for (int i = 0; i < fish_height; i++){
for (int j = 0; j < pad_size; j++){
for (int k = 0; k < size_channels; k++){
output[i+pad_size][j][k] = 0.0;
}
}
}
// right
for (int i = 0; i < fish_height; i++){
for (int j = fish_width + pad_size; j < fish_width + 2*pad_size; j++){
for (int k =0; k < size_channels; k++){
output[i+pad_size][j][k] = 0.0;
}
}
}
}
// Function to assist with operation with matrix within error diffusion
template<size_t height_pad, size_t width_pad, size_t channels, size_t matrix_size>
void diffuse(double (&padded_image)[height_pad][width_pad][channels], const double (&matrix)[matrix_size][matrix_size],int row, int col, int offset, bool mirror, double divisor, int channel){
// calculate the offset to know how far we have to move within padded image
double error = 0.0;
// calculate error and update the current value
if (padded_image[row+offset][col+offset][channel] >= fixed_threshold){
error = (double) padded_image[row+offset][col+offset][channel]-255.0;
padded_image[row+offset][col+offset][channel] = 255.0;
}
else{
error = (double) padded_image[row+offset][col+offset][channel]-0.0;
padded_image[row+offset][col+offset][channel] = 0.0;
}
// check if we are mirroring or not
if (mirror == false){
int matrix_i = 0;
int matrix_j = 0;
// if not do everything normally
for (int i = row; i < row+matrix_size; i++){
for (int j = col; j < col+matrix_size; j++){
padded_image[i][j][channel] += (divisor*matrix[matrix_i][matrix_j]*error);
matrix_j += 1;
}
matrix_i += 1;
matrix_j = 0;
}
}
else{
int matrix_i = 0;
int matrix_j = matrix_size-1;
for (int i = row; i < row+matrix_size; i++){
for (int j = col; j > col-matrix_size; j--){
padded_image[i][j][channel] += (divisor*matrix[matrix_i][matrix_j]*error);
matrix_j -= 1;
}
matrix_i += 1;
matrix_j = matrix_size-1;
}
}
}
// Function to perform error diffusion
template<size_t height, size_t width, size_t channels, size_t height_pad, size_t width_pad, size_t matrix_size>
void error_diffuse(double (&padded_image)[height_pad][width_pad][channels], unsigned char (&output)[height][width][channels], const double (&mat_normal)[matrix_size][matrix_size], const double (&mat_mirror)[matrix_size][matrix_size], int pad_size, double divisor, char * output_path){
// serpentine loop through original image
for(int i = 0; i <= height_pad-matrix_size; i++){
// if we are on an even row go from left to right
if (i%2 == 0){
for (int j = 0; j <= width_pad-matrix_size; j++){
// diffuse with normal matrix on each channel
diffuse(padded_image, mat_normal, i, j, pad_size, false, divisor, 0);
diffuse(padded_image, mat_normal, i, j, pad_size, false, divisor, 1);
diffuse(padded_image, mat_normal, i, j, pad_size, false, divisor, 2);
}
}
// else we are on an odd row and we go from right to left
else{
for (int j = width_pad; j >= matrix_size-1; j--){
// diffuse with mirrored matrix
diffuse(padded_image, mat_mirror, i, j, pad_size, true, divisor, 0);
diffuse(padded_image, mat_mirror, i, j, pad_size, true, divisor, 1);
diffuse(padded_image, mat_mirror, i, j, pad_size, true, divisor, 2);
}
}
}
// copy the padded image to the output
for (int row = 0; row < height; row++){
for (int col = 0; col < width; col++){
for (int channel = 0; channel < channels; channel++){
output[row][col][channel] = round_and_clip(padded_image[row+pad_size][col+pad_size][channel]);
}
}
}
// write out the new image
write_out(output, output_path, fish_height, fish_width, fish_channels);
}
/// Main Function ///
int main(int argc, char * argv[]){
if (argc < 2){
cout << "wrong usage, printing out command usage..." << endl;
print_commands();
return 0;
}
// cout << "performing separable error diffusion on fish image..." << endl;
// read in the input image
unsigned char fish_data[426][640][3];
read_in(fish_data, argv[1], fish_height, fish_width, fish_channels);
// construct output image
unsigned char fish_output[426][640][3];
// pad the image
double fish_padded[428][642][3];
zero_pad(fish_padded, fish_data, 1);
// divisor
double divisor = (1.0/16.0);
// call the separable error diffusion function
error_diffuse(fish_padded, fish_output, fs_normal, fs_mirrored, 1, divisor, argv[2]);
} | true |
ef20e960c7b60662773afff2bf6ba241403e2139 | C++ | Sudarshan-Kulkarni/Huffman-Compressor | /main.cpp | UTF-8 | 730 | 3.390625 | 3 | [
"MIT"
] | permissive | #include "huffman.h"
bool fileExists(string fileName)
{
fstream infile(fileName.c_str());
return infile.good();
}
int main(int argc, char *argv[])
{
if(argc!=3)
{
cout<<"Wrong number of arguments provided."<<endl<<"Usage:'./app.exe <-(c/d)> <filepath>";
return -1;
}
string mode = argv[1];
string fileName = argv[2];
if(!fileExists(fileName))
{
cout<<"File doesn't exist"<<endl;
return -1;
}
Huffman h;
if(mode=="-c")
{
h.compressFile(fileName);
}
else if(mode=="-d")
{
h.decompressFile(fileName);
}
else
{
cout<<"Invalid mode entered"<<endl;
return -1;
}
}
| true |
377aa34fc45ca857db3129b9a10f7e4021feaf8c | C++ | Xiaojiean/ros2_tutorial_collection | /tutorial_sync_service/src/service_server.cpp | UTF-8 | 786 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | #include "rclcpp/rclcpp.hpp"
#include "std_srvs/srv/trigger.hpp"
class ServiceServer: public rclcpp::Node
{
public:
ServiceServer():Node("sample_server")
{
server_ = create_service<std_srvs::srv::Trigger>(
"sample_service",
std::bind(&ServiceServer::service_callback, this, std::placeholders::_1, std::placeholders::_2));
}
void service_callback(std_srvs::srv::Trigger::Request::SharedPtr, std_srvs::srv::Trigger::Response::SharedPtr res)
{
res->success = true;
res->message = "good";
}
private:
rclcpp::Service<std_srvs::srv::Trigger>::SharedPtr server_;
};
int main(int argc, char* argv[])
{
rclcpp::init(argc, argv);
auto node = std::make_shared<ServiceServer>();
rclcpp::executors::MultiThreadedExecutor exec;
exec.add_node(node);
exec.spin();
}
| true |
1fdb859b4f7edd46eb902a56bef82cf115c73e2a | C++ | md143rbh7f/competitions | /codeforces/121/demonstration.cpp | UTF-8 | 568 | 2.625 | 3 | [] | no_license | #include <algorithm>
#include <iostream>
#include <utility>
using namespace std;
pair<int,int> c[100005];
int main()
{
int n, k;
long long b;
cin >> n >> k >> b;
for( int i = 0; i < n; i++ )
{
cin >> c[i].first;
c[i].second = i + 1;
}
sort( c, c + n - 1 );
reverse( c, c + n - 1 );
long long tot = 0;
for( int i = 0; i < k - 1; i++ ) tot += c[i].first;
int best = n;
for( int i = 0; i < n - 1; i++ )
{
bool ok = b - tot < c[ max( k - 1, i ) ].first;
if( ok && c[i].second < best ) best = c[i].second;
}
cout << best << endl;
return 0;
}
| true |
30584fe3093fd15d21ea81056119ed7636fad032 | C++ | llalexandru00/ICPC-Training | /Codeforces/#451 Div. 2/A - Rounding.cpp | UTF-8 | 162 | 2.59375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int a;
int main()
{
cin >> a;
if (a % 10 <= 5)
cout << a / 10 * 10;
else
cout <<(a / 10 + 1) * 10;
return 0;
} | true |
9ef8a3ce7caa490d59cca7ef18874f092dc10c9e | C++ | MukulR/Turning-point | /worlds/src/pom.cpp | UTF-8 | 1,249 | 2.578125 | 3 | [] | no_license | #include "pom.hpp"
#include "commons.hpp"
#include "motordefs.hpp"
#include "robot_driver.hpp"
POM::POM(MotorDefs *md, RobotDriver *rd, bool ra, Commons *ca){
mtrDefs = md;
robotDriver = rd;
redAlliance = ra;
commonAutons = ca;
}
POM::~POM() {}
void POM::getPlatformBallAndAlignAgainstFence(){
// Drive to the ball on platform
robotDriver->smoothDrive(350, 80, 1);
// Pickup the ball
mtrDefs->intake_mtr->move(127);
mtrDefs->flipper_mtr->move(-40);
pros::Task::delay(350);
robotDriver->driveRobot(-50, 50);
mtrDefs->flipper_mtr->move(0);
pros::Task::delay(100);
// Drive back to starting position
robotDriver->smoothDrive(350, 80, -1);
// Turn left if red alliance or right if blue alliance
if(redAlliance){
robotDriver->turnRobot(33, true);
} else {
robotDriver->turnRobot(18, false);
}
// Drive back so that the back of the robot aligns against the fence and bring up flipper
robotDriver->driveWithCoast(800, -50);
mtrDefs->flipper_mtr->move(110);
pros::Task::delay(250);
mtrDefs->flipper_mtr->move(5);
}
void POM::runAuton(){
getPlatformBallAndAlignAgainstFence();
commonAutons->alignAndShootOurFlags();
//toggleLowFlag(mtrDefs, redAlliance);
commonAutons->pickupBallsFromCapFlipAndShoot();
}
| true |
82e804904b136837496f40ece8028d1fecbee31e | C++ | ihorkobreniuk/repos | /lab1/lab1-1/lab1-1.cpp | UTF-8 | 449 | 2.765625 | 3 | [] | no_license |
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
int main()
{
int a, b, c, d, e, f;
a = sizeof(int);
b = sizeof(short);
c = sizeof(long);
d = sizeof(char);
e = sizeof(float);
f = sizeof(double);
//sizeof рассчитывает кол-во байт в операторе
return 0;
}
//f11 - Шаг с заходом. f10 - шаг с обходом. f5 - с отладкой. ctrl + f5 - без отладки | true |
ff7d7fd5ad08070370922b67acb2025b6de08c05 | C++ | tanvirhossain33/uva | /10327 - Flip Sort.cpp | UTF-8 | 422 | 3.109375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int num,ary[1000],i,j,count,temp;
while(cin >> num){
for(i = 0; i < num; i++)
cin >> ary[i];
count = 0;
for(i = 0; i < num; i++){
for(j = 1; j < num; j++){
if(ary[j-1] > ary[j]){
temp = ary[j];
ary[j] = ary[j-1];
ary[j-1] = temp;
count++;
}
}
}
cout << "Minimum exchange operations : " << count << endl;
}
return 0;
}
| true |
f6a803c80ee8c2a5cc144c5b1454159de4e68f2c | C++ | Puttichai/projecteuler | /src/p0037.cpp | UTF-8 | 1,754 | 3.71875 | 4 | [] | no_license | #include <iostream>
#include <stdlib.h> // atoi
#include <vector>
#include <string>
#include <algorithm>
bool IsPrime(long target) {
if( target < 2 ) {
return false;
}
if( target == 2 ) {
return true;
}
if( target % 2 == 0 ) {
return false;
}
for( long i = 3; i < target/2; i += 2 ) {
if( target % i == 0 ) {
return false;
}
}
return true;
}
// Suppose the input is already prime.
bool IsLeftTruncatablePrime(long target)
{
long divisor = 10;
while( target % divisor != target ) {
if( !IsPrime(target % divisor) ) {
return false;
}
divisor *= 10;
}
return true;
}
// Suppose the input is already prime
bool IsRightTruncatablePrime(long target)
{
long divisor = 10;
while( target / divisor > 0 ) {
if( !IsPrime(target / divisor) ) {
return false;
}
divisor *= 10;
}
return true;
}
long SumVectorLong(std::vector<long>& v)
{
long sum = 0;
for( size_t index = 0; index < v.size(); ++index ) {
sum += v[index];
}
return sum;
}
int main(int argc, char* argv[])
{
std::vector<long> results;
results.reserve(11); // There are only 11 primes that are both left-truncatable and right-truncatable
for( long n = 11; n < 1000000; ++n ) {
if( !IsPrime(n) ) {
continue;
}
if( IsLeftTruncatablePrime(n) && IsRightTruncatablePrime(n) ) {
results.push_back(n);
std::string sep = "";
std::cout << "results=[";
for( size_t index = 0; index < results.size(); ++index ) {
std::cout << sep << results[index];
sep = ", ";
}
std::cout << "];\n";
}
if( results.size() == 11 ) {
break;
}
}
std::cout << "Sum of all left-/right-truncatable primes is " << SumVectorLong(results) << "\n";
}
| true |
187b1715bb0d2e68680e1aeaed1f52bebdc2aaf0 | C++ | banghartOSU/165 | /week5/stringSort.cpp | UTF-8 | 2,830 | 4.21875 | 4 | [] | no_license | /*************************************************************************************
* Author: Thomas Banghart
* Date: 04/27/2019
* Description: stringSort sorts an array of C++ strings (std::string) into dictionary order.
* It takes two parameters, an array of strings, and the size of the array. Two helper functions
* toUpper() and isBefore() are needed to make this program work.
* ***********************************************************************************/
#include <string>
#include <iostream>
/******************************************************
* FUNCTION: toUpper
* Helper function while comparing stings. Used to convert every
* char in a string to uppercase using std::string toupper() function.
* ****************************************************/
std::string toUpper(std::string str){
for (int i =0; i < str.length(); i++){
str[i] = toupper(str[i]);
}
return str;
}
/******************************************************
* FUNCTION: isBefore
* Compares two strings in a string array.
* Returns true if the first string is should appear before
* the second string if they were arranged alphanumerically
* and false otherwise.
* ****************************************************/
bool isBefore(std::string first, std::string second){
std::string string1 = toUpper(first);
std::string string2 = toUpper(second);
return string1 < string2;
}
/******************************************************
* FUNCTION: stringSort
* The main function of the program
* ****************************************************/
void stringSort(std::string arr[], int size){
int startScan,
minIndex;
std::string minString;
for (startScan = 0; startScan < (size - 1); startScan++) {
minIndex = startScan;
minString = arr[startScan];
for (int index = startScan + 1; index < size; index++) {
if (isBefore(arr[index], minString)) {
minString = arr[index];
minIndex = index;
}
}
arr[minIndex] = arr[startScan];
arr[startScan] = minString;
}
}
void printArray(std::string arr[], int size){
for(int i = 0; i < size; i++)
std::cout << arr[i] << std::endl;
}
// int main(){
// const int SIZE = 5;
// std::string s1 = "AbcdedFG";
// std::string s2 = "AbbD";
// std::string s3 = "QRST";
// std::string s4 = "SEVEN";
// std::string s5 = "SEVEN";
// std::string sArray[] = {s1, s2, s3, s4, s5};
// std::cout << "Unsorted: " << std::endl;
// printArray(sArray, SIZE);
// std::cout << "\n" << std::endl;
// std::cout << "Sorted: " << std::endl;
// stringSort(sArray, SIZE);
// printArray(sArray, SIZE);
// return 0;
// }
| true |
37d6ccfed4d5ece1f2cc784f23b74f91f79a1bf4 | C++ | Daniel521/raytracing | /p_raytracing2/Matrix.h | UTF-8 | 7,994 | 3.328125 | 3 | [] | no_license | #pragma once
#include "Vector.h"
#include "Misc.h"
namespace RT {
template <typename scalar_type, size_t HEIGHT, size_t WIDTH>
class Matrix {
public:
// Type aliases
using same_type = Matrix<scalar_type, HEIGHT, WIDTH>;
using row_type = Vector<scalar_type, WIDTH>;
using row_container_type = std::array<row_type, HEIGHT>;
using row_iterator = typename row_container_type::iterator;
using const_row_iterator = typename row_container_type::const_iterator;
public:
// Constructor and Assignment
Matrix() : Matrix(scalar_type(0)) {}
Matrix(const same_type& m) = default;
Matrix(same_type&& m) = default;
Matrix(scalar_type default_value) { fill(default_value); }
template <typename input_iterator>
Matrix(input_iterator input_begin, input_iterator input_end) {
input_iterator iter = input_begin;
for (size_t y = 0; y < HEIGHT; ++y) {
for (size_t x = 0; x < WIDTH; ++x) {
data_[y][x] = (iter == input_end) ? scalar_type(0) : *iter++;
}
}
}
Matrix(std::initializer_list<scalar_type> il) : Matrix(il.begin(),il.end()) {}
same_type& operator=(const same_type& m) = default;
// Comparators
bool operator==(const same_type& rhs) { return std::equal(data_.begin(), data_.end(), rhs.data_.begin()); }
bool operator!=(const same_type& rhs) { return !(*this == rhs); }
// Accessor
const row_type& operator[](size_t i) const { assert(is_row(i)); return data_[i]; }
row_type& operator[](size_t i) { assert(is_row(i)); return data_[i]; }
// Math operations
const same_type& operator+() const { return *this; }
same_type operator-() const {
same_type negation_;
for (size_t y = 0; y < HEIGHT; ++y)
for (size_t x = 0; x < WIDTH; ++x)
negation_[y][x] = - 1 * data_[y][x];
return negation_;
}
same_type operator+(const same_type& rhs) const {
same_type sum_;
for (size_t y = 0; y < HEIGHT; ++y)
for (size_t x = 0; x < WIDTH; ++x)
sum_[y][x] = data_[y][x] + rhs.data_[y][x];
return sum_;
}
same_type operator-(const same_type& rhs) const {
same_type difference_;
for (size_t y = 0; y < HEIGHT; ++y)
for (size_t x = 0; x < WIDTH; ++x)
difference_[y][x] = data_[y][x] - rhs.data_[y][x];
return difference_;
}
// Matrix-scalar multiplication
same_type operator*(scalar_type scalar) const {
same_type product_;
for (size_t y = 0; y < HEIGHT; ++y)
for (size_t x = 0; x < WIDTH; ++x)
product_[y][x] = data_[y][x] * scalar;
return product_;
}
// Matrix-matrix multiplication
template <size_t RESULT_WIDTH>
Matrix<scalar_type, HEIGHT, RESULT_WIDTH> operator*(const Matrix<scalar_type, WIDTH, RESULT_WIDTH>& rhs) const {
Matrix < scalar_type, HEIGHT< RESULT_WIDTH> result_;
for (size_t y = 0; y < HEIGHT; ++y) // rows
for (size_t x = 0; x < RESULT_WIDTH; ++x) // result-width
for (size_t addies = 0; addies < WIDTH; ++addies) // column
result_[y][x] += data_[y][addies] * rhs[addies][x];
return result_;
}
same_type operator/(scalar_type scalar) const {
same_type quotient_;
for (size_t y = 0; y < HEIGHT; ++y)
for (size_t x = 0; x < WIDTH; ++x)
quotient_[y][x] = data_[y][x] / scalar;
return quotient_;
}
// Determinant
scalar_type determinant() const {
assert(is_square(), "Must have squared matrix to perform determinant");
assert((WIDTH == 2 || WIDTH == 3), "Must have 2x2 or 3x3 matrix to perform determinant");
scalar_type det = 0;
if (WIDTH == 3) {
scalar_type row0 = data_[0][0] * ((data_[1][1] * data_[2][2]) - (data_[2][1] * data_[1][2]));
scalar_type row1 = data_[0][1] * ((data_[1][0] * data_[2][2]) - (data_[2][0] * data_[1][2]));
scalar_type row2 = data_[0][2] * ((data_[1][0] * data_[2][1]) - (data_[2][0] * data_[1][1]));
det = row0 - row1 + row2;
}
else {
det = (data_[0][0] * data_[1][1]) - (data_[1][0] * data_[0][1]);
}
return det;
}
// Solving Linear Equations
Vector<scalar_type, HEIGHT> solve(const Vector<scalar_type, HEIGHT>& b) const {
assert(is_square(), "Matrix must be square to solve linear equation");
assert((WIDTH == 2 || WIDTH == 3), "Matrix must be 2x2 or 3x3 to solve linearly");
Vector<scalar_type, HEIGHT> result;
// Cramer's rule
scalar_type det(0);
if (WIDTH == 3) {
scalar_type row0 = data_[0][0] * ((data_[1][1] * data_[2][2]) - (data_[2][1] * data_[1][2]));
scalar_type row1 = data_[0][1] * ((data_[1][0] * data_[2][2]) - (data_[2][0] * data_[1][2]));
scalar_type row2 = data_[0][2] * ((data_[1][0] * data_[2][1]) - (data_[2][0] * data_[1][1]));
det = row0 - row1 + row2;
}
else {
det = (data_[0][0] * data_[1][1]) - (data_[1][0] * data_[0][1]);
}
if (WIDTH == 3) {
scalar_type row0;
scalar_type row1;
scalar_type row2;
//x
row0 = b[0] * ((data_[1][1] * data_[2][2]) - (data_[2][1] * data_[1][2]));
row1 = data_[0][1] * ((b[1] * data_[2][2]) - (b[2] * data_[1][2]));
row2 = data_[0][2] * ((b[1] * data_[2][1]) - (b[2] * data_[1][1]));
result[0] = (row0 - row1 + row2) / det;
//y
row0 = data_[0][0] * ((b[1] * data_[2][2]) - (b[2] * data_[1][2]));
row1 = b[0] * ((data_[1][0] * data_[2][2]) - (data_[2][0] * data_[1][2]));
row2 = data_[0][2] * ((data_[1][0] * b[2]) - (data_[2][0] * b[1]));
result[1] = (row0 - row1 + row2) / det;
//z
row0 = data_[0][0] * ((data_[1][1] * b[2]) - (data_[2][1] * b[1]));
row1 = data_[0][1] * ((data_[1][0] * b[2]) - (data_[2][0] * b[1]));
row2 = b[0] * ((data_[1][0] * data_[2][1]) - (data_[2][0] * data_[1][1]));
result[2] = (row0 - row1 + row2) / det;
}
else {
result[0] = ((b[0] * data_[1][1]) - (b[1] * data_[0][1])) / det;
result[1] = ((data_[0][0] * b[1]) - (data_[1][0] * b[0])) / det;
}
return result;
}
// Converting to other types
// Approximately equal
bool approx_equal(const same_type& rhs, double delta) const {
for (size_t y = 0; y < HEIGHT; ++y)
for (size_t x = 0; x < WIDTH; ++x)
if (approx_equal(data_[y][x], rhs[y][x], delta) == false) return false;
return true;
}
// ostream
friend std::ostream& operator<<(std::ostream& out, same_type matrix) {
for (const auto& r : matrix.data_) {
out << '[';
if (WIDTH > 0)
out << r[0];
for (size_t c = 1; c < WIDTH; ++c)
out << ' ' << r[c];
out << ']' << std::endl;
}
return out;
}
// Iterators
row_iterator begin() { return data_.begin(); }
row_iterator end() { return data_.end(); }
const_row_iterator begin() const { return data_.cbegin(); }
const_row_iterator end() const { return data_.cend(); }
// Size and indices
size_t width() const { return WIDTH; }
size_t height() const { return HEIGHT; }
bool is_column(size_t i) const { return (i < WIDTH); }
bool is_row(size_t i) const { return (i < HEIGHT); }
bool is_row_column(size_t r, size_t c) const { return (is_row(r) && is_column(c)); }
bool is_square() const { return (WIDTH == HEIGHT); }
template <typename other_scalar_type, size_t OTHER_HEIGHT, size_t OTHER_WIDTH>
bool is_same_size(const Matrix<other_scalar_type, OTHER_HEIGHT, OTHER_WIDTH>& other) const {
return (width() == other.width()) && (height() == other.height());
}
// Misc
void fill(scalar_type value) {
for (auto& i : data_)
i.fill(value);
}
same_type identity() const {
same_type ident_;
for (size_t i = 0; i < HEIGHT && i < WIDTH; ++i)
ident_[i][i] = 1;
return ident_;
}
Matrix<scalar_type, WIDTH, HEIGHT> tranpose() const {
Matrix<scalar_type, WIDTH, HEIGHT> trans_;
for (size_t y = 0; y < WIDTH; ++y)
for (size_t x = 0; x < HEIGHT; ++x)
trans_[y][x] = data_[x][y];
return trans_;
}
private:
row_container_type data_;
};
// Type aliases
template <typename scalar_type> using Matrix2x2 = Matrix<scalar_type, 2, 2>;
template <typename scalar_type> using Matrix3x3 = Matrix<scalar_type, 3, 3>;
template <typename scalar_type> using Matrix4x4 = Matrix<scalar_type, 4, 4>;
} | true |
4e902da7f7d2913e706b64f81ada4af58ccaac2d | C++ | suhwoo/algo_study_alone | /백준/2839_deliver_sugar_dp.cpp | UTF-8 | 895 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
unsigned int bagNum[5001];
int main() {
unsigned int totalWeight;
cin >> totalWeight;
bagNum[3] = 1;
bagNum[5] = 1;
for (int index = 6; index <= totalWeight; index++) {
if (index % 5 == 0) {
bagNum[index] = bagNum[index-5] + 1;
}
else if (index % 3 == 0) {
bagNum[index] = bagNum[index - 3] + 1;
}
else {
if (bagNum[index - 5] != 0 && bagNum[index - 3] == 0) {
bagNum[index] = bagNum[index - 5] + 1;
}
else if (bagNum[index - 5] == 0 && bagNum[index - 3] != 0) {
bagNum[index] = bagNum[index - 3] + 1;
}
else if (bagNum[index - 5] != 0 && bagNum[index - 3] != 0) {
bagNum[index] = min(bagNum[index - 5], bagNum[index - 3]) + 1;
}
else {
bagNum[index] = 0;
}
}
}
if (bagNum[totalWeight] != 0) {
cout << bagNum[totalWeight];
}
else {
cout << "-1";
}
return 0;
}
| true |
88630a590c4bff91a9c5ed91ce93e53cb3e95eb6 | C++ | zombre98/zia | /src/server/DlWrapper.hpp | UTF-8 | 1,856 | 2.796875 | 3 | [
"Unlicense"
] | permissive | #pragma once
#ifdef WIN32
#include <windows.h>
#else
#include <dlfcn.h>
#endif
#include <string>
namespace zia {
class DlWrapper {
public:
DlWrapper() = default;
/**
* Construct and load
* @param file the path to the file
*/
DlWrapper(const std::string &file) {
open(file);
}
/**
* Destructor
*/
~DlWrapper() {
#ifdef WIN32
if (handler_)
FreeLibrary(handler_);
#else
if (handler_)
dlclose(handler_);
#endif
};
public:
/**
* Get symbol and return it as a pointer to function
* @tparam fncType pointer to function type
* @param symbol the symbol to load
* @return
*/
template<typename fncType>
fncType getSymbol(const std::string &symbol) const {
#ifdef WIN32
auto ret = reinterpret_cast<fncType>(GetProcAddress(handler_, symbol.c_str()));
if (ret == nullptr)
throw std::runtime_error("Cannot get the symbol");
return ret;
#else
auto ret = reinterpret_cast<fncType>(dlsym(handler_, symbol.c_str()));
char *error = dlerror();
if (error)
throw std::runtime_error(error);
return ret;
#endif
}
/**
* Open and load a file
* @param file the path to the file
*/
void open(const std::string &file) {
#ifdef WIN32
if (handler_) {
if (FreeLibrary(handler_) == 0)
throw std::runtime_error("error while closing the lib");
handler_ = nullptr;
}
handler_ = LoadLibrary(TEXT(file.c_str()));
if (handler_ == nullptr)
throw std::runtime_error("Error while opening the shared lib");
#else
if (handler_) {
if (dlclose(handler_) != 0)
throw std::runtime_error("error while closing the lib");
handler_ = nullptr;
}
handler_ = dlopen(file.c_str(), RTLD_NOW);
if (handler_ == nullptr)
throw std::runtime_error("Error while opening the shared lib");
#endif
}
private:
#ifdef WIN32
HINSTANCE handler_ = nullptr;
#else
void *handler_ = nullptr;
#endif
};
}
| true |
abac975bc5d77a8a441132d39bfd7a995d9a7acb | C++ | HunterKonoha/ESCCore | /ESCCore/src/Data/Transform.cpp | UTF-8 | 3,148 | 2.671875 | 3 | [
"MIT"
] | permissive | #include "Transform.h"
#include "../Entity/Entity.h"
#include <boost/range/adaptor/indexed.hpp>
gsl::Transform::Transform(const boost::uuids::uuid & Obj) :self_(Obj) {
}
gsl::Transform::Transform(Transform && Obj) {
this->self_ = std::move(Obj.self_);
this->center_ = std::move(Obj.center_);
this->child_ = std::move(Obj.child_);
this->globalmatrix_ = std::move(Obj.globalmatrix_);
this->localmatrix_ = std::move(Obj.localmatrix_);
this->parent_ = std::move(Obj.parent_);
this->rot_ = std::move(Obj.rot_);
this->scale_ = std::move(Obj.scale_);
}
gsl::Transform::~Transform() {
}
gsl::Transform & gsl::Transform::SetCenter(const s3d::Vec2 & Center){
this->center_ = Center;
this->LocalMatrixUpdate();
this->GlobalMatrixUpdate();
return *this;
}
const s3d::Vec2 & gsl::Transform::GetCenter() const {
return this->center_;
}
gsl::Transform & gsl::Transform::SetScale(const s3d::Vec2 & Scale){
this->scale_ = Scale;
this->LocalMatrixUpdate();
this->GlobalMatrixUpdate();
return *this;
}
const s3d::Vec2 & gsl::Transform::GetScale() const {
return this->scale_;
}
gsl::Transform & gsl::Transform::SetRotation(double Angle) {
this->rot_ = Angle;
this->LocalMatrixUpdate();
this->GlobalMatrixUpdate();
return *this;
}
double gsl::Transform::GetRotation() const {
return this->rot_;
}
gsl::Transform & gsl::Transform::AddChild(const boost::uuids::uuid & Obj) {
this->child_.push_back(Obj);
auto& last = this->child_.back();
auto& trans = Entity(last).GetTransform();
trans->parent_ = this->self_;
trans->LocalMatrixUpdate();
trans->GlobalMatrixUpdate();
return *this;
}
gsl::Transform & gsl::Transform::RemoveChild(const boost::uuids::uuid & Obj) {
return this->RemoveChildIf([&](const boost::uuids::uuid& Id) {return Obj == Id; });
}
gsl::Transform & gsl::Transform::RemoveChildIf(const std::function<bool(const boost::uuids::uuid&)>& Pred) {
this->child_.erase(std::remove_if(this->child_.begin(), this->child_.end(), Pred), this->child_.end());
return *this;
}
gsl::Entity gsl::Transform::GetOwner() {
return gsl::Entity(this->self_);
}
std::vector<gsl::Entity> gsl::Transform::GetChild() {
return this->GetChildIf([](auto) {return true; });
}
std::vector<gsl::Entity> gsl::Transform::GetChildIf(const std::function<bool(const Entity&)>& Pred) {
std::vector<Entity> result;
for (auto&& id : this->child_) {
Entity entity(id);
if (entity.IsValid() && Pred(entity)) {
result.emplace_back(std::move(entity));
}
}
return result;
}
const s3d::Mat3x2 & gsl::Transform::GetLocalMatrix() const{
return this->localmatrix_;
}
const s3d::Mat3x2 & gsl::Transform::GetGlobalMatrix() const{
return this->globalmatrix_;
}
void gsl::Transform::GlobalMatrixUpdate() {
auto trans = Entity(*this->parent_).GetTransform();
if (this->parent_ && trans) {
this->globalmatrix_ = trans->globalmatrix_ * this->localmatrix_;
}
else {
this->globalmatrix_ = this->localmatrix_;
}
}
void gsl::Transform::LocalMatrixUpdate() {
this->localmatrix_ = s3d::Mat3x2::Rotate(this->rot_, this->center_).translate(this->center_).scale(this->scale_);
}
| true |
3245b6d2ce7af88fabab68eaf45d6de9c245043f | C++ | RGoralewski/pithon | /Pithon/Rect.cpp | UTF-8 | 1,016 | 3.03125 | 3 | [] | no_license | #include "Rect.h"
#include <SDL2_image/SDL_image.h>
#include <iostream>
Rect::Rect(int _w, int _h, int _r, int _g, int _b, int _a) :
w(_w), h(_h), r(_r), g(_g), b(_b), a(_a)
{
}
Rect::Rect(SDL_Renderer *renderer, int _w, int _h, const std::string &image_path) :
w(_w), h(_h)
{
texture = nullptr;
//Create surface
auto surface = IMG_Load(image_path.c_str());
if (!surface) {
std::cerr << "Failed to create surface." << std::endl;
}
//Create texture
texture = SDL_CreateTextureFromSurface(renderer, surface);
if (!texture) {
std::cerr << "Failed to create texture." << std::endl;
}
//Get rid of surface
SDL_FreeSurface(surface);
}
Rect::~Rect()
{
SDL_DestroyTexture(texture);
}
void Rect::Draw(SDL_Renderer *renderer, int x, int y) {
SDL_Rect rect = { x, y, w, h };
if (texture) {
SDL_RenderCopy(renderer, texture, nullptr, &rect);
}
else {
SDL_SetRenderDrawColor(renderer, r, g, b, a);
SDL_RenderFillRect(renderer, &rect);
}
}
| true |
ce2e8181183967b400170f05bb1f0fcc6e0f15db | C++ | kirill146/CudaMemoryAnalyzer | /CudaMemoryAnalyzer/src/Operator.h | UTF-8 | 2,472 | 2.71875 | 3 | [] | no_license | #pragma once
#include "Expression.h"
enum UnaryOperation {
PRE_INCREMENT,
PRE_DECREMENT,
POST_INCREMENT,
POST_DECREMENT,
NEGATE,
NOT, // ~
ADDR_OF,
DEREF,
LNOT, // !
REAL,
IMAG,
UO_UNDEFINED
};
enum BinaryOperation {
ASSIGN,
ADD,
SUB,
MUL,
DIV,
REM,
SHL,
SHR,
EQ,
NEQ,
LT,
LE,
GT,
GE,
LOR,
OR,
LAND,
AND,
XOR,
ADD_ASSIGN,
SUB_ASSIGN,
MUL_ASSIGN,
DIV_ASSIGN,
REM_ASSIGN,
XOR_ASSIGN,
BO_UNDEFINED,
COMMA
};
class UnaryOperator : public Expression {
public:
UnaryOperator(UnaryOperation op, std::unique_ptr<Expression> arg,
ExpressionType const& type, clang::SourceLocation const& location);
z3::expr toZ3Expr(State const* state) const override;
void modifyState(State* state) const override;
void rememberMemoryAccesses(State* state, std::vector<MemoryAccess>& memoryAccesses) const override;
Expression const* getArg() const { return arg.get(); }
UnaryOperation getOp() const { return op; }
private:
UnaryOperation op;
std::unique_ptr<Expression> arg;
};
class BinaryOperator : public Expression {
public:
BinaryOperator(BinaryOperation op, std::unique_ptr<Expression> lhs,
std::unique_ptr<Expression> rhs, ExpressionType const& type,
clang::SourceLocation const& location);
z3::expr toZ3Expr(State const* state) const override;
void modifyState(State* state) const override;
void rememberMemoryAccesses(State* state, std::vector<MemoryAccess>& memoryAccesses) const override;
Expression const* getLhs() const { return lhs.get(); }
Expression const* getRhs() const { return rhs.get(); }
private:
BinaryOperation op;
std::unique_ptr<Expression> lhs;
std::unique_ptr<Expression> rhs;
};
class ConditionalOperator : public Expression {
public:
ConditionalOperator(std::unique_ptr<Expression> cond, std::unique_ptr<Expression> then,
std::unique_ptr<Expression> _else, ExpressionType const& type,
clang::SourceLocation const& location);
z3::expr toZ3Expr(State const* state) const override;
Expression const* getCond() const { return cond.get(); }
Expression const* getThen() const { return then.get(); }
Expression const* getElse() const { return _else.get(); }
private:
std::unique_ptr<Expression> cond;
std::unique_ptr<Expression> then;
std::unique_ptr<Expression> _else;
}; | true |
69c9ba2aef5e83c641ff22779fb1a94269a85837 | C++ | OronW/Genetic-Lab4 | /Genetic.cpp | UTF-8 | 12,455 | 2.625 | 3 | [] | no_license | #include <string>
#include "Genetic.h"
#define TARGET std::string("Hello world!")
#define BULLSEYE 2 * TARGET.size() * TARGET.size()
#define MAXITER 16384
#define ELITISIM_RATE 0.2f
#define MUTATION_RATE 0.25f
#define MUTATION RAND_MAX * MUTATION_RATE
#define MAXK 20
#define LOST 8
#define SHIMSHON 0.5
#define YOVAV 1
int Scount;
int Ycount;
vector<double> avg_fitness;
vector<double> std_fitness;
int GA_POPSIZE;
int lastBest = 0;
int currentBest = 0;
int getTotalFitness(ga_vector &all_pop) {
int sum = 0;
for (int i = 0; i < GA_POPSIZE; i++)
sum += all_pop[i].fitness;
return sum;
}
void tournament(ga_vector &pop, ga_vector &output, int n) {
if (n > GA_POPSIZE) {
cout << "tournament: n too large!" << endl;
return;
}
output.clear();
int k = rand() % (MAXK - 2) + 2;
int index;
int best = INFINITY;
int choice = 0;
ga_vector t;
for (int i = 0; i < n; i++) {
for (int j = 0; j < k; j++) { //randomize k values
index = rand() % GA_POPSIZE;
t.push_back(pop[index]);
}
for (int j = 0; j < t.size(); j++) { // find the best one
if (t[i].fitness < best) {
best = t[i].fitness;
choice = i;
}
}
output.push_back(t[choice]);
}
SUSElitism(output, pop);
}
int fitnessSum(ga_vector &all_pop, int end) {
int fitness_sum = 0;
for (int i = 0; i <= end && i < all_pop.size(); i++)
fitness_sum += all_pop[i].fitness;
return fitness_sum;
}
int BEHeuristic(string source, string target) {
int result = 0;
int targetSize = target.size();
for (int i = 0; i < targetSize; i++) {
char sourceChar = source[i];
if (sourceChar == target[i])
result += 2*targetSize;
else {
for (int j = 0; j < targetSize; j++) {
if ((sourceChar == target[j])&&(target[j]!=source[j])) {
result = targetSize/2;
break;
}
}
}
}
return BULLSEYE - result;
}
void SUS(ga_vector &all_pop, ga_vector &output, int N) {
int F = getTotalFitness(all_pop);
int P = floor(F / N);
int index;
int start = rand() % P; // start with random number between 0 and P
vector<int> Points;
for (int i = 1; i < N; i++) {
index = start + i * P;
Points.push_back(index);
}
RWS(all_pop, Points, output);
SUSElitism(output, all_pop);
}
void SUSElitism(ga_vector &output, ga_vector &pop) {
int i = output.size();
int i1, i2, spos;
int tsize = TARGET.size();
string str;
while (output.size() < GA_POPSIZE) { //mate and add to output
i1 = rand() % (GA_POPSIZE / 2);
i2 = rand() % (GA_POPSIZE / 2);
spos = rand() % tsize;
str = pop[i1].str.substr(0, spos) + pop[i2].str.substr(spos, tsize - spos);
ga_struct citizen;
citizen.fitness = 0;
citizen.str = str;
output.push_back(citizen);
if (rand() < MUTATION)
mutate(output[i]);
i++;
}
}
void RWS(ga_vector &all_pop, vector<int> &Points, ga_vector &Keep) {
int numOfPoints = Points.size();
int fitness_threshold, j;
int last = 0;
Keep.clear();
for (int i = 0; i < numOfPoints; i++) { //find citizen with grater fitness
fitness_threshold = Points[i];
j = 0;
while (fitnessSum(all_pop, j) < fitness_threshold) {
j++;
}
if (j > GA_POPSIZE) {
cout << "RWS: next pop index j out of bounds!" << endl;
return;
}
ga_struct citizen;
citizen.str = all_pop[j].str;
citizen.fitness = all_pop[j].fitness;
Keep.push_back(citizen);
}
}
bool goalState(string source) {
bool s = source.compare(TARGET);
return (!s);
}
void BEFitness(ga_vector &all_pop)
{
string target = TARGET;
int tsize = target.size();
unsigned int fitness;
double avg = 0;
double std = 0;
for (int i = 0; i<GA_POPSIZE; i++) {
fitness = BEHeuristic(all_pop[i].str, target);
all_pop[i].fitness = fitness;
avg += fitness;
}
avg = avg / GA_POPSIZE;
avg_fitness.push_back(avg);
for (int i = 0; i<GA_POPSIZE; i++) {
std += pow(all_pop[i].fitness - avg, 2);
}
std = sqrt(std / GA_POPSIZE);
std_fitness.push_back(std);
}
string uniform_cross(string source1, string source2) {
int n = source1.size();
string result = source1;
for (int i = 0; i < n; i++) {
if (rand() % 2 == 1)
result[i] = source2[i];
}
return result;
}
string smartXbreed(string source1, string source2, int fitness1, int fitness2) {
int n = source1.size();
string result = source1;
if (fitness1 == 0)
return source1;
if (fitness2 == 0)
return source2;
if (fitness2 == fitness1)
return uniform_cross(source1, source2);
double p1 = double(fitness2) / double(fitness1);
double p2 = double(fitness1) / double(fitness2);
if (p1 < p2)
p2 = 1 - p1;
else if (p2 < p1)
p1 = 1 - p2;
else {
cout << "probabilities are out of bounds" << endl;
return uniform_cross(source1, source2);
}
//apply cross
for (int i = 0; i < n; i++) {
if (rand() < p2)
result[i] = source2[i];
}
return result;
}
int getGenDist(ga_struct & first, ga_struct & second)
{
string target = TARGET;
int tsize = target.size();
string str1 = first.str;
string str2 = second.str;
int i = 0, count = 0;
while (i< tsize) {
if (str1[i] != str2[i]) {
count++;
}
i++;
}
return count;
}
double getAverage(ga_vector & all_pop)
{
double average = 0.0;
for ( int i = 0 ; i < GA_POPSIZE ; i++ ) {
average += all_pop[i].fitness;
}
average = average / GA_POPSIZE;
return average;
}
double getVariance(ga_vector &all_pop)
{
double average = getAverage(all_pop);
double variance = 0.0;
for (int i = 0; i < GA_POPSIZE; i++) {
variance += (all_pop[i].fitness - average)*(all_pop[i].fitness - average);
}
variance = variance / GA_POPSIZE;
return variance;
}
double getPopulationDist(ga_vector & all_pop)
{
double pop_dist = 0.0;
for (int i = 0; i < GA_POPSIZE; i++) {
for (int j = i+1; j < GA_POPSIZE; j++) {
pop_dist += getGenDist(all_pop[i], all_pop[j]);
}
}
pop_dist = pop_dist / (GA_POPSIZE * GA_POPSIZE);
return pop_dist;
}
int catchLocalOptima(ga_vector & all_pop)
{
double res = getVariance(all_pop);
cout << "-D- var indicator :\n" << res << "\n" << endl;
if (res < SHIMSHON) {
if (Scount == 0) {
cout << "-E- LOCAL OPTIMA SIGNAL DETECTED (by vatiance)" << endl;
return 1;
}
--Scount;
}
//res = getPopulationDist(all_pop);
//cout << "-D- Dist indicator :\n" << res << "\n" << endl;
//if (res < YOVAV) {
// if (Ycount == 0) {
// cout << "-E- LOCAL OPTIMA SIGNAL DETECTED (by stupid hamming distance)" << endl;
// return 1;
// }
// --Ycount;
//}
return 0;
}
int randomImmigrants(ga_vector & all_pop)
{
//int immigration_rate = (rand() % 50);
int immigration_rate = 80;
cout << "-D- immigration rate is - " << immigration_rate << endl;
int immigrates = floor((immigration_rate * GA_POPSIZE)/100);
int tsize = TARGET.size();
cout << "-D- number of immigrants is - " << immigrates << endl;
for (int i = 0; i < immigrates; ++i) {
int kidnap = rand() % GA_POPSIZE;
//cout << "-D- kidnap is - " << kidnap << endl;
string shabah= "";
for (int j = 0; j < tsize; j++)
shabah += (rand() % 95) + 32;
all_pop[kidnap].str=shabah;
}
return 0;
}
void initAllPop(ga_vector &all_pop, ga_vector &buffer)
{
int tsize = TARGET.size();
for (int i = 0; i<GA_POPSIZE; i++) {
ga_struct citizen;
citizen.fitness = 0;
citizen.str.erase();
for (int j = 0; j<tsize; j++)
citizen.str += (rand() % 95) + 32;
all_pop.push_back(citizen);
}
buffer.resize(GA_POPSIZE);
}
void calcFit(ga_vector &all_pop)
{
string target = TARGET;
int tsize = target.size();
unsigned int fitness;
double avg = 0;
double std = 0;
for (int i = 0; i<GA_POPSIZE; i++) {
fitness = 0;
for (int j = 0; j<tsize; j++) {
fitness += abs(int(all_pop[i].str[j] - target[j]));
}
all_pop[i].fitness = fitness;
avg += fitness;
}
avg = avg / GA_POPSIZE;
avg_fitness.push_back(avg);
for (int i = 0; i<GA_POPSIZE; i++) {
std += pow(all_pop[i].fitness - avg, 2);
}
std = sqrt(std / GA_POPSIZE);
std_fitness.push_back(std);
}
bool fitSort(ga_struct x, ga_struct y)
{
return (x.fitness < y.fitness);
}
inline void sortAccToFit(ga_vector &all_pop)
{
sort(all_pop.begin(), all_pop.end(), fitSort);
}
void elitism(ga_vector &all_pop, ga_vector &buffer, int esize)
{
for (int i = 0; i<esize; i++) {
buffer[i].str = all_pop[i].str;
buffer[i].fitness = all_pop[i].fitness;
}
}
void mutate(ga_struct &member)
{
int tsize = TARGET.size();
int ipos = rand() % tsize;
int delta = (rand() % 90) + 32;
member.str[ipos] = ((member.str[ipos] + delta) % 122);
}
void onePointCross(ga_vector &all_pop, ga_vector &buffer )
{
int esize = GA_POPSIZE * ELITISIM_RATE;
int tsize = TARGET.size(), spos, i1, i2;
for (int i = esize; i < GA_POPSIZE; i++) {
i1 = rand() % (GA_POPSIZE / 2);
i2 = rand() % (GA_POPSIZE / 2);
spos = rand() % tsize;
buffer[i].str = all_pop[i1].str.substr(0, spos) +
all_pop[i2].str.substr(spos, tsize - spos);
}
}
void mate(ga_vector &all_pop, ga_vector &buffer, int cross_type, double mutation_rate)
{
int esize = GA_POPSIZE * ELITISIM_RATE;
int tsize = TARGET.size(), spos, i1, i2;
elitism(all_pop, buffer, esize);
// Mate the rest
for (int i = esize; i<GA_POPSIZE; i++) {
i1 = rand() % (GA_POPSIZE / 2);
i2 = rand() % (GA_POPSIZE / 2);
spos = rand() % tsize;
bool flag = false;
if (cross_type==1) //siungle point
buffer[i].str = all_pop[i1].str.substr(0, spos) + all_pop[i2].str.substr(spos, tsize - spos);
else if (cross_type==2) // uniform
buffer[i].str = uniform_cross(all_pop[i1].str, all_pop[i2].str);
else
{
cout << "mate error: unknown cross type" << endl;
return;
}
//if (rand() < mutation_rate) mutate(buffer[i]);
//<ORON>
if ((abs(currentBest - lastBest) < 1) && (flag == false))
{
mutate(buffer[i]);
//cout << "*******************************************" << endl;
//cout << "currentBest: " << currentBest << " lastBest: " << lastBest << endl;
//cout << "*******************************************"<< endl;
flag = true;
}
}
}
inline void printResOfBest(ga_vector &gav)
{
cout << "Best: " << gav[0].str << " (" << gav[0].fitness << ")" << endl;
lastBest = currentBest;
currentBest = gav[0].fitness;
}
inline void printStatOf()
{
cout << "Average Fitness: " << avg_fitness.back() << endl << "STD Fitness: " << std_fitness.back() << endl;
}
inline void swap(ga_vector *&all_pop, ga_vector *&buffer)
{
ga_vector *temp = all_pop; all_pop = buffer; buffer = temp;
}
bool solveUsingGen(int N, int itr, int h, int cross_type, double mutation_rate, int selection_type) {
GA_POPSIZE = N;
clock_t start = clock();
bool success = false;
ga_vector pop_alpha, pop_beta;
ga_vector *all_pop, *buffer;
Scount = 5;
Ycount = 5;
initAllPop(pop_alpha, pop_beta);
all_pop = &pop_alpha;
buffer = &pop_beta;
for (int i = 0; i<itr; i++) {
cout << "-D- iteration number " << i << endl;
if (h==1)
calcFit(*all_pop);
else if (h==2)
BEFitness(*all_pop);
else {
cout << "solveUsingGen: unknown h type" << endl;
return false;
}
sortAccToFit(*all_pop); // sort them
printResOfBest(*all_pop); // print the best one
printStatOf();
if (goalState((*all_pop)[0].str)) {
success = true;
cout << "done" << endl;
cout << "********" << endl;
cout << "time data:" << endl;
break;
}
if ((*all_pop)[0].fitness < LOST) {
if (catchLocalOptima(*all_pop)) {
randomImmigrants(*all_pop);
Scount = 5;
Ycount = 5;
}
}
if (selection_type==1)
mate(*all_pop, *buffer, cross_type, mutation_rate); // mate the all_pop together
else if (selection_type == 2)
SUS(*all_pop, *buffer, floor(10));
else if (selection_type == 3)
tournament(*all_pop, *buffer, 20);
else {
cout << "solve_pop: invalid selection type" << endl;
return false;
}
swap(all_pop, buffer); // swap buffers
}
double time = clock() - start;
cout << "Total clicks: " << time << endl;
cout << "Total Time: " << (float)time / CLOCKS_PER_SEC << endl;
return success;
}
| true |
60b5137882edf37a63b263b923ebb4ed4ee2f1dc | C++ | keineahnung2345/leetcode-cpp-practices | /1382. Balance a Binary Search Tree.cpp | UTF-8 | 1,302 | 3.53125 | 4 | [] | no_license | //Runtime: 188 ms
//Memory Usage: 52 MB
/**
* 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:
void inOrder(TreeNode* node, vector<int>& nums){
if(!node)return;
inOrder(node->left, nums);
nums.push_back(node->val);
inOrder(node->right, nums);
}
TreeNode* buildTree(vector<int>& nums, int start, int end){
//end is inclusive
if(start > end) return NULL;
int mid = (start+end)/2;
TreeNode* newroot = new TreeNode(nums[mid]);
newroot->left = buildTree(nums, start, mid-1);
newroot->right = buildTree(nums, mid+1, end);
return newroot;
}
TreeNode* balanceBST(TreeNode* root) {
//parse tree
vector<int> nums;
inOrder(root, nums);
// for(int e : nums){
// cout << e << " ";
// }
// cout << endl;
//build tree
int N = nums.size();
TreeNode* newroot = new TreeNode(nums[N/2]);
newroot->left = buildTree(nums, 0, N/2-1);
newroot->right = buildTree(nums, N/2+1, N-1);
return newroot;
}
};
| true |
4e877b1979ac214ec3276321862441290c738e75 | C++ | SerenityOS/serenity | /Userland/Libraries/LibWeb/HTML/ListOfAvailableImages.cpp | UTF-8 | 2,019 | 2.71875 | 3 | [
"BSD-2-Clause"
] | permissive | /*
* Copyright (c) 2023, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibWeb/HTML/DecodedImageData.h>
#include <LibWeb/HTML/ListOfAvailableImages.h>
namespace Web::HTML {
ListOfAvailableImages::ListOfAvailableImages() = default;
ListOfAvailableImages::~ListOfAvailableImages() = default;
bool ListOfAvailableImages::Key::operator==(Key const& other) const
{
return url == other.url && mode == other.mode && origin == other.origin;
}
u32 ListOfAvailableImages::Key::hash() const
{
if (!cached_hash.has_value()) {
u32 url_hash = Traits<AK::URL>::hash(url);
u32 mode_hash = static_cast<u32>(mode);
u32 origin_hash = 0;
if (origin.has_value())
origin_hash = Traits<HTML::Origin>::hash(origin.value());
cached_hash = pair_int_hash(url_hash, pair_int_hash(mode_hash, origin_hash));
}
return cached_hash.value();
}
ErrorOr<NonnullRefPtr<ListOfAvailableImages::Entry>> ListOfAvailableImages::Entry::create(NonnullRefPtr<DecodedImageData> image_data, bool ignore_higher_layer_caching)
{
return adopt_nonnull_ref_or_enomem(new (nothrow) Entry(move(image_data), ignore_higher_layer_caching));
}
ListOfAvailableImages::Entry::Entry(NonnullRefPtr<DecodedImageData> data, bool ignore_higher_layer_caching)
: ignore_higher_layer_caching(ignore_higher_layer_caching)
, image_data(move(data))
{
}
ListOfAvailableImages::Entry::~Entry() = default;
ErrorOr<void> ListOfAvailableImages::add(Key const& key, NonnullRefPtr<DecodedImageData> image_data, bool ignore_higher_layer_caching)
{
auto entry = TRY(Entry::create(move(image_data), ignore_higher_layer_caching));
TRY(m_images.try_set(key, move(entry)));
return {};
}
void ListOfAvailableImages::remove(Key const& key)
{
m_images.remove(key);
}
RefPtr<ListOfAvailableImages::Entry> ListOfAvailableImages::get(Key const& key) const
{
auto it = m_images.find(key);
if (it == m_images.end())
return nullptr;
return it->value;
}
}
| true |
d85b313ef4a5b3549b62c79347836fbb6c3ff04c | C++ | petrmanek/fel-master-thesis | /gen/main.cpp | UTF-8 | 1,459 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <random>
#include <cmath>
#include <cal/cal.h>
int track_width(double k, double wmax)
{
double e = 2.5 * k - 0.3;
double w = wmax * std::exp(-e*e);
return std::max(0, std::min(256, (int) w));
}
kev_t track_energy(double k, double l, double emax)
{
double e = 4.0 * l;
double ev = emax * std::exp(-e*e);
double decay = std::exp(-(k + 0.5));
return std::max(0.0, std::min(emax, decay * ev));
}
void draw_line(kev_matrix& mat)
{
int y = 25;
int x0 = 10;
int l = 150;
double wmax = 14;
double emax = 320e6;
int x1 = x0 + l;
for (int x = x0; x < x1; ++x) {
// k = [0, 1] progress along the track length (0 = start, 1 = end)
double k = (double) x / (double) (x1 - 1);
int w = track_width(k, wmax);
if (w <= 0) continue;
for (int dy = -w; dy <= w; ++dy) {
// l = [-1, 1] progress along the track width (-1 = left edge, 0 = center, 1 = right edge)
double l = (double) dy / (double) w;
mat.at(dy + y, x) = track_energy(k, l, emax);
}
}
}
int main(int argc, char *argv[])
{
kev_matrix mat;
mat.fill(0);
draw_line(mat);
for (coord_t i = 0; i < CHIP_DIM; ++i) {
for (coord_t j = 0; j < CHIP_DIM; ++j) {
if (mat.at(i, j) <= 0) continue;
std::cout << CHIP_DIM * i + j << "\t " << mat.at(i, j) << std::endl;
}
}
return 0;
}
| true |
c096d6ed8639ad5fa8e77369f4b1669d29ad5d9f | C++ | kailashkai28/programs- | /Cplusplus/p12.cpp | UTF-8 | 803 | 3.25 | 3 | [] | no_license | #include<iostream>
#include "head12.h"
using namespace std;
int main(){
Employee e1;
cout<<e1;
Employee e2(e1);
cout<<e2;
Employee e3[5];
int ch,n;
do{
cout<<"\n\t-0-0-0-0Employee Menu-0-0-0-0\n\t\t1.Add details\t2.Display details\t3.Exit\nChoose an option(1-3):";
cin>>ch;
switch(ch){
case 1:
cout<<"\nEnter the number of employees:";
cin>>n;
for(int i=0;i<n;i++)
{ cout<<"\nEnter details of "<<i+1<<" employee:";
cin>>e3[i];
}
break;
case 2:cout<<"\nDetails:";
for(int i=0;i<n;i++){
cout<<"\nEmployee "<<i+1<<":";
cout<<e3[i];
}
break;
case 3:exit(0);
break;
default: cout<<"\nWrong choice entered!!!";
break;
}
}while(ch<=3);
return 0;
}
| true |
9409284cfd73e6ed6bda5c406e34e76132601b1e | C++ | GordilloXavi/pro1 | /consolidation/X17276.cc | UTF-8 | 814 | 3.25 | 3 | [] | no_license | #include<iostream>
#include <vector>
using namespace std;
typedef vector< vector<int> > Matrix;
bool diags(Matrix& m, int r, int c){
int rows = m.size();
int cols = m[0].size();
bool a = true;
int i = r, j = c;
while(i<rows and j < cols){
if()
i++;
j++;
}
}
void display(Matrix& m){
int r = m.size();
int c = m[0].size();
for(int i = 0; i<r; ++i){
for(int j = 0; j<c; ++j)cout << m[i][j] << ' ';
cout << endl;
}
}
int main() {
int r,c;
while(cin >> r >> c){
Matrix m(r,vector<int>(c));
for(int i = 0; i<r; ++i)for(int j = 0; j<c; ++j)cin >> m[i][j];
int x,y;
cin >> x >> y;
if(diags(m,x,y))cout << "yes\n";
else cout << "no\n";
}
}
| true |
c27d42245fbe2ef3f7984f10bab7f76f4782af3e | C++ | d01000100/tank_game | /GameServer/TankGameStuff/TankControls.cpp | UTF-8 | 1,544 | 2.890625 | 3 | [] | no_license | #include "TankControls.h"
#include "cGameBrain.h"
#include <string>
void cTankControls::updateTank(std::string tankName, UserInputMessage pressedKeys)
{
std::map<std::string, cGameObject*>::iterator itGO;
itGO = ::g_map_GameObjects.find(tankName);
if (itGO != ::g_map_GameObjects.end())
{
cGameObject* player = itGO->second;
glm::vec3 velocity = glm::vec3(0);
float rotationStep = 4.0f, speed = 10.0f;
// check rotation
if (pressedKeys.A)
{
player->updateOrientation(glm::vec3(0, rotationStep, 0));
}
if (pressedKeys.D)
{
player->updateOrientation(glm::vec3(0, -rotationStep, 0));
}
// check velocity
if (pressedKeys.W)
{
velocity += player->getCurrentAT() * speed;
}
if (pressedKeys.S)
{
velocity += player->getCurrentAT() * -speed;
}
if (pressedKeys.Space)
{
if(canFire(player->friendlyName))
{
fire(player->friendlyName);
}
}
player->velocity = velocity;
}
}
bool cTankControls::canFire(std::string shooterName)
{
cGameBrain* theGameBrain = cGameBrain::getTheGameBrain();
sTank* pTank = theGameBrain->get_sTank(shooterName);
if(pTank->fireCooldown <= 0 && pTank->isAlive)
{
return true;
}
else if (!pTank->isAlive)
{
pTank->isAlive = true;
::g_map_GameObjects[pTank->name]->isVisible = true;
}
return false;
}
void cTankControls::fire(std::string shooterName)
{
cGameBrain* theGameBrain = cGameBrain::getTheGameBrain();
theGameBrain->addBullet(shooterName);
sTank* pTank = theGameBrain->get_sTank(shooterName);
pTank->fireCooldown = 2.0f;
}
| true |
de792ee9b6469c18bd6a07a749aefe35060f210a | C++ | Shailesh-Tripathi/cuda_helpers | /gpu_sgemm/main.cpp | UTF-8 | 1,966 | 3.109375 | 3 | [] | no_license | /* Author : Shailesh Tripathi
* Sample code for invoking the gpu_sgemm wrapper function
* command to compile : nvcc -o res main.cpp fun.cu -lcudart -lcublas
*/
#include <stdio.h>
#include <stdlib.h>
#include "fun.h"
/* Matrix size */
#define N (4)
#define K (3)
#define M (2)
/* Main */
int main(int argc, char **argv)
{
float *h_A;
float *h_B;
float *h_C;
float alpha = 1.0f;
float beta = 0.0f;
int i,j;
float error_norm;
float ref_norm;
float diff;
/* Allocate host memory for the matrices */
h_A = (float *)malloc(M*K * sizeof(h_A[0]));
if (h_A == 0)
{
fprintf(stderr, "!!!! host memory allocation error (A)\n");
return EXIT_FAILURE;
}
h_B = (float *)malloc(K*N * sizeof(h_B[0]));
if (h_B == 0)
{
fprintf(stderr, "!!!! host memory allocation error (B)\n");
return EXIT_FAILURE;
}
h_C = (float *)malloc(M*N * sizeof(h_C[0]));
if (h_C == 0)
{
fprintf(stderr, "!!!! host memory allocation error (C)\n");
return EXIT_FAILURE;
}
/* Fill the matrices with test data */
for (i = 0; i < M*N; i++)
{
h_C[i] =i ;
}
for (i = 0; i < M*K; i++)
{
h_A[i] = i;
}
for (i = 0; i < K*N; i++)
{
h_B[i] = i;
}
//invoke wrapper function for mm
gpu_sgemm('N', 'N', M, N, K, alpha, h_A, M, h_B, K, beta, h_C, M);
printf("A: \n");
for( i = 0 ; i < M ; i++ )
{
for( j = 0 ; j < K ; j++ )
printf("%f ", h_A[i + M*j]);
printf("\n");
}
printf("\nB: \n");
for( i = 0 ; i < K ; i++ )
{
for( j = 0 ; j < N ; j++ )
printf("%f ", h_B[i + K*j]);
printf("\n");
}
printf("\nC: \n");
for( i = 0 ; i < M ; i++ )
{
for( j = 0 ; j < N ; j++ )
printf("%f ", h_C[i + M*j]);
printf("\n");
}
/* Check result against reference */
error_norm = 0;
ref_norm = 0;
/* Memory clean up */
free(h_A);
free(h_B);
free(h_C);
}
| true |
b4a3b1b99f632c97aa0e43714d77fb15fc9a4c6b | C++ | Biendeo/Wolf3D-Clone | /MapViewer/src/Framebuffer.cpp | UTF-8 | 981 | 3.421875 | 3 | [] | no_license | // Framebuffer.cpp
//
// Holds the data to determine a frame (as well as providing quick functions
// for modifying and accessing the buffer).
#include "Framebuffer.h"
Framebuffer::Framebuffer(uint16_t width, uint16_t height) {
this->data = nullptr;
Resize(width, height);
}
Framebuffer::~Framebuffer() {
delete[] data;
}
Color Framebuffer::Get(uint16_t x, uint16_t y) {
return data[x + y * width];
}
void Framebuffer::Set(uint16_t x, uint16_t y, Color c) {
data[x + y * width] = c;
}
uint16_t Framebuffer::Width() {
return width;
}
uint16_t Framebuffer::Height() {
return height;
}
void Framebuffer::Flush() {
Flush(0);
}
void Framebuffer::Flush(Color c) {
memset(Data(), c.ARGB(), sizeof(Color) * width * height);
}
void Framebuffer::Resize(uint16_t width, uint16_t height) {
if (data != nullptr) {
delete[] data;
}
data = new Color[width * height];
this->width = width;
this->height = height;
Flush();
}
void *Framebuffer::Data() {
return data;
}
| true |
556e6a8ebefaa788971bad2005cc0f05b293c981 | C++ | leandrovianna/programming_contests | /URI/2560_splay.cpp | UTF-8 | 6,008 | 3.34375 | 3 | [] | no_license | // URI - Surf Aquático - 2560
#include <bits/stdc++.h>
using namespace std;
template <typename T>
class SplayTree {
template <typename U>
struct Node {
U key;
Node *left, *right;
Node *parent;
int count;
Node(U key) :
key(key), left(nullptr), right(nullptr), parent(nullptr), count(1) {}
~Node() {
if (left != nullptr)
delete left;
if (right != nullptr)
delete right;
}
void copy(const Node<U>& node) {
this->key = node.key;
this->count = node.count;
}
};
Node<T> *root;
static const int SPLAY_HEIGHT = 100;
bool isLeftChild(const Node<T> *const node) const {
assert(node->parent != nullptr);
return node->key < node->parent->key;
}
void rotateLeft(Node<T> *node) {
auto q = node->right;
assert(q != nullptr);
node->right = q->left;
if (q->left != nullptr)
q->left->parent = node;
q->left = node;
if (node->parent != nullptr) {
if (isLeftChild(node))
node->parent->left = q;
else
node->parent->right = q;
}
q->parent = node->parent;
node->parent = q;
}
void rotateRight(Node<T> *node) {
auto q = node->left;
assert(q != nullptr);
node->left = q->right;
if (q->right != nullptr)
q->right->parent = node;
q->right = node;
if (node->parent != nullptr) {
if (isLeftChild(node))
node->parent->left = q;
else
node->parent->right = q;
}
q->parent = node->parent;
node->parent = q;
}
void splay(Node<T> *node) {
if (node == nullptr) return;
while (node->parent != nullptr) {
// parent of node
auto p = node->parent;
// grandparent of node
auto g = p->parent;
if (g == nullptr) {
// zig operation
if (isLeftChild(node)) {
rotateRight(p);
} else {
rotateLeft(p);
}
} else if (isLeftChild(node) && isLeftChild(p)) {
// zig-zig operation
rotateRight(g);
rotateRight(p);
} else if (isLeftChild(node)) {
// zig-zag operation
rotateRight(p);
rotateLeft(g);
} else if (isLeftChild(p)) {
// zig-zag operation
rotateLeft(p);
rotateRight(g);
} else {
// zig-zig operation
rotateLeft(g);
rotateLeft(p);
}
}
// change root to node
root = node;
}
Node<T> *minNode(Node<T> *node) {
assert(node != nullptr);
Node<T> *parent = nullptr;
while (node != nullptr) {
parent = node;
node = node->left;
}
return parent;
}
Node<T> *maxNode(Node<T> *node) {
assert(node != nullptr);
Node<T> *parent = nullptr;
while (node != nullptr) {
parent = node;
node = node->right;
}
return parent;
}
void printNode(Node<T> *node, int space = 0) const {
cout << string(space, ' ');
if (node == nullptr) cout << "X" << endl;
else {
cout << node->key << "(" << node->count << ")"<< endl;
printNode(node->left, space+1);
printNode(node->right, space+1);
}
}
public:
SplayTree() : root(nullptr) {
}
~SplayTree() {
if (root != nullptr)
delete root;
}
void insert(T key) {
if (root == nullptr) {
root = new Node<T>(key);
return;
}
Node<T> *node = root, *parent = nullptr;
int h = 0;
while (node != nullptr) {
h++;
parent = node;
if (key < node->key) {
node = node->left;
} else if (node->key < key) {
node = node->right;
} else {
// Key repeated, increase count
node->count++;
break;
}
}
if (node == nullptr) {
node = new Node<T>(key);
node->parent = parent;
if (key < parent->key) {
parent->left = node;
} else {
parent->right = node;
}
}
if (h > SPLAY_HEIGHT)
splay(node);
}
void erase(T key) {
Node<T> *node = root, *parent = nullptr;
int h = 0;
while (node != nullptr) {
h++;
if (key < node->key) {
parent = node;
node = node->left;
} else if (node->key < key) {
parent = node;
node = node->right;
} else if (node->count > 1) {
// More than one for this key, descrease count
node->count--;
node = nullptr;
} else if (node->right == nullptr) {
if (parent == nullptr) {
root = node->left;
} else if (node->key < parent->key) {
parent->left = node->left;
} else {
parent->right = node->left;
}
if (node->left != nullptr)
node->left->parent = parent;
node->left = nullptr;
delete node;
node = nullptr;
} else {
Node<T> *tmp = minNode(node->right);
node->copy(*tmp);
tmp->count = 1;
key = tmp->key; // change the key to delete
parent = node;
node = node->right; // continue search
}
}
if (parent == nullptr) return;
if (h > SPLAY_HEIGHT)
splay(parent);
}
T min() {
auto node = minNode(root);
splay(node);
return node->key;
}
T max() {
auto node = maxNode(root);
splay(node);
return node->key;
}
void print() const {
printNode(root);
}
};
const int N = 200100;
int a[N];
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int n, b;
while (cin >> n >> b) {
for (int i = 0; i < n; i++) {
cin >> a[i];
}
SplayTree<int> values;
int sum = 0;
for (int i = 0; i < b; i++) {
sum += a[i];
values.insert(a[i]);
}
int64_t ans = 0;
for (int i = 0, j = b-1; j < n; i++, j++) {
int minimum = values.min();
int maximum = values.max();
ans += sum - minimum - maximum;
values.erase(a[i]);
sum -= a[i];
values.insert(a[j+1]);
sum += a[j+1];
}
cout << ans << "\n";
}
return 0;
}
| true |
a9794af71ddd1e40f9eb6b90a565a613aa0d67ed | C++ | alexloboda/SVDFunctions | /src/vcf_parser.cpp | UTF-8 | 12,391 | 2.546875 | 3 | [
"MIT"
] | permissive | #include "include/vcf_parser.h"
#include <algorithm>
#include <sstream>
#include <type_traits>
#include <Rcpp.h>
namespace {
using namespace vcf;
using std::istream;
using std::vector;
using std::string;
using std::find;
using std::pair;
using std::stoi;
// Rcpp conflict
using vcf::MISSING;
vector<std::string> split(const string& line, char delim, size_t max_num_tokens = 0){
size_t tokens = 1;
for (char ch: line) {
if (ch == delim) {
++tokens;
if (tokens == max_num_tokens) {
break;
}
}
}
vector<string> result;
result.reserve(tokens);
unsigned long last = 0;
for (size_t i = 0; i < line.length(); i++) {
char ch = line[i];
if (ch == delim) {
result.push_back(line.substr(last, i - last));
last = i + 1;
if (result.size() == max_num_tokens) {
return result;
}
}
}
if (last != line.length()) {
result.push_back(line.substr(last, line.length() - last));
}
return result;
}
Position parse_position(const vector<string>& tokens) {
Chromosome chr(tokens[CHROM]);
int pos;
try {
pos = stoi(tokens[POS]);
} catch (...) {
throw ParserException("Can't read variant position");
}
return {chr, pos};
}
void find_pos(const vector<string>& tokens, const string& field, long& pos) {
auto position = find(tokens.begin(), tokens.end(), field);
if (position == tokens.end()) {
pos = -1;
} else {
pos = position - tokens.begin();
}
}
AlleleType type(int first, int second, int allele) {
if (first > second) {
std::swap(first, second);
}
if (first == second) {
if (first == 0) {
return HOMREF;
} else if (first == allele) {
return HOM;
}
} else {
if (first == 0 && second == allele) {
return HET;
}
}
return MISSING;
}
}
namespace vcf {
Format::Format(const string& format) {
vector<string> parts = split(format, ':');
find_pos(parts, DP_FIELD, depth_pos);
find_pos(parts, GQ_FIELD, qual_pos);
find_pos(parts, AD_FIELD, ad_pos);
find_pos(parts, GT_FIELD, genotype_pos);
if (genotype_pos == -1) {
throw ParserException("No GT field available for a variant");
}
}
AlleleType Format::parse_gt(const string& gt, int allele){
if (allele == 0) {
return HOM;
}
int first_allele, second_allele;
std::istringstream iss(gt);
iss >> first_allele;
if (iss.eof()) {
if (first_allele == 0) {
return HOMREF;
}
return first_allele == allele ? HOM : MISSING;
}
char ch;
iss >> ch;
if (ch != DELIM_1 && ch != DELIM_2) {
throw ParserException("Wrong GT format: " + gt);
}
iss >> second_allele;
if (iss.fail()) {
throw ParserException("Wrong GT format: " + gt);
}
return type(first_allele, second_allele, allele);
}
Allele Format::parse(const string& genotype, int allele, const VCFFilter& filter, VCFFilterStats& stats) {
vector<string> parts = split(genotype, ':');
try {
string gt = parts[genotype_pos];
if (gt == "." || gt == "./." || gt == ".|.") {
stats.add(Stat::GT_MISS, 1);
return {MISSING, 0, 0};
}
if (depth_pos >= (long)parts.size() || qual_pos >= (long)parts.size()) {
throw ParserException("ignored");
}
int dp = depth_pos == -1 || parts[depth_pos] == "." ? 0 : stoi(parts[depth_pos]);
int gq = qual_pos == -1 || parts[qual_pos] == "." ? 0 : stoi(parts[qual_pos]);
if (!filter.apply(dp, gq)) {
stats.add(Stat::DP_GQ, 1);
return {MISSING, (unsigned)dp, (unsigned)gq};
}
Allele ret{parse_gt(gt, allele), (unsigned)dp, (unsigned)gq};
if (ret.alleleType() == HET) {
// if (ad_pos != -1 && dp != 0) {
// std::istringstream adstream(parts[ad_pos]);
// int ref, alt;
// char ch;
// adstream >> ref;
// for (int i = 0; i < allele; i++) {
// while(!std::isdigit(adstream.peek())) {
// adstream >> ch;
// }
// adstream >> alt;
// }
// if (!adstream.fail()) {
// double ref_ratio = ref / (double)dp;
// double alt_ratio = alt / (double)dp;
// if (ref_ratio < 0.3 || ref_ratio > 0.7) {
// stats.add(Stat::ALLELE_BALANCE, 1);
// return {MISSING, 0, 0};
// }
// if (alt_ratio < 0.3 || alt_ratio > 0.7) {
// stats.add(Stat::ALLELE_BALANCE, 1);
// return {MISSING, 0, 0};
// }
// }
// }
}
return ret;
} catch (...) {
throw ParserException("Wrong GT format: " + genotype);
}
}
AlleleVector::AlleleVector(std::shared_ptr<std::string>& line, std::shared_ptr<std::vector<size_t>>& indices,
std::shared_ptr<vcf::VCFFilter>& filter, vcf::VCFFilterStats& stats, size_t variant, size_t ncols)
:line(line), indices(indices), filter(filter), stats(stats), variant(variant),
expected_ncols(ncols) {}
Allele AlleleVector::operator[](size_t i) {
resolve();
return alleles.at(i);
}
size_t AlleleVector::size() {
resolve();
return indices->size();
}
std::vector<Allele>::const_iterator AlleleVector::begin() {
resolve();
return alleles.begin();
}
std::vector<Allele>::const_iterator AlleleVector::end() {
resolve();
return alleles.end();
}
void AlleleVector::resolve() {
if (corrupted) {
throw ParserException(corruption_cause);
}
if (resolved) {
return;
}
resolved = true;
auto tokens = split(*line, VCFParser::DELIM);
if (tokens.size() != expected_ncols) {
stats.add(Stat::WARNING, 1);
throw ParserException("The row has " + std::to_string(tokens.size()) +
" number of columns whereas header has " + std::to_string(expected_ncols));
}
Format format{tokens[FORMAT]};
try {
for (int sample : *indices) {
alleles.push_back(format.parse(tokens.at(sample), variant + 1, *filter, stats));
}
} catch (ParserException& e) {
corrupted = true;
corruption_cause = e.get_message();
throw e;
}
}
std::vector<AlleleType> AlleleVector::vector() {
resolve();
std::vector<AlleleType> ret;
ret.reserve(alleles.size());
for (auto a: alleles) {
ret.push_back(a.alleleType());
}
return ret;
}
void VCFParser::register_handler(std::shared_ptr<VariantsHandler> handler, int order) {
handlers.emplace_back(handler, order);
}
VCFParser::VCFParser(std::istream& input, const VCFFilter& filter, VCFFilterStats& stats) :filter(filter),
input(input), line_num(0), stats(stats){}
std::vector<std::string> VCFParser::sample_names() {
return samples;
}
vector<Variant> VCFParser::parse_variants(const vector<string>& tokens, const Position& position) {
vector<Variant> variants;
string ref = tokens[REF];
vector<string> alts = split(tokens[ALT], ',');
for (const string& alt: alts) {
Variant variant(position, ref, alt);
if (is_of_interest(variant)) {
variants.emplace_back(position, ref, alt);
}
}
return variants;
}
void VCFParser::parse_header() {
string line;
while (getline(input, line)) {
++line_num;
if (line.substr(0, 2) == "##") {
continue;
}
if (line.substr(0, 1) == "#") {
line = line.substr(1);
auto tokens = split(line, DELIM);
number_of_samples = tokens.size() - FIELDS.size();
for (size_t i = 0; i < tokens.size(); i++) {
const string& token = tokens[i];
if (i < FIELDS.size()) {
if (token != FIELDS[i]) {
throw ParserException("Wrong header line: expected column " + FIELDS[i] +
"Found: " + token, line_num);
}
} else {
if (filter.apply(token)) {
samples.push_back(token);
filtered_samples.push_back(i);
}
}
}
return;
}
}
throw ParserException("No VCF header found in given file");
}
bool VCFParser::is_of_interest(const Variant& var) {
bool interesting = false;
for (const auto& handler: handlers) {
interesting |= handler.first->isOfInterest(var);
}
return interesting;
}
void VCFParser::parse_genotypes() {
std::sort(handlers.begin(), handlers.end(), [](decltype(*handlers.cbegin()) l, decltype(*handlers.cbegin()) r) {
return l.second < r.second;
});
string line;
std::shared_ptr<std::vector<size_t>> sample_indices = std::make_shared<std::vector<size_t>>(filtered_samples);
std::shared_ptr<VCFFilter> vcf_filter = std::make_shared<VCFFilter>(filter);
while (getline(input, line)) {
Rcpp::checkUserInterrupt();
++line_num;
if (line.empty() || std::all_of(line.begin(),line.end(),isspace)) {
continue;
}
vector<string> tokens = split(line, DELIM, FIELDS.size());
try {
if (tokens.size() < FIELDS.size()) {
throw ParserException("The row is too short");
}
Position position = parse_position(tokens);
vector<Variant> variants = parse_variants(tokens, position);
stats.add(Stat::OVERALL, variants.size());
if (tokens[FILTER] != "PASS" && tokens[FILTER] != ".") {
stats.add(Stat::NON_PASS, variants.size());
continue;
}
if (!filter.apply(position)) {
stats.add(Stat::BANNED, variants.size());
continue;
}
if (variants.empty()) {
continue;
}
std::shared_ptr<std::string> line_pointer = std::make_shared<std::string>(std::move(line));
for (size_t i = 0; i < variants.size(); i++) {
Variant& variant = variants[i];
auto alleles = std::make_shared<AlleleVector>(line_pointer, sample_indices, vcf_filter, stats, i,
FIELDS.size() + number_of_samples);
for (auto& handler: handlers) {
handler.first->processVariant(variant, alleles);
}
}
} catch (const ParserException& e) {
ParserException exception(e.get_message(), line_num);
handle_error(exception);
}
}
}
}
| true |
5912d670d62409fb884167ebf4839046cf55b39d | C++ | ali-ramadhan/cToan | /tests/movingaround/main.cpp | UTF-8 | 15,352 | 2.828125 | 3 | [] | no_license | #include <stack>
#include <vector>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include "SDLWrap_SDLEngine.hpp"
#include "SDLWrap_Surface.hpp"
#include "SDLWrap_Display.hpp"
#include "SDLWrap_Font.hpp"
#include "SDLWrap_Color.hpp"
#include "SDLWrap_FontSurface.hpp"
#include "SDLWrap_Enums.hpp"
#include "Logger.hpp"`
using namespace SDLWrap;
class GameState
{
public:
virtual void operator()() = 0;
static std::stack< boost::shared_ptr<GameState> > StateStack;
protected:
virtual void Logic() {}
virtual void Render() {}
};
std::stack< boost::shared_ptr<GameState> > GameState::StateStack;
class MenuState : public GameState, public EventHandler
{
public:
MenuState() {
CurrentChoice = 0;
CursorPosition = 0;
UpKeyDown = false;
DownKeyDown = false;
Surface *tmp_background = new Surface("gfx/titlescreen.bmp");
Background.reset(tmp_background);
Surface *tmp_cursor = new Surface("gfx/cursor.bmp");
Cursor.reset(tmp_cursor);
Font *tmp_textfont = new Font("fonts/optionlistfont.ttf");
TextFont.reset(tmp_textfont);
Color *tmp_textcolor = new Color(63, 107, 105);
TextColor.reset(tmp_textcolor);
FontSurface *tmp_newgame = new FontSurface("New Game", TextFont, *TextColor);
NewGame.reset(tmp_newgame);
NewGame->RenderTextBlended();
MenuOptionList.push_back(tmp_newgame);
FontSurface *tmp_settings = new FontSurface("Settings", TextFont, *TextColor);
Settings.reset(tmp_settings);
Settings->RenderTextBlended();
MenuOptionList.push_back(tmp_settings);
FontSurface *tmp_exitgame = new FontSurface("Exit Game", TextFont, *TextColor);
ExitGame.reset(tmp_exitgame);
ExitGame->RenderTextBlended();
MenuOptionList.push_back(tmp_exitgame);
}
void operator()() {
this->HandleEvent(); // Defined in the EventHandler class
this->Logic();
this->Render();
}
public: /* Event handlers */
void OnKeyDown(Key sym) {
switch (sym) {
case KEY_UP:
UpKeyDown = true;
break;
case KEY_DOWN:
DownKeyDown = true;
break;
case KEY_RETURN:
switch (CurrentChoice) {
case 0:
GameState::StateStack.push(Singleton::Instance()->NewGame); //TODO
break;
case 1:
GameState::StateStack.push(Singleton::Instance()->Settings); // TODO
break;
case 2:
// GameState::StateStack.push(Singleton::Instance()->Exit);
GameState::StateStack.pop(); // Should I auto pop or push Exit which pops twice?
break;
default:
;
break;
}
break;
case KEY_ESCAPE:
GameState::StateStack.pop();
break;
default:
;
break;
}
}
void OnKeyUp(Key sym) {
switch (sym) {
case KEY_UP:
UpKeyDown = false;
break;
case KEY_DOWN:
DownKeyDown = false;
break;
default:
;
break;
}
}
protected: /* Game state loop */
void Logic() {
if (UpKeyDown) {
CurrentChoice--;
if (CurrentChoice < 0)
CurrentChoice = 2; // User went above first option, loop around.
}
if (DownKeyDown) {
CurrentChoice++;
if (CurrentChoice > 2)
CurrentChoice = 0; // User tried to go below last (third) option, loop around.
}
CursorPosition = (CurrentChoice * 200) + 10;
}
void Render() {
Background.Blit(*(Singleton::Instance()->Screen));
for (unsigned int i = 0; i < MenuOptionList.size(); i++) {
MenuOptionList[i]->Blit(*(Singleton::Instance()->Screen), 500, (i * 200) + 10); }
Cursor.Blit(*(Singleton::Instance()->Surface), 450, CursorPosition);
}
private:
boost::scoped_ptr<Surface> Background;
boost::scoped_ptr<Surface> Cursor;
boost::shared_ptr<Font> TextFont;
boost::scoped_ptr<Color> TextColor;
shared_ptr<FontSurface> NewGame;
shared_ptr<FontSurface> Settings;
shared_ptr<FontSurface> ExitGame;
std::vector< boost::shared_ptr<FontSurface > MenuOptionList;
int CurrentChoice;
int CursorPosition;
bool UpKeyDown, DownKeyDown;
};
class NewGameState : public GameState
{
// Holy shit this one is gonna be BIG if the settings was 220+ lines.
};
class SettingsState : public GameState, public EventHandler
{
/* - Different background
* - List of 3 or 4 options (FontSurfaces)
* - Each with their own options like (resolution: 800x600, 1024x768, etc.)
* - Up and down to change options.
* - Left/Right or Space to toggle options
* - Option looping, yes
* - Different colored font for chosen options. (Purple = chosen, orange = not) etc. example
*/
public:
SettingsState() {
CurrentChoice = ResolutionChoice = DifficultyChoice = FullscreenChoice = 0;
UpKeyDown = DownKeyDown = RightKeyDown = LeftKeyDown = false;
CursorPosition = 0;
Surface *tmp_background = new Surface("gfx/settingsbackground.bmp");
Background.reset(tmp_background);
Surface *tmp_cursor = new Surface("gfx/settingscursor.bmp");
Cursor.reset(tmp_cursor);
Font *tmp_textfont = new Font("fonts/optionlistfont.ttf", 26);
TextFont.reset(tmp_textfont);
Color *tmp_textcolor = new Color(46, 124, 49);
TextColor.reset(tmp_color);
FontSurface *tmp_resolution = new FontSurface("Resolution", TextFont, *TextColor);
FontSurface *tmp_res1280 = new FontSurface("1280x1024", TextFont, *TextColor);
FontSurface *tmp_res1024 = new FontSurface("1024x768", TextFont, *TextColor);
FontSurface *tmp_res800 = new FontSurface("800x600", TextFont, *TextColor);
FontSurface *tmp_difficulty = new FontSurface("Difficulty", TextFont, *TextColor);
FontSurface *tmp_pisseasy = new FontSurface("Piss Easy", TextFont, *TextColor);
FontSurface *tmp_theusual = new FontSurface("The Usual", TextFont, *TextColor);
FontSurface *tmp_fuckme = new FontSurface("Fuck Me", TextFont, *TextColor);
FontSurface *tmp_fullscreen = new FontSurface("Fullscreen", TextFont, *TextColor);
FontSurface *tmp_yes = new FontSurface("Yes", TextFont, *TextColor);
FontSurface *tmp_no = new FontSurface("No", TextFont, *TextColor);
FontSurface *tmp_back = new FontSurface("Back", TextFont, *TextColor);
Resolution.reset(tmp_resolution);
Res1280.reset(tmp_1280);
Res1024.reset(tmp_1024);
Res800.reset(tmp_800);
Difficulty.reset(tmp_difficulty);
PissEasy.reset(tmp_pisseasy);
TheUsual.reset(tmp_theusual);
FuckMe.reset(tmp_fuckme);
Fullscreen.reset(tmp_fullscreen);
Yes.reset(tmp_yes);
No.reset(tmp_no);
Back.reset(tmp_back);
SettingsOptionList.push_back(Resolution);
SettingsOptionList.push_back(Res1280);
SettingsOptionList.push_back(Res1024);
SettingsOptionList.push_back(Res800);
SettingsOptionList.push_back(Difficulty);
SettingsOptionList.push_back(PissEasy);
SettingsOptionList.push_back(TheUsual);
SettingsOptionList.push_back(FuckMe);
SettingsOptionList.push_back(Fullscreen);
SettingsOptionList.push_back(Yes);
SettingsOptionList.push_back(No);
SettingsOptionList.push_back(Back);
for (unsigned int i = 0; i < SettingsOptionList.size(); i++) {
SettingsOptionList[i]->RenderTextBlended(); }
}
void OnKeyDown(Key sym) {
switch (sym) {
case KEY_UP:
UpKeyDown = true;
break;
case KEY_DOWN:
DownKeyDown = true;
break;
case KEY_RIGHT:
RightKeyDown = true;
break;
case KEY_LEFT:
LeftKeyDown = true;
break;
case KEY_RETURN:
switch (CurrentChoice) {
case 3:
GameState::StateStack.pop();
break;
default:
;
break;
}
break;
case KEY_ESCAPE:
GameState::StateStack.pop();
break;
default:
;
break;
}
}
protected:
Logic() {
if (UpKeyDown) {
CurrentChoice--;
if (CurrentChoice < 0)
CurrentChoice = 3;
}
if (DownKeyDown) {
CurrentChoice++;
if (CurrentChoice > 3)
CurrentChoice = 0;
}
if (RightKeyDown) {
switch (CurrentChoice) {
case 0:
ResolutionChoice++;
if (ResolutionChoice > 2)
ResolutionChoice = 0;
break;
case 1:
DifficultyChoice++;
if (DifficultyChoice > 2)
DifficultyChoice = 0;
break;
case 2:
FullscreenChoice++;
if (FullscreenChoice > 1)
DifficultyChoice = 0;
break;
default:
;
break;
}
}
if (LeftKeyDown) {
switch (CurrentChoice) {
case 0:
ResolutionChoice--;
if (ResolutionChoice < 0)
ResolutionChoice = 2;
break;
case 1:
DifficultyChoice--;
if (DifficultyChoice < 0)
DifficultyChoice = 2;
break;
case 2:
FullscreenChoice++;
if (FullscreenChoice < 0)
DifficultyChoice = 1;
break;
default:
;
break;
}
}
CursorPosition = (CurrentChoice + 1) * 100;
}
void Render() {
Background.Blit(*(Singleton::Instance->Screen));
Resolution.Blit(*(Singleton::Instance->Screen), 110, 100);
Difficulty.Blit(*(Singleton::Instance->Screen), 110, 200);
Fullscreen.Blit(*(Singleton::Instance->Screen), 110, 300);
Back.Blit(*(Singleton::Instance->Screen), 110, 400);
Cursor.Blit(*(Singleton::Instance->Screen), 30, CursorPosition);
// Blit the choices to the right.
// If chosen, color c2
// If not, color c1
// Too much trouble for now though, come back later. TODO
// Maybe redesign the vectors.
}
priviate:
int CurrentChoice, ResolutionChoice, DifficultyChoice, FullscreenChoice;
bool UpKeyDown, DownKeyDown, LeftKeyDown, RightKeyDown;
int CursorPosition;
boost::scoped_ptr<Surface> Background;
boost::scoped_ptr<Surface> Cursor;
boost::shared_ptr<Font> TextFont;
boost::scoped_ptr<Color> TextColor;
boost::scoped_ptr<color> ChosenTextColor;
boost::shared_ptr<FontSurface> Resolution;
boost::shared_ptr<FontSurface> Res1280;
boost::shared_ptr<FontSurface> Res1024;
boost::shared_ptr<FontSurface> Res800;
boost::shared_ptr<FontSurface> Difficulty;
boost::shared_ptr<FontSurface> PissEasy;
boost::shared_ptr<FontSurface> TheUsual;
boost::shared_ptr<FontSurface> FuckMe;
boost::shared_ptr<FontSurface> Fullscreen;
boost::shared_ptr<FontSurface> Yes;
boost::shared_ptr<FontSurface> No;
boost::shared_ptr<FontSurface> Back;
std::vector< boost::shared_ptr<FontSurface> > SettingsOptionList;
};
class ExitState : public GameState
{
public:
void operator()() {
StateStack.pop(); // Popping self off to empty the stack and exit the game loop.
}
};
class Singleton : public EventHandler
{
private:
/* Constructor + instance pointer */
static Singleton *InstancePtr;
Singleton() {
// Pushing the exit state first.
ExitState *tmp_exit = new ExitState();
Exit.reset(tmp_exit);
GameState::StateStack.push(Exit);
// Menu pushed next and no more, it's the first state anyways.
MenuState *tmp_menu = new MenuState();
Menu.reset(tmp_menu);
GameState::StateStack.push(Menu);
SDLEngine *tmp_engine = new SDLEngine(VIDEO);
Engine.reset(tmp_engine);
Display *tmp_screen = new Display(SWSURFACE);
Display.reset(tmp_screen);
}
public:
/* Instance Management*/
static Singleton* Instance() {
if (InstancePtr == NULL)
InstancePtr = new Singleton();
return InstancePtr;
}
/* States */
boost::shared_ptr<ExitState> Exit;
boost::shared_ptr<MenuState> Menu;
boost::shared_ptr<NewGameState> NewGame; //TODO
boost::shared_ptr<SettingsState> Settings; //TODO
private:
/* SDL Objects */
boost::scoped_ptr<SDLEngine> Engine;
boost::scoped_ptr<Display> Screen;
};
Singleton *Singleton::InstancePtr = NULL;
int
main()
{
Singleton::Instance(); // Setting up the singleton.
while (!GameState::StateStack.empty()) {
GameState::StateStack.top()(); // Syntax looks weird but it works xD
}
return 10;
}
| true |
45d251d1626241fdfef18c1af3b47f0a2ea1149b | C++ | firewood/topcoder | /atcoder/agc_015/b.cpp | UTF-8 | 438 | 2.671875 | 3 | [] | no_license | // B.
#include <iostream>
#include <algorithm>
#include <sstream>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
typedef long long LL;
int main(int argc, char *argv[])
{
string s;
cin >> s;
LL n = s.length(), ans = 0;
for (LL i = 0; i < n; ++i) {
if (s[i] == 'U') {
ans += (n - i - 1);
ans += i * 2;
} else {
ans += (n - i - 1) * 2;
ans += i;
}
}
cout << ans << endl;
return 0;
}
| true |
71e36b7760de0866b72bf4436d5ad7f7f5d6bd03 | C++ | Tainel/cpn | /source/algorithms/dynamic_programming.cpp | UTF-8 | 712 | 3.078125 | 3 | [] | no_license | /// SOURCE - DYNAMIC PROGRAMMING
/** Source file for Dynamic Programming. */
#ifndef __DYNAMIC_PROGRAMMING__
#define __DYNAMIC_PROGRAMMING__
//_____________________________________________________________________________
// ------ IMPLEMENTATION ------ //
/** Returns dp of size k+1 such that dp[i] is the maximum possible value after
* evaluating [0,n) with capacity i. {O(n*k),O(k)} */
template<class T>vector<T>knapsack(vector<T>&val,vector<int>&w,int k){
int n=sz(val); vector<T>dp(k+1);
forn(i,n)
for(int j=k;j>=w[i];--j)
dp[j]=max(dp[j],dp[j-w[i]]+val[i]);
return dp;
}
//_____________________________________________________________________________
#endif // __DYNAMIC_PROGRAMMING__
| true |
88ccb2e22e563ed7b9a481e0c9280dc0307f8ba1 | C++ | Bootz/BlueCodes | /FunScripts/XpForPvp.cpp | UTF-8 | 1,017 | 2.6875 | 3 | [] | no_license | /*
Author: Chase(http://wowemuf.org)
*/
class System_Xpforpvp : public PlayerScript
{
public:
System_Xpforpvp() : PlayerScript("System_Xpforpvp") {}
void OnPVPKill(Player* killer, Player* killed)
{
uint32 killerlvl = killer->getLevel();
uint32 killedlvl = killed->getLevel();
int32 diff = killerlvl-killedlvl;
uint32 XPLow = (killedlvl*5+45)*(1+0.05*diff);
uint32 XPHigh = (killedlvl*5+45)*(1+0.05*diff);
uint32 minusgold = killer->GetMoney()-(diff*10000);
uint32 plusgold = killed->GetMoney()+(diff*10000);
uint32 killergold = killer->GetMoney();
uint32 killedgold = killed->GetMoney();
uint32 plusgold2= killedgold+killergold;
if (killerlvl < killedlvl +1)
killer->GiveXP(XPHigh , killed);
else
if (diff > 10)
if (killergold > minusgold)
{
killer->SetMoney(minusgold);
killed->SetMoney(plusgold);
}
else
{
killed->SetMoney(plusgold2);
killer->SetMoney(0);
}
else
if(0 < diff && diff <10)
killer->GiveXP(XPLow , killed);
}
};
| true |
cc557ab9dbaca38bae1fcf418649b2653203c381 | C++ | Pbra1484/DataStructures | /DataStructures/Controller/DataStructureController.cpp | UTF-8 | 9,966 | 3.25 | 3 | [] | no_license | //
// DataStructureController.cpp
// DataStructures
//
// Created by Brashear, Patrick on 2/8/17.
// Copyright © 2017 Brashear, Patrick. All rights reserved.
//
#include "DataStructureController.hpp"
#include <iostream>
#include "../Model/IntNodeArray.hpp"
#include "../Model/Array.hpp"
#include "../Model/List.hpp"
#include "../Model/BinarySearchTree.hpp"
#include "../Model/AVLTree.hpp"
#include "FileController.hpp"
#include "../Model/HashTable.hpp"
using namespace std;
DataStructureController :: DataStructureController()
{
wordNode = Node<string>("");
numberNode = Node<int>();
}
void DataStructureController:: testNodes()
{
cout << "Node contents for Node<string>" <<endl;
cout << wordNode.getNodeData() << endl;
cout << "Here is the Node<int>" << endl;
cout << numberNode.getNodeData() << endl;
}
void DataStructureController :: start()
{
cout << "starting" << endl;
// testAdvancedFeatures();
// testNodes();
// cout << "Switing to aray testing" << endl;
// testIntArray();
// testFoodQueue();
// testCurcularList();
// testDoubleList();
// testIntStack();
// testList();
// testBinarySearchTreeOperations();
// testGraph();
testHashTable();
cout << "Finished Testing" << endl;
}
void DataStructureController :: testIntArray()
{
cout << "Testing the array" << endl;
IntNodeArray temp = IntNodeArray(3);
for(int index = 0; index < temp.getSize(); index++)
{
cout << temp.getFromIndex(index) << " is at spot " << index << endl;
}
for(int index = 0; index < temp.getSize(); index++)
{
temp.setAtIndex(index, index);
}
for(int index = 0; index < temp.getSize(); index++)
{
cout << temp.getFromIndex(index) << " is at spot " << index << endl;
}
}
void DataStructureController :: testAdvancedFeatures()
{
int showDestructor = 0;
if(showDestructor < 1)
{
Array<string> words = Array<string>(5);
cout << "Destrouctor mesages next" << endl;
}
Array<string> words = Array<string>(4);
words.setAtIndex(0, "at zero");
words.setAtIndex(3, " in the last spot");
Array<string> copiedWords = Array<string>(words);
cout << "These should match:" << endl;
cout << words.getFromIndex(0) << " should be the same as " << copiedWords.getFromIndex(0) << endl;
copiedWords.setAtIndex(2, "Changed the contents of the copied Array");
}
void DataStructureController:: testList()
{
List<int> list;
list.addFront(1);
list.addEnd(3);
list.addAtIndex(1, 2);
cout << "should be 1 2 3" << endl;
for(int index = 0; index < list.getSize(); index++)
{
cout << list.getAtIndex(index) << endl;
}
list.remove(1);
list.setAtIndex(1, 2);
cout << "shuld be 1 2" << endl;
for(int index = 0; index < list.getSize(); index++)
{
cout << list.getAtIndex(index) << endl;
}
cout << "should be 1 and is " << list.getFront()->getNodeData() << endl;
cout << "should be 2 and is " << list.getEnd()->getNodeData() << endl;
}
void DataStructureController :: testIntStack()
{
Stack<int> numbers;
numbers.add(0);
numbers.push(1);
cout << "the top is " << numbers.peek() << " and should be 1" << endl;
numbers.push(2);
cout << "the size is " << numbers.getSize() << " and should be 3" << endl;
cout << "the top is " << numbers.peek() << " and should be 2" << endl;
int removed = numbers.remove(2);
cout << "the revomed value is " << removed << " and should be 2" << endl;
numbers.add(2345);
numbers.add(202350926);
cout << "the size is " << numbers.getSize() << " and should be 4" << endl;
numbers.pop();
cout << "the size is " << numbers.getSize() << " and should be 3" << endl;
}
void DataStructureController :: testFoodQueue()
{
Queue<FoodItem> tastyFood;
FoodItem dunkin("grows stuff");
tastyFood.enqueue(dunkin);
FoodItem boring;
tastyFood.add(boring);
cout << "thie size is " << tastyFood.getSize() << " and should be 2" << endl;
FoodItem removed = tastyFood.dequeue();
cout << "The item removed from the queue was: " << removed.getFoodName() << " and should be : grows stuff" << endl;
cout << "the size is " << tastyFood.getSize() << " and should be 1"<< endl;
tastyFood.add(dunkin);
cout << "the size is " << tastyFood.getSize() << " and should be 2" << endl;
tastyFood.remove(0);
cout << "the front of the queue is " << tastyFood.peek().getFoodName() << endl;
}
void DataStructureController :: testCurcularList()
{
CircularList<int> roundInts;
roundInts.add(0);
roundInts.add(1);
roundInts.add(2);
roundInts.add(3);
cout << "this should be 1 and is " << roundInts.getFromIndex(1) << endl;
roundInts.remove(1);
cout << "this should be 2 and is " << roundInts.getFromIndex(1) << endl;
roundInts.setAtIndex(1, 9001);
cout << "This should be over 9000 and is " << roundInts.getFromIndex(1) << endl;
}
void DataStructureController :: testDoubleList()
{
DoubleList<int> dInts;
dInts.add(0);
dInts.add(1);
dInts.add(2);
dInts.add(3);
cout << "this should be 1 and is " << dInts.getFromIndex(1) << endl;
dInts.remove(1);
cout << "this should be 2 and is " << dInts.getFromIndexFast(1) << endl;
}
void DataStructureController :: testBinarySearchTreeOperations()
{
BinarySearchTree<int> numbers;
numbers.insert(9843);
numbers.insert(10);
cout << "Size should be 2 and is: " << numbers.getSize() << endl;
numbers.insert(43);
numbers.insert(-123);
numbers.insert(23465);
cout << "Size should be 5 and is: " << numbers.getSize() << endl;
numbers.insert(10); // won't go in
numbers.insert(43243);
numbers.insert(-45677654);
numbers.insert(92165);
cout << "Size should be 8 and is: " << numbers.getSize() << endl;
cout << "In order traversal should be: \n\t-45677654 \n\t-123 \n\t10 \n\t43 \n\t9843 \n\t23465 \n\t43243 \n\t92165" << endl;
numbers.inOrderTraversal();
numbers.postOrderTraversal();
numbers.remove(43);
numbers.preOrderTraversal();
cout << "Height should be 4 and is: " << numbers.getHeight() << endl;
cout << "Balanced should be false || 0 and is: " << numbers.isBalanced() << endl;
}
void DataStructureController :: testBinarySearchData()
{
FileController fileData;
Timer treeTimer;
treeTimer.startTimer();
BinarySearchTree<CrimeData> crimeTree = fileData.readCrimeDataToBinarySearchTree("/Users/cody.henrichsen/Documents/crimes.csv");
treeTimer.stopTimer();
int count = crimeTree.getSize();
int height = crimeTree.getHeight();
bool complete = crimeTree.isComplete();
bool balanced = crimeTree.isBalanced();
cout << "The count of the tree is: " << count << ", the height is " << height << ".\n The tree's balanced status is " << balanced << ", and its complete status is " << complete << endl;
cout << "The time to read in the tree was: " << endl;
treeTimer.displayTimerInformation();
}
void DataStructureController :: testAVLTreeOperations()
{
AVLTree<int> numbers;
numbers.insert(9843);
numbers.insert(10);
numbers.insert(43);
numbers.insert(-123);
numbers.insert(23465);
numbers.insert(10); // won't go in
numbers.insert(43243);
numbers.insert(-45677654);
numbers.insert(92165);
cout << "Size should be 8 and is: " << numbers.getSize() << endl;
cout << "In order traversal should be: \n\t-45677654 \n\t-123 \n\t10 \n\t43 \n\t9843 \n\t23465 \n\t43243 \n\t92165" << endl;
numbers.inOrderTraversal();
cout << "Height should be 4 and is: " << numbers.getHeight() << endl;
cout << "Balanced should be true || 1 and is: " << numbers.isBalanced() << endl;
}
void DataStructureController :: testAVLData()
{
FileController fileData;
Timer treeTimer;
treeTimer.startTimer();
AVLTree<CrimeData> crimeTree = fileData.readCrimeDataToAVLTree("/Users/cody.henrichsen/Documents/crimes.csv");
treeTimer.stopTimer();
int count = crimeTree.getSize();
int height = crimeTree.getHeight();
bool complete = crimeTree.isComplete();
bool balanced = crimeTree.isBalanced();
cout << "The count of the tree is: " << count << ", the height is " << height << ".\n The tree's balanced status is " << balanced << ", and its complete status is " << complete << endl;
cout << "The time to read in the tree was: " << endl;
treeTimer.displayTimerInformation();
}
void DataStructureController :: testGraph()
{
Graph<string> words;
words.addVertex("number");
words.addVertex("one");
words.addVertex("two");
words.addVertex("three");
words.addVertex("Three.4");
words.addVertex("Thre.453");
words.addEdge(0,1);
words.addEdge(0,2);
words.addEdge(0,3);
words.addEdge(3,4);
words.addEdge(3,5);
words.breadthFirstTraversal(words, 0);
words.depthFirstTraversal(words, 0);
}
void DataStructureController :: testHashTable()
{
HashTable<string> table;
table.add("one");
table.add("two");
table.add("three");
table.add("four");
table.add("five");
table.add("six");
table.add("seven");
table.add("eight");
table.add("nine");
table.add("ten");
table.displayContents();
}
| true |
66225d73a1311455583840a22f164841ab4f8f8d | C++ | oshogun/Dogoo | /src/Player.cpp | UTF-8 | 1,492 | 2.984375 | 3 | [
"Unlicense"
] | permissive | #include "Player.h"
Player::Player() : abilities(6)
{
}
void Player::setName (const std::string _name)
{
name = _name;
}
std::string Player::getName()
{
return name;
}
void Player::setHP (int hp)
{
HP = hp;
}
void Player::setMP(int mp)
{
MP = mp;
}
int Player::getHP()
{
return HP;
}
int Player::getMP()
{
return MP;
}
void Player::setRace(RACES _race)
{
race = _race;
}
RACES Player::getRace()
{
return race;
}
void Player::setPlayerStatus(PLAYER_STATUS _status)
{
status = _status;
}
PLAYER_STATUS Player::getPlayerStatus()
{
return status;
}
void Player::setStr(unsigned str)
{
abilities[ABILITIES::STR] = str;
}
void Player::setDex(unsigned dex)
{
abilities[ABILITIES::DEX] = dex;
}
void Player::setInt(unsigned intelligence)
{
abilities[ABILITIES::INT] = intelligence;
}
void Player::setWis(unsigned wis)
{
abilities[ABILITIES::WIS] = wis;
}
void Player::setCha(unsigned cha)
{
abilities[ABILITIES::CHA] = cha;
}
unsigned Player::getStr()
{
return abilities[ABILITIES::STR];
}
unsigned Player::getDex()
{
return abilities[ABILITIES::DEX];
}
unsigned Player::getInt()
{
return abilities[ABILITIES::INT];
}
unsigned Player::getWis()
{
return abilities[ABILITIES::WIS];
}
unsigned Player::getCha()
{
return abilities[ABILITIES::CHA];
}
void Player::setAge(int _age)
{
age = _age;
}
int Player::getAge()
{
return age;
}
unsigned Player::getLevel()
{
return level;
}
void Player::setLevel(unsigned _level)
{
level = _level;
}
void Player::levelUp()
{
level++;
}
| true |
21b2e74ffeca7225e10eb0d18d8cdd9b07d0bcb3 | C++ | NikolausDemmel/KTH-AI-Project | /opposition/mnp/board.cc | UTF-8 | 15,339 | 2.828125 | 3 | [] | no_license | /*
* board.cc
*
* Created on: 20.09.2011
* Author: astridrupp
*/
#include <algorithm>
#include <sstream>
#include <queue>
#include <vector>
#include "board.h"
namespace mnp {
////////////////////////////////////////////////////////////////////////////////
// CONSTRUCTION
////////////////////////////////////////////////////////////////////////////////
// FIXME: make sure all members are set up properly by parseBoard
Board::Board(const char* board) {
parseBoard(board);
}
Board::Board(string board) {
parseBoard(board.c_str());
}
Board::Board(const char* fileName, unsigned int boardNumber) {
parseBoardFromFile(fileName, boardNumber);
}
Board::~Board() {
// FIXME
}
void Board::parseBoardFromFile(const char *fileName, size_t boardNumber) {
string str;
ifstream fileStream(fileName);
ostringstream stringStream;
while(boardNumber>0) {
do {
getline(fileStream,str);
} while(str.at(0)!=';');
boardNumber--;
}
getline(fileStream,str);
while(str.at(0)!=';') {
stringStream<<str<<"\n";
getline(fileStream,str);
}
parseBoard(stringStream.str().c_str());
// cout<<"H: "<<mHeight<<" W: "<<mWidth<<endl;
}
void Board::printBoard(uint8_t print_flags) const {
cout << boardToString(print_flags) << endl;
}
//creates a String that can be printed
string Board::boardToString(uint8_t printFlags, const vector<TileGraphNode> * const nodes, bool print_dead, bool print_dist) const
{
stringstream board;
for(int y = mHeight-1; y >= 0; --y) {
for (uint x = 0; x < mWidth; ++x) {
index_t index = tileIndex(x, y);
board << flagString(mTiles[index], printFlags);
if (mPlayerIndex == index)
if (mTiles[index].isGoal())
board << '+';
else
board << '@';
else
board << tileCharacter(mTiles[index], (nodes ? &(nodes->at(index)) : 0), print_dead, print_dist);
board << endFlagString(printFlags);
}
board << '\n';
}
return board.str();
}
// applies a move, so it only moves a box
void Board::applyMove(const Move &move, SearchType type = Forward) {
index_t curr = move.getBoxIndex();
index_t next = move.getNextIndex(this);
updateHash(mZobristBoxes[curr]);
updateHash(mZobristPlayer[mPlayerIndex]);
int box = mTiles[curr].removeBox();
mTiles[next].setBox(box);
mBoxes[box] = next;
if (type == Forward) {
setPlayerIndex(curr);
mMissingGoals += (mTiles[curr].isGoal() ? 1 : 0);
mMissingGoals -= (mTiles[next].isGoal() ? 1 : 0);
}
else {
setPlayerIndex(tileIndex(next, move.getMoveDir(), 1));
// dont care about missing goals
}
updateHash(mZobristBoxes[next]);
updateHash(mZobristPlayer[mPlayerIndex]);
}
// move the box back
void Board::undoMove(const Move &move, SearchType type = Forward) {
index_t curr = move.getBoxIndex();
index_t next = move.getNextIndex(this);
updateHash(mZobristBoxes[next]);
updateHash(mZobristPlayer[mPlayerIndex]);
int box = mTiles[next].removeBox();
mTiles[curr].setBox(box);
mBoxes[box] = curr;
if (type == Forward) {
setPlayerIndex(move.getPlayerIndex(this));
mMissingGoals -= (mTiles[curr].isGoal() ? 1 : 0);
mMissingGoals += (mTiles[next].isGoal() ? 1 : 0);
}
else {
setPlayerIndex(next);
}
updateHash(mZobristBoxes[curr]);
updateHash(mZobristPlayer[mPlayerIndex]);
}
bool Board::doAction(Dir to) {
index_t next = tileIndex(mPlayerIndex, to);
if( mTiles[next].isWall() ) {
throw "[board] banging head in the wall :-/";
} else if (mTiles[next].isBox() ) {
cout << "push at " << indexToPos(mPlayerIndex).toString() << cDirs[to] << endl;
Move move(next, to);
applyMove(move, Forward);
return true;
} else {
setPlayerIndex(next);
return false;
}
}
void Board::undoAction(Dir from, bool unpush){
index_t prev = tileIndex(mPlayerIndex, from, -1);
if (unpush) {
Move move(mPlayerIndex, from);
undoMove(move, Forward);
} else {
if (!mTiles[prev].isFree()) throw "[board] banging back in the wall :-/";
else setPlayerIndex(prev);
}
}
void Board::simulateActions(const char* actions){
bool pushed = false;
switch(*actions) {
case ' ':
return simulateActions(++actions);
case 'U': case 'u': case '0':
cout << "up" << endl;
pushed = doAction(Up);
printBoard();
#ifdef INFO
cin.get();
#endif
simulateActions(++actions);
undoAction(Up, pushed);
return;
case 'D': case 'd': case '1':
cout << "down" << endl;
pushed = doAction(Down);
printBoard();
#ifdef INFO
cin.get();
#endif
simulateActions(++actions);
undoAction(Down, pushed);
return;
case 'L': case 'l': case '2':
cout << "left" << endl;
pushed = doAction(Left);
printBoard();
#ifdef INFO
cin.get();
#endif
simulateActions(++actions);
undoAction(Left, pushed);
return;
case 'R': case 'r': case '3':
cout << "right" << endl;
pushed = doAction(Right);
printBoard();
#ifdef INFO
cin.get();
#endif
simulateActions(++actions);
undoAction(Right, pushed);
return;
case '\0':
return;
default:
cout << "[board] invalid character in simulate actions: \'\\" << (int)*actions << "\'\n";
return;
}
}
// FIXME: would it not be quicker to incrementally update all the reachability information
// also maybe store the boxes as a list of positions
void Board::generateMoves(vector<Move> &moves, SearchType type)
{
if (type == Forward) {
visitTile(mPlayerIndex, moves);
//cout << "size of all moves forward" << moves.size() << endl;
}
else {
//first iteration: do not use start pos of player...
vector<index_t> possiblePlayerInd;
vector<pair<uint64_t,uint64_t>> hashes;
if(mPlayerIndex == 0)
{
//cout << "should only happen at the beginning!" << endl;
getAllPlayerPosHashBack(possiblePlayerInd, hashes, false);
//cout << "size of possible player indices " << possiblePlayerInd.size() << endl;
foreach(index_t tile, possiblePlayerInd){
vector<Move> tempmoves;
reverseVisitTile(tile, tempmoves); // works quite good with our flags, moves are only once in the vector :)
//cout << "size of tempmoves " << tempmoves.size() << endl;
foreach(Move move, tempmoves){
moves.push_back(move);
}
//cout << "size of all moves " << moves.size() << endl;
}
}
else{
reverseVisitTile(mPlayerIndex, moves);
//cout << "playerindex:" << mPlayerIndex << endl;
//cout << "size of all moves in else " << moves.size() << endl;
}
}
#ifdef VERBOSE_GENERATE_MOVES
cout << boardToString(Tile::VisitedFlag | Tile::ExtraFlag);
cout << "Possible moves:" << endl;
for (vector<Move>::iterator iter = moves.begin(); iter != moves.end(); ++iter) {
cout << iter->toString(this) << endl;
}
#endif
clearFlags();
}
void Board::getAllPlayerPosHashForward(vector<index_t> &possiblePlayerInd, vector<pair<uint64_t, uint64_t>> &hashes, bool hash){
updateHash(mZobristPlayer[mPlayerIndex]);
vector<Move> moves;
visitTile(mPlayerIndex, moves);
clearFlags();
foreach(Move move, moves)
{
index_t next = move.getPlayerIndex(this);
possiblePlayerInd.push_back(next);
//cout << "possible player index pushback forward" << next << endl;
if(hash == true)
{
setPlayerIndex(next);
updateHash(mZobristPlayer[next]);
//cout << "pushback hash forward" << getHash() <<endl;
hashes.push_back(pair<uint64_t, uint64_t>(getHash(),computeHash2Value()));
updateHash(mZobristPlayer[next]);
}
}
setPlayerIndex(mInitialPlayerIndex);
updateHash(getZobristPlayer(mPlayerIndex));
}
void Board::getAllPlayerPosHashBack(vector<index_t> &possiblePlayerInd, vector<pair<uint64_t, uint64_t>> &hashes, bool hash){
updateHash(mZobristPlayer[mPlayerIndex]);
for(int i = 0; i<mTiles.size();i++)
{
if(mTiles[i].isGoal()){
foreach(Dir dir, cDirs){
index_t next = tileIndex(i, dir);
if(mTiles[next].isFree()){
possiblePlayerInd.push_back(next); // TODO: do not save same player pos several times
//cout << "possible player index pushback back" << next << endl;
if(hash == true){
setPlayerIndex(next);
updateHash(mZobristPlayer[mPlayerIndex]);
//cout << "pushback hash back " << getHash() <<endl;
hashes.push_back(pair<uint64_t, uint64_t>(getHash(), computeHash2Value()));
updateHash(mZobristPlayer[mPlayerIndex]);
}
}
}
}
}
setPlayerIndex(0);
updateHash(mZobristPlayer[mPlayerIndex]);
}
void Board::visitTile(index_t tile, vector<Move> &moves)
{
if ( !(mTiles[tile].flagsSet(Tile::VisitedFlag)) ) {
mTiles[tile].setFlags(Tile::VisitedFlag);
foreach (Dir dir, cDirs) {
index_t next = tileIndex(tile, dir);
if (mTiles[next].isBox() && mTiles[tileIndex(next, dir)].isFree() && !mTiles[tileIndex(next, dir)].isDead()) {
mTiles[tile].setFlags(Tile::ExtraFlag);
moves.push_back(Move(next, dir));
} else if (mTiles[next].isFree()) {
visitTile(next, moves);
}
}
}
}
void Board::reverseVisitTile(index_t tile, vector<Move> &moves)
{
if ( !(mTiles[tile].flagsSet(Tile::VisitedFlag)) ) {
mTiles[tile].setFlags(Tile::VisitedFlag);
foreach (Dir dir, cDirs) {
index_t next = tileIndex(tile, dir);
if (mTiles[next].isBox() && mTiles[tileIndex(tile, invertDirection(dir))].isFree() && !mTiles[tile].isDead()) {
mTiles[tile].setFlags(Tile::ExtraFlag);
moves.push_back(Move(next, invertDirection(dir)));
} else if (mTiles[next].isFree()) {
reverseVisitTile(next, moves);
}
}
}
}
void Board::clearFlags() {
for (uint i = 0; i < mSize; ++i) {
mTiles[i].clearFlags();
}
}
bool Board::isSolved() {
return mMissingGoals == 0;
}
void Board::parseBoard(const char* board) {
// TODO: detect malformed boards and throw error
mBoxes.clear();
mGoals.clear();
mWidth = 0;
mHeight = 0;
uint currWidth = 0;
for (uint i = 0; i < strlen(board); ++i) {
if (board[i] == '\n') {
++mHeight;
mWidth = max(mWidth, currWidth);
currWidth = 0;
} else {
++currWidth;
}
}
mSize = mWidth*mHeight;
mTiles.resize(mSize);
if (mSize == 0) {
throw "[board] board of size 0 ???";
}
uint y = mHeight - 1;
uint x = 0;
for (uint i = 0; i < strlen(board); ++i) {
if (board[i] == '\n') {
// FIXME: maybe find all unreachable regions and make them "invalid" straight away.
// for now we just fill trailing tiles with walls.
for (; x < mWidth; ++x) {
mTiles[tileIndex(x, y)].static_type = Tile::Wall;
}
x = 0;
--y;
} else {
index_t tile = tileIndex(x, y);
mTiles[tile] = parseTile(board[i]);
if (board[i] == '$' || board[i] == '*') {
mTiles[tile].box = mBoxes.size(); // set the number of the box to the index on the mBoxes list
mBoxes.push_back(tile);
}
if (board[i] == '.' || board[i] == '+' || board[i] == '*') {
mGoals.push_back(tile);
}
if (board[i] == '@' || board[i] == '+') {
setPlayerIndex(tile);
}
++x;
}
}
// FIXME: compute group info
initializeZobrist();
mHashValue = computeHashValue();
mMissingGoals = countMissingGoals();
mInitialPlayerIndex = mPlayerIndex;
mIndexBits = calculateIndexBits(mSize);
}
uint Board::calculateIndexBits(uint size) {
return ceil(log2((float)size));
}
// tile from character ignoring the player and the boxes
Tile Board::parseTile(char c) {
switch(c) {
case ' ':
case '$':
case '@':
return Tile(Tile::Empty);
case '#':
return Tile(Tile::Wall);
case '.':
case '+':
case '*':
return Tile(Tile::Goal);
default:
throw "Invalid tile character.";
}
}
// character from tile ignoring the player
char Board::tileCharacter(const Tile &tile, const TileGraphNode * const node, bool print_dead, bool print_dist) {
switch(tile.static_type) {
case Tile::Empty:
if (tile.isBox())
return '$';
else {
if (node) {
return '0' + node->distance;
}
else{
if(print_dead &&tile.isDead())
return '-';
if(print_dist) {
return tile.distanceClosestGoal%10 + '0';
} else
return ' ';
}
}
case Tile::Wall:
return '#';
case Tile::Goal:
if (tile.isBox())
return '*';
else
return '.';
default:
throw "Invalid tile type.";
}
}
const char* Board::flagString(const Tile &tile, uint8_t flags) {
if ((Tile::VisitedFlag & flags) && tile.flagsSet(Tile::VisitedFlag))
if ((Tile::ExtraFlag & flags) && tile.flagsSet(Tile::ExtraFlag))
return "\e[43m";
else
return "\e[42m";
else
return "";
}
const char* Board::endFlagString(uint8_t flags) {
if (flags)
return "\e[0m";
else
return "";
}
uint Board::countMissingGoals() const {
uint count = 0;
for(index_t i=0; i < mSize; ++i)
if( (mTiles[i].isGoal()) && !(mTiles[i].isBox()) )
++count;
return count;
}
void Board::initializeZobrist() {
mZobristBoxes.clear();
mZobristPlayer.clear();
for(index_t i = 0; i < mSize; ++i) {
mZobristBoxes.push_back(rand64());
mZobristPlayer.push_back(rand64());
}
}
// get the ZobristNumber of the tile at a certain index.
uint64_t Board::getZobristBox(index_t tile) const {
if (mTiles[tile].isBox())
return mZobristBoxes[tile];
else
return 0;
}
uint64_t Board::getZobristPlayer(index_t tile) const {
if (tile == mPlayerIndex)
return mZobristPlayer[tile];
else
return 0;
}
// xor the number to the hash value
void Board::updateHash(uint64_t zobristNumber) {
mHashValue ^= zobristNumber;
}
// computes the hash value from scratch
uint64_t Board::computeHashValue() const {
uint64_t hash = 0;
for (index_t i = 0; i < mSize; ++i) {
hash ^= getZobristBox(i);
hash ^= getZobristPlayer(i);
}
return hash;
}
// computes an alternative hash value from scratch
uint64_t Board::computeHash2Value() {
return mHashValue;
// FIXME
// uint64_t hash = mPlayerIndex;
// foreach (index_t box_index, mBoxes ) {
// hash <<= mIndexBits;
// hash |= box_index;
// }
// return hash; // will always be != 0
}
void Board::setPlayerIndex(index_t player) {
mPlayerIndex = player;
}
void Board::restoreInitialPlayerIndex() {
setPlayerIndex(mInitialPlayerIndex);
}
bool Board::shortestPathSearch(string &actions, index_t start, index_t end) const
{
// This uses dijkstra to search for the end
// Since we have this very special layout we don't ever need to update a node.
stringstream ss;
vector<TileGraphNode> nodes(mSize);
nodes[start].distance = 0;
nodes[start].visited = true;
TileGraphNode::IndexComparator comparator(&nodes);
priority_queue<uint, vector<uint>, TileGraphNode::IndexComparator> pq(comparator);
pq.push(start);
while(!pq.empty()) {
index_t curr = pq.top();
pq.pop();
if (curr == end) {
// Found the goal, now back up and record the way
while (curr != start) {
ss << directionToAction(invertDirection(nodes[curr].parent));
curr = tileIndex(curr, nodes[curr].parent);
}
actions = ss.str();
reverse(actions.begin(), actions.end());
#ifdef VERBOSE_SHORTEST_PATH
cout << "Shortest path search result: " << endl;
cout << boardToString(0, &nodes) << endl;
#endif
return true;
}
// not found the goal yet, so search further
foreach (Dir dir, cDirs) {
index_t next = tileIndex(curr, dir);
if (!nodes[next].visited && mTiles[next].isFree()) {
nodes[next].distance = nodes[curr].distance + 1;
nodes[next].parent = invertDirection(dir);
nodes[next].visited = true;
pq.push(next);
}
}
}
return false;
}
bool Board::actionsForMove(string &actions, const Move &move) const
{
if ( shortestPathSearch(actions, getPlayerIndex(), move.getPlayerIndex(this)) ) {
actions += directionToAction(move.getMoveDir());
return true;
}
return false;
}
};
| true |
6450ea2c5e17bad533336dbaa150936b2894ee42 | C++ | cRYP70n-13/Algorithms | /Data_Structures/C++/BinaryTree/BinaryTree.cpp | UTF-8 | 584 | 3.71875 | 4 | [] | no_license | #include <iostream>
struct Node {
int val;
struct Node *left;
struct Node *right;
};
struct Node *newNode(int data)
{
struct Node *new_node = malloc(sizeof(struct Node));
new_node->val = data;
new_node->left = NULL;
new_node->right = NULL;
return (new_node);
}
int main(void)
{
struct Node *root = newNode(1);
root->left = newNode(3);
root->right = newNode(5);
root->left->right = newNode(8);
root->left->left = newNode(7);
root->right->left = newNode(19);
root->right->right = newNode(28);
return (0);
}
| true |
55114a76b1972e4b815e812da1589985f85b68ba | C++ | axxonite/algorithms | /EPI/Solutions/25_HonorRoll/25.13_binary_tree_postorder_traversal_iterative_solution.cpp | UTF-8 | 1,286 | 3.328125 | 3 | [] | no_license | // Copyright (c) 2015 Elements of Programming Interviews. All rights reserved.
#include "stdafx.h"
#include "binary_tree_prototype.h"
namespace Solutions
{
// A few key things to be able to write this in the most compact and elegant way:
// There's no need for a "current" pointer. Just push the current at the top of the stack, with the stack describing the path down the tree.
// There is a bit of repetition in the algorith, but it's only a couple of lines.
vector<int> PostorderTraversal(const unique_ptr<BinaryTreeNode<int>>& tree)
{
stack<BinaryTreeNode<int>*> s;
BinaryTreeNode<int>* last = nullptr;
s.push(tree.get());
vector<int> result;
while (!s.empty())
{
auto cur = s.top();
if (!last || last->left.get() == cur || last->right.get() == cur) // Coming from the parent.
{
// Traverse left if there is a left child, otherwise traverse right.
if (cur->left)
s.push(cur->left.get());
else if (cur->right)
s.push(cur->right.get());
else
{
result.emplace_back(cur->data);
s.pop();
}
}
else if (cur->left.get() == last && cur->right) // Coming from the left child.
s.push(cur->right.get());
else
{
result.emplace_back(cur->data);
s.pop();
}
last = cur;
}
return result;
}
}
| true |
473f948a808bae2ddf3857b25c6e1abe5a8d7883 | C++ | lyw1204/Racoon-Project | /scanner_optimizing/e_TrickArsenal.ino | UTF-8 | 1,149 | 2.625 | 3 | [] | no_license | class TrickArsenal{
private:
byte _pin1;
byte _pin2;
byte _pin3;
public:
TrickArsenal(byte dPIN1, byte dPIN2, byte dPIN3){
_pin1 = dPIN1;
_pin2 = dPIN2;
_pin3 = dPIN3;
pinMode(_pin1, OUTPUT);
pinMode(_pin2, OUTPUT);
pinMode(_pin3, OUTPUT);
}
void deploy(){
int noTrigger = random(0,2);
switch(noTrigger){//toggle outputs randomly for 1s
case 0:
digitalWrite(_pin2, HIGH);
digitalWrite(_pin3, HIGH);
delay(1000);
digitalWrite(_pin2,LOW);
digitalWrite(_pin3,LOW);
break;
case 1:
digitalWrite(_pin1, HIGH);
digitalWrite(_pin3, HIGH);
delay(1000);
digitalWrite(_pin1,LOW);
digitalWrite(_pin3,LOW);
break;
case 2:
digitalWrite(_pin1, HIGH);
digitalWrite(_pin2, HIGH);
delay(1000);
digitalWrite(_pin1,LOW);
digitalWrite(_pin2,LOW);
break;
default:
break;
}
}
};
TrickArsenal ta1(DET1_PIN, DET2_PIN, DET3_PIN);
| true |
29e1df2cedcb6aaef0ac6a813ee0b8c582d7dfde | C++ | DenysenkoIvan/toy-compiler | /source/Tokenizer.cpp | UTF-8 | 4,602 | 3.0625 | 3 | [] | no_license | #include "Tokenizer.h"
Tokenizer::Tokenizer(const std::filesystem::path& input_file)
: m_stream(input_file)
{
scan_next_token();
}
Token& Tokenizer::current() {
return m_token;
}
Token& Tokenizer::next() {
scan_next_token();
return m_token;
}
void Tokenizer::scan_next_token() {
Position pos = { m_stream.line(), m_stream.column() };
do {
if (is_eof())
m_token.set_type(TokenKind::EOS);
else if (is_white_space())
m_token = scan_white_space();
else if (is_name_start())
m_token = scan_name();
else if (is_number_start())
m_token = scan_number();
else
m_token = scan_operator_or_punctuation_mark();
} while (m_token.kind() == TokenKind::WHITE_SPACE ||
m_token.kind() == TokenKind::COMMENT ||
m_token.kind() == TokenKind::INVALID);
if (m_token.kind() == TokenKind::INVALID) {
Position new_pos = { m_stream.line(), m_stream.column() };
// TODO Error messages
//
// error(pos, new_pos, "Invlaid characters");
// For now it just skips all the invlaid characters
}
m_token.set_position(pos);
}
bool Tokenizer::is_eof() const {
return m_stream.current() == EOF;
}
bool Tokenizer::is_name_start() const {
return std::isalpha(m_stream.current());
}
bool Tokenizer::is_number_start() const {
return std::isdigit(m_stream.current());
}
bool Tokenizer::is_white_space() const {
return std::isspace(m_stream.current());
}
Token Tokenizer::scan_white_space() {
while (is_white_space())
m_stream.next();
return Token(TokenKind::WHITE_SPACE);
}
Token Tokenizer::scan_name() {
Token token(TokenKind::NAME);
std::string name;
while (std::isalnum(m_stream.current()) || m_stream.current() == '_') {
name += m_stream.current();
m_stream.next();
}
token.set_lexeme(std::move(name));
return token;
}
Token Tokenizer::scan_number() {
Token token;
std::string lexeme;
while (std::isdigit(m_stream.current())) {
lexeme += m_stream.current();
m_stream.next();
token.set_type(TokenKind::INT);
}
if (m_stream.current() == '.') {
if (!std::isdigit(m_stream.next())) {
token.set_type(TokenKind::INVALID);
return token;
}
while (std::isdigit(m_stream.current())) {
lexeme += m_stream.current();
m_stream.next();
}
token.set_type(TokenKind::FLOAT);
}
token.set_lexeme(std::move(lexeme));
return token;
}
Token Tokenizer::scan_operator_or_punctuation_mark() {
Token token;
switch (m_stream.current()) {
case '/':
if (m_stream.next() == '/') {
char c = m_stream.next();
while (c != '\n' && c != EOF) {
c = m_stream.next();
}
token.set_type(TokenKind::COMMENT);
m_stream.next();
} else
token.set_type(TokenKind::SLASH);
break;
case '=':
if (m_stream.next() == '=') {
m_stream.next();
token.set_type(TokenKind::EQUAL_EQUAL);
} else
token.set_type(TokenKind::EQUAL);
break;
case '!':
if (m_stream.next() == '=') {
m_stream.next();
token.set_type(TokenKind::NOT_EQUAL);
} else
token.set_type(TokenKind::LOGICAL_NOT);
break;
case '+':
if (m_stream.next() == '+') {
m_stream.next();
token.set_type(TokenKind::PLUS_PLUS);
} else
token.set_type(TokenKind::PLUS);
break;
case '-':
m_stream.next();
if (m_stream.current() == '-') {
m_stream.next();
token.set_type(TokenKind::MINUS_MINUS);
} else if (m_stream.current() == '>') {
m_stream.next();
token.set_type(TokenKind::ARROW);
} else
token.set_type(TokenKind::MINUS);
break;
case '*':
token.set_type(TokenKind::STAR);
m_stream.next();
break;
case '<':
if (m_stream.next() == '=') {
m_stream.next();
token.set_type(TokenKind::LESS_EQUAL);
} else
token.set_type(TokenKind::LESS);
break;
case '>':
if (m_stream.next() == '=') {
m_stream.next();
token.set_type(TokenKind::GREATER_EQUAL);
} else
token.set_type(TokenKind::GREATER);
break;
case '(':
m_stream.next();
token.set_type(TokenKind::LEFT_PAREN);
break;
case ')':
m_stream.next();
token.set_type(TokenKind::RIGHT_PAREN);
break;
case '&':
if (m_stream.next() == '&') {
m_stream.next();
token.set_type(TokenKind::LOGICAL_AND);
} else
token.set_type(TokenKind::INVALID);
case '|':
if (m_stream.next() == '|') {
m_stream.next();
token.set_type(TokenKind::LOGICAL_OR);
} else
token.set_type(TokenKind::INVALID);
case ';':
m_stream.next();
token.set_type(TokenKind::SEMICOLON);
break;
case '{':
m_stream.next();
token.set_type(TokenKind::LEFT_BRACE);
break;
case '}':
m_stream.next();
token.set_type(TokenKind::RIGHT_BRACE);
break;
default:
token.set_type(TokenKind::INVALID);
}
return token;
} | true |
afc6ed8f8e6c449f4c28572b5b0ba5f5d52714f1 | C++ | leandro1623/Punto-movible- | /puntoM.cpp | UTF-8 | 554 | 3.046875 | 3 | [] | no_license | #include<iostream>
#include<iomanip>
#include"puntoM.h"
using std::setw;
void puntoM::set_x(int x){
this->x=x;
}
void puntoM::set_y(int y){
this->y=y;
}
int puntoM::get_x(){
return this->x;
}
int puntoM::get_y(){
return this->y;
}
void puntoM::limpiar_mapa(){
for(int i=0;i<10;i++){
for(int j=0;j<10;j++){
this->map[i][j]='#';
}
}
}
void puntoM::punto_en_el_mapa(){
this->map[this->x][this->y]='.';
}
void puntoM::ver_mapa(){
for(int i=0;i<10;i++){
for(int j=0;j<10;j++){
std::cout<<this->map[i][j];
}
std::cout<<"\n";
}
} | true |
03eee56c6d79184e5be72c0764557addd550cbe6 | C++ | dtbinh/crapengine | /source/core/unittests/source/delegates.cpp | UTF-8 | 3,299 | 2.8125 | 3 | [
"MIT"
] | permissive | #include "delegates.h"
#include "UnitTest++.h"
#include "logger.h"
namespace
{
TEST( AnnounceTestDelegates )
{
CRAP_DEBUG_LOG( LOG_CHANNEL_CORE| LOG_TARGET_COUT| LOG_TYPE_DEBUG, "Starting tests for \"delegates.h\"" );
}
int dele_func( void )
{
return 1;
}
int dele_add( int val )
{
return 1+val;
}
long dele_add2( int val, long val1 )
{
return val1 + val;
}
float dele_mul( int base, long fun, float multi )
{
return ((float)(base*fun)) * multi;
}
float dele_mul2( int base, long fun, float multi, float plus )
{
return ((float)(base*fun)) * multi + plus;
}
float dele_div( int base, long fun, float multi, float plus, int add )
{
return ((float)(base*fun)) * multi + plus + add;
}
class dele_test
{
public:
int dele_func( void )
{
return 0;
}
int dele_add( int val )
{
return 2+val;
}
long dele_add2( int val, long val1 )
{
return val1 + val;
}
float dele_mul( int base, long fun, float multi )
{
return ((float)(base*fun)) * multi;
}
float dele_mul2( int base, long fun, float multi, float plus )
{
return ((float)(base*fun)) * multi + plus;
}
float dele_div( int base, long fun, float multi, float plus, int add )
{
return ((float)(base*fun)) * multi + plus + add;
}
};
TEST(TestDelegateZero)
{
dele_test setest;
crap::delegate< int (void) > dele;
dele.bind<dele_func>();
//printf("Se delegate says: %i\n", dele.invoke());
dele.bind<dele_test, &dele_test::dele_func>( &setest );
// printf("Se delegate says again: %i\n", dele.invoke());
}
TEST(TestDelegateOne)
{
dele_test setest;
crap::delegate<int(int)> dele2;
dele2.bind<dele_add>();
//printf("Se delegate adds: %i\n", dele2.invoke(25));
dele2.bind<dele_test, &dele_test::dele_add>( &setest );
//printf("Se delegate adds: %i\n", dele2.invoke(125));
}
TEST(TestDelegateTwo)
{
dele_test setest;
crap::delegate<long(int, long)> dele3;
dele3.bind<dele_add2>();
//printf("Se delegate adds: %i\n", dele3.invoke(25, 25));
dele3.bind<dele_test, &dele_test::dele_add2>( &setest );
// printf("Se delegate adds: %i\n", dele3.invoke(50, 25));
}
TEST(TestDelegateThree)
{
dele_test setest;
crap::delegate<float(int, long, float)> dele3;
dele3.bind<dele_mul>();
//printf("Se delegate adds: %f\n", dele3.invoke(25, 25, 1.3f));
dele3.bind<dele_test, &dele_test::dele_mul>( &setest );
//printf("Se delegate adds: %f\n", dele3.invoke(50, 25, 2.6f));
}
TEST(TestDelegateFour)
{
dele_test setest;
crap::delegate<float(int, long, float, float)> dele3;
dele3.bind<dele_mul2>();
//printf("Se delegate adds: %f\n", dele3.invoke(25, 25, 1.3f, 2.6f));
dele3.bind<dele_test, &dele_test::dele_mul2>( &setest );
//printf("Se delegate adds: %f\n", dele3.invoke(50, 25, 2.6f, 4.3f));
}
TEST(TestDelegateFive)
{
dele_test setest;
crap::delegate<float(int, long, float, float, int)> dele3;
dele3.bind<dele_div>();
//printf("Se delegate adds: %f\n", dele3.invoke(25, 25, 1.3f, 2.6f,8));
dele3.bind<dele_test, &dele_test::dele_div>( &setest );
//printf("Se delegate adds: %f\n", dele3.invoke(50, 25, 2.6f, 4.3f, 7));
}
}
| true |
d6f32c0f8db6d9851bf86f65a609d3769bf6674a | C++ | melancholymans/PocketCplusplus | /chapter5/264.cpp | UTF-8 | 191 | 2.765625 | 3 | [] | no_license | #include <iostream>
using namespace std;
/*
int main(void)
{
wchar_t s;
char sc;
cout << "wchar size= " << sizeof(s) << " char size= " << sizeof(sc) << endl;
getchar();
return 0;
}
*/
| true |
c549443412147b24667ff0a762efa0b1993d7a72 | C++ | DetrembleurArthur/engineTools | /unnamed-engine/windows-no-last-update/engine/include/CircleEntity.hpp | UTF-8 | 947 | 2.703125 | 3 | [
"MIT"
] | permissive | #ifndef CIRCLEENTITY_HPP
#define CIRCLEENTITY_HPP
#include "Entity.hpp"
#include "Image.hpp"
#include "Animated.hpp"
class CircleEntity : public Entity<sf::CircleShape>, public Animated
{
private:
protected:
public:
static const float DEFAULT_RADIUS;
CircleEntity();
CircleEntity(float x, float y, Origin origin=TOP_LEFT);
CircleEntity(const sf::Vector2f& pos, Origin origin=TOP_LEFT);
CircleEntity(float x, float y, float radius, Origin origin=TOP_LEFT);
CircleEntity(const sf::Vector2f& pos, float radius, Origin origin=TOP_LEFT);
CircleEntity(const CircleEntity& cp);
CircleEntity(sf::Texture *texture, float x=0, float y=0, Origin origin=TOP_LEFT);
CircleEntity(sf::Texture *texture, const sf::Vector2f& pos, Origin origin=TOP_LEFT);
virtual ~CircleEntity();
bool collision(const CircleEntity& other);
CircleEntity& operator=(const CircleEntity& cp);
friend ostream &operator<<(ostream& out, const CircleEntity& obj);
};
#endif
| true |
b32d50d36614a2203f4d4be0eff646ab6233eec2 | C++ | czczc/LArViewer | /MicroBooNE/event/MCGeometry.h | UTF-8 | 1,130 | 2.59375 | 3 | [] | no_license | #ifndef MCGEOMETRY_H
#define MCGEOMETRY_H
#include "MCChannel.h"
#include <map>
#include "TString.h"
#define NCHANNELS 8254
class MCGeometry {
private:
MCGeometry();
MCGeometry(MCGeometry const&) {};
void operator=(MCGeometry const&) {};
public:
MCChannel channels[NCHANNELS];
TString mapFileName;
std::map<int, int> wireToChannel; // hash map to find channel no. given wire hash
virtual ~MCGeometry();
// singleton method
static MCGeometry& GetInstance() { static MCGeometry geom; return geom; }
// methods
void ReadChanneleWireMap();
void PrintInfo();
double Projection(int plane, int wire);
// double ProjectionZ(int wire); // projection to Z coordinate for collection plane
// double ProjectionU(int wire); // projection to perpendicular coordinate of U plane
// double ProjectionV(int wire); // projection to perpendicular coordinate of V plane
// double ProjectionX(int tdc); // projection to X coordinate for drifting
enum VIEW {
kU = 0,
kV = 1,
kZ = 2, // collection
kX = 3, // drift
};
};
#endif | true |
e8b02be86cf6861a87140438bbfa148a0b71029b | C++ | ysluckly/Hello-Linux | /C++/Project2_ConcurrentMemoryPool/CentralCache.h | GB18030 | 1,161 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include "Common.h"
// 1.central cacheһϣӳspan
// 2.ÿӳСempty spanһУnonempty spanһ
// 3.Ϊ˱֤ȫֻΨһcentral cache౻Ƴ˵ģʽ
class CentralCache
{
public:
static CentralCache* GetInstance(){
return &_inst;
}
// ĻȡһĶthread cache
size_t FetchRangeObj(void*& start, void*& end, size_t n, size_t byte);
// һĶͷŵspan
void ReleaseListToSpans(void* start, size_t byte_size);
// page cacheȡһspan
Span* GetOneSpan(SpanList* spanlist, size_t bytes);
private:
// Ļ
SpanList _spanlist[NLISTS];
private:
//ֹ˴˽
CentralCache() = default;//ĬϹ죬ɶĬ
CentralCache(const CentralCache&) = delete;
CentralCache& operator=(const CentralCache&) = delete;
static CentralCache _inst; //.hļ᱾ļã.cppʼ⡣
}; | true |
008eb963f6632a9a0d4647a1cc1fedba5bb6217b | C++ | garcia-pedro-hr/ComponentGameSystem | /Actor.cpp | UTF-8 | 1,398 | 3.078125 | 3 | [] | no_license | #include "Actor.h"
#include <cassert>
Actor::Actor()
{
} // EOConstructor
Actor::Actor(std::string p_name, int p_ID ) :
m_name(p_name), m_actorID(p_ID)
{
} // EOConstructor
Actor::~Actor(void)
{
Destroy();
} // EODestructor
void Actor::Destroy(void)
{
// Nunca chame explicitamente o destrutor.
for (auto& componentIt : m_components)
{
Component* pComponent = componentIt.second;
if (pComponent != nullptr)
{
delete pComponent;
pComponent = nullptr;
}
}
} // EODestroy
void Actor::SetName(const std::string p_name)
{
this->m_name = p_name;
} // EOSetName
void Actor::SetID(const int p_ID)
{
this->m_actorID = p_ID;
} // EOSetID
const int Actor::GetActorID(void) const
{
return this->m_actorID;
} // EOGetActorID
const std::string Actor::GetName(void)
{
return this->m_name;
} // EOGetName
void Actor::AddComponent(Component* p_component)
{
assert(p_component != nullptr);
this->m_components.insert(std::pair<std::string, Component*>(p_component->GetName(), p_component));
} // EOAddComponent
Component* Actor::GetComponent(std::string p_componentName)
{
std::map<std::string, Component*>::const_iterator results = this->m_components.find(p_componentName);
if(results == this->m_components.end())
return NULL;
return results->second;
} // EOGetComponent | true |
d183dacd80772c0d8db5e560160dfd1cd168ebd7 | C++ | adaapp/primers-portfolio-e457 | /include/thursday.h | UTF-8 | 1,847 | 3.734375 | 4 | [] | no_license | #include <iostream>
#include<thread>
#include <chrono>
using namespace std;
void sleep(int seconds = 10) { //sleep for 10 seconds by default
int milliseconds = seconds * 1000; //calculate the number of milliseconds from the seconds provided
cout << "sleep - thread: " << this_thread::get_id() << " started\n";
this_thread::sleep_for(chrono::milliseconds(milliseconds)); //sleep for the milliseconds specified
}
void sleepTime(int seconds = 10) {
cout << "\nStarting sleep timer\n";
sleep(seconds);
cout << "sleep - thread: " << this_thread::get_id() << " end\n";
}
void sleepTimer(void) {
sleepTime();
}
#include <iostream>
#include<thread>
#include <chrono>
using namespace std;
const int timerOneDuration = 5;
const int timerTwoDuration = 10;
void firstTimer() {
cout << "Thread 1: " << this_thread::get_id() << " started"<<endl;
sleep(timerOneDuration);
cout << "Thread 1: " << this_thread::get_id() << " ended" <<endl;
}
void secondTimer() {
cout << "Thread 2: " << this_thread::get_id() << " started"<<endl;
sleep(timerTwoDuration);
cout << "Thread 2: " << this_thread::get_id() << " ended"<<endl;
}
int joinThreads(void) {
cout << "Main thread: " << this_thread::get_id() << " started"<<endl;
thread thread1(firstTimer);
thread thread2(secondTimer);
thread1.join();
thread2.join();
cout << "Main thread: " << this_thread::get_id() << " ended"<<endl;
return 0;
}
int detachThreads(void) {
cout << "\nDetach Threads"<<endl;
cout << "Main thread: " << this_thread::get_id() << " started"<<endl;
thread thread1(firstTimer);
thread1.detach();
thread thread2(secondTimer);
thread2.detach();
sleepTime(11);
cout << "Main thread: " << this_thread::get_id() << " ended"<<endl;
return 0;
}
void joinDetachThreads(void) {
joinThreads();
detachThreads();
} | true |
b4f474f270beb9873eeeee77af968afc32fecaf6 | C++ | sxudai/myWebSever | /asyncLogging.cpp | UTF-8 | 4,966 | 2.96875 | 3 | [] | no_license | #include <ctime>
#include <chrono>
#include <functional>
#include "logFile.h"
#include "asyncLogging.h"
asyncLogging::asyncLogging(const string& basename,
size_t rollSize,
int flushInterval)
: flushInterval_(flushInterval),
running_(true),
basename_(basename),
rollSize_(rollSize),
thread_(std::bind(&asyncLogging::threadFunc, this)), // 可以这么写,类函数都有一个隐藏参数:类指针。&asyncLogging::threadFunc是类成员函数指针
currentBuffer_(new Buffer()), //首先准备了两块缓冲区,当前缓冲区
nextBuffer_(new Buffer()), //预备缓冲区
buffers_()
{
currentBuffer_->bzero(); //将缓冲区清零
nextBuffer_->bzero();
buffers_.reserve(16); //缓冲区指针列表预留16个空间
}
void asyncLogging::append(const char* logline, int len)
{
//因为有多个线程要调用append,所以用mutex保护
std::unique_lock<std::mutex> ul(mutex_);
if (currentBuffer_->avail() > len)//判断一下当前缓冲区是否满了
{
//当缓冲区未满,将数据追加到末尾
currentBuffer_->append(logline, len);
}
else
{
//当缓冲区已满,将当前缓冲区添加到待写入文件的以填满的缓冲区
buffers_.push_back(std::move(currentBuffer_));
//将当前缓冲区设置为预备缓冲区
if (nextBuffer_)
{
currentBuffer_ = std::move(nextBuffer_);
}
else//相当于nextbuffer也没有了
{
//这种情况极少发生,前端写入速度太快了,一下把两块缓冲区都写完了,那么之后分配一个新的缓冲区
currentBuffer_.reset(new Buffer());
}
currentBuffer_->append(logline, len);
cond_.notify_all();//通知后端开始写入日志
}
}
void asyncLogging::threadFunc()
{
logFile output(basename_, rollSize_, false);
/*一开始就准备了两块缓冲区
* 一块用来替换current buffer
* 一块用来做备用buffer
*/
BufferPtr newBuffer1(new Buffer);
BufferPtr newBuffer2(new Buffer);
newBuffer1->bzero();
newBuffer2->bzero();
BufferVector buffersToWrite;
buffersToWrite.reserve(16);
while(running_)
{
{
std::unique_lock<std::mutex> ul(mutex_);
// 处理假唤醒问题
while(running_ && buffers_.empty()) cond_.wait_for(ul,std::chrono::seconds(flushInterval_));
// 将当前缓冲区压入buffers,来都来了,也许current buffer里也有东西,顺便把它一起写了
buffers_.push_back(std::move(currentBuffer_));
//将空闲的newbuffer1置为当前缓冲区_
currentBuffer_ = std::move(newBuffer1);
//buffers与bufferstowrite交换,这样后面的代码可以在临界区之外方位bufferstowrite
buffersToWrite.swap(buffers_);
//确保前端始终有一个预留的buffer可供调配, 减少前端临界区分配内存的概率,缩短前端
if (!nextBuffer_) nextBuffer_ = std::move(newBuffer2);
}
/*消息堆积
* 前端陷入死循环,拼命发送日志消息,超过后端的处理能力,这就是典型的生产速度
* 超过消费速度的问题,会造成数据在内存中堆积,严重时会引发性能问题,(可用内存不足)
* 或程序崩溃(分配内存失败)
*/
if (buffersToWrite.size() > 25)//需要后端写的日志块超过25个,可能是前端日志出现了死循环
{
char buf[256];
time_t tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
snprintf(buf, sizeof(buf), "Dropped log messages at %s, %zd larger buffers\n",
ctime(&tt),
buffersToWrite.size()-2);//表明是前端出现了死循环
fputs(buf, stderr);
output.append(buf, static_cast<int>(strlen(buf)));
buffersToWrite.erase(buffersToWrite.begin()+2, buffersToWrite.end()); //丢掉多余日志,以腾出内存,只保留2块
}
// 后端开写
for (const auto& buffer : buffersToWrite) output.append(buffer->data(), buffer->length());
// 只保留两个buffer, 用于可能的newbuffer1和newbuffer2
if (buffersToWrite.size() > 2) buffersToWrite.resize(2);
// 检查两块缓冲区
if (!newBuffer1)
{
newBuffer1 = std::move(buffersToWrite.back());
buffersToWrite.pop_back();
newBuffer1->reset();
}
if (!newBuffer2)
{
newBuffer2 = std::move(buffersToWrite.back());
buffersToWrite.pop_back();
newBuffer2->reset();
}
buffersToWrite.clear();
// 刷入磁盘
output.flush();
}
output.flush();
} | true |
e89342cd1786f58f6d0ca0c6255ddfdd0d0dd807 | C++ | wjakubowski/akademia | /cmake-gtest-master/src/rational.h | UTF-8 | 1,500 | 3.265625 | 3 | [] | no_license | #ifndef RATIONAL_H
#define RATIONAL_H
#include <exception>
#include <ostream>
//liczby wymierne
//sprowadzanie do ujednoliconej postaci:
//najmiejszy wspulny dzielnik
//nie zewoeosc mianownika
//jak mianownik <0 mnozymy gore i dol przez -1
int nwd(int i1, int i2);
int nww(int i1, int i2);
class Rational
{
int nominator;
int denominator;
public:
Rational(int nominator, int denominator):nominator{nominator}, denominator{denominator}{}
Rational(int n): Rational{n,1}{}
int getNominator(){return nominator;}
int getDenominator(){return denominator;}
//modyfikujace w ciele klasy
Rational& operator += (Rational a)
{
//modyfikacje
return *this;
}
//to jest gorsze bo nie pozwala na domyslna konwersje 1 arg
// nie mozna:
// new_rat=1+rat
//Rational operator + (const Rational& r ) const;
};
inline Rational operator + (Rational a, Rational b);
inline Rational operator - (Rational a, Rational b);
inline Rational operator - (Rational a);
inline bool operator == (Rational a, Rational b);
inline bool operator != (Rational a, Rational b);
inline bool operator < (Rational a, Rational b);
inline bool operator <= (Rational a, Rational b);
inline bool operator > (Rational a, Rational b);
inline bool operator >= (Rational a, Rational b);
inline std::ostream& operator << (std::ostream& os, Rational a)
{
os << "[" << a.getNominator() << "/" << a.getDenominator() << "]";
return os;
}
#endif // RATIONAL_H
| true |
f2a7d95308d7652e3438764f7ca4a7d64e7a1a03 | C++ | slayerwalt/LeetCode | /OJ/leet699/leet699.cpp | UTF-8 | 1,281 | 2.890625 | 3 | [] | no_license | /*
leet699
*/
#include <iostream>
#include <tuple>
#include <vector>
#include <queue>
#include <stack>
#include <string>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <functional>
#include <utility>
#include "../utils/LeetCpp.utils.hpp"
using namespace std;
class Solution {
public:
vector<int> fallingSquares(const vector<vector<int>>& positions) {
// O(N^2) 朴实无华
using Tuple = tuple<int, int, int>;
vector<Tuple> active;
vector<int> ans; int last = 0;
for (const auto& pos: positions) {
auto x = pos[0], h = pos[1], y = h;
for (const auto& [x1, x2, y0]: active ) {
if (x + h <= x1 or x >= x2) continue;
else y = max(y, h + y0);
}
active.push_back({x, x+h, y});
last = max(last, y);
ans.push_back(last);
}
return ans;
}
};
int main(int argc, char const *argv[])
{
Solution sol;
cout << sol.fallingSquares({{1,2},{2,3},{6,1}}) << endl;
cout << sol.fallingSquares({{100,100},{200,100}}) << endl;
return 0;
}
| true |
b3781b69ca97cd2dc582ddb6af563d262f3d1be3 | C++ | kevcywu/Cpp-Tutorial-Sample | /Concepts/Linkedlist/intlinkedlist4/intlist4.cpp | UTF-8 | 1,609 | 3.703125 | 4 | [] | no_license | #include "stdafx.h"
#include "IntList4.h"
#include <iostream>
IntList4::Node::Node(int n): data(n), next(nullptr) {
std::cout << "Creating node " << data << " (" << reinterpret_cast<uintptr_t>(this) << ")\n";
}
IntList4::Node::~Node() {
std::cout << "Destroying node " << data << " (" << reinterpret_cast<uintptr_t>(this) << ")\n";
}
IntList4::IntList4() : head(nullptr), tail(nullptr), len(0) {}
IntList4::~IntList4() {
clear();
}
// Copy constructor
IntList4::IntList4(const IntList4& other) {
for (auto cursor = other.head; cursor; cursor = cursor->next)
insert(cursor->data);
}
// Assignment operator
IntList4& IntList4::operator=(const IntList4& other) {
// Make a local temporyary copy of other
IntList4 temp{ other };
// Exchange the head and tail pointers and len from this list
// with those of the new, temporary list
std::swap(head, temp.head);
std::swap(tail, temp.tail);
std::swap(len, temp.len);
// The temporary list now points to this list's original contents,
// and this list now points to the copy of other's list
return *this;
}
void IntList4::insert(int n) {
IntList4::Node *new_node = new Node(n);
if (tail) {
tail->next = new_node;
tail = new_node;
}
else {
head = tail = new_node;
}
len++;
}
void IntList4::print() const {
for (auto cursor = head; cursor; cursor = cursor->next)
std::cout << cursor->data << ' ';
std::cout << '\n';
}
int IntList4::length() const {
return len;
}
void IntList4::clear() {
auto cursor = head;
while (cursor) {
auto temp = cursor;
cursor = cursor->next;
delete temp;
}
head = tail = nullptr;
len = 0;
}
| true |
e98a1d31ed07b5ed95bf9b7c0054a289f13ececb | C++ | Grishameister/TestTask | /include/Parser.h | UTF-8 | 922 | 2.75 | 3 | [] | no_license | #ifndef TESTTASK_PARSER_H
#define TESTTASK_PARSER_H
#include <string>
struct Table {
std::string name_;
std::string date_;
std::string hours_worked_;
std::string car_;
std::string StringTable() {
std::string res;
res.reserve(name_.length() + date_.length() + hours_worked_.length() + car_.length() + 5);
res += name_ + '\n' + date_ + '\n' + hours_worked_ + '\n' + car_ + "\n\n";
return res;
}
};
class Parser {
public:
Parser() = default;
~Parser() = default;
std::string Parse(const std::string& block);
std::string ParseField(const std::string& str, const std::string& find_str, const std::string& find_end,
size_t start, size_t& end, size_t end_block);
bool ParseBlock(const std::string& str, const std::string& find_str, const std::string& find_end,
size_t& start, size_t& end);
};
#endif //TESTTASK_PARSER_H
| true |
db898ef8a0a8bbec76b5c5a76f59644da3ea1cb9 | C++ | humeaua/CVATools | /CVATools/PutSpread.cpp | UTF-8 | 963 | 2.921875 | 3 | [] | no_license | //
// PutSpread.cpp
// CVATools
//
// Created by Alexandre HUMEAU on 28/09/13.
//
//
#include "PutSpread.h"
#include "Require.h"
namespace Finance
{
namespace Payoff
{
PutSpread::PutSpread(double dStrike, double dLeftSpread, double dRightSpread) : dStrike_(dStrike), dLeftSpread_(dLeftSpread), dRightSpread_(dRightSpread)
{
REQUIREEXCEPTION(dLeftSpread_ >= 0.0, "Left spread has to be positive");
REQUIREEXCEPTION(dRightSpread_ >= 0.0, "Right spread has to be positive");
}
double PutSpread::operator()(const double s1) const
{
// We buy one put of strike dStrike + dRightSpread and sell one put of strike dStrike - dLeftSpread
return std::max(dStrike_ + dRightSpread_ - s1, 0.0) - std::max(dStrike_ - dLeftSpread_ - s1, 0.0);
}
BasePayoff1D * PutSpread::clone() const
{
return new PutSpread(*this);
}
}
} | true |
665c2e956d091943f4896491ddef9b2c52ece545 | C++ | sejal2712/OOPM-CI-305-_Assignments | /p7_quadratic_eq.cpp | WINDOWS-1252 | 874 | 3.6875 | 4 | [] | no_license | //Write a Program for Solving Quadratic Equation
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
double a,b,c,x1,x2;
cout<<"enter coefficient a,b and c of Quadratic Equation of form (ax^2 + bx + c = 0) = ";
cin>>a>>b>>c;
cout<<"equation : "<<"("<<a<<" * x * x) + ("<<b;
cout<<" * x) + ("<<c<<") = 0"<<endl;
if (a==0 && b==0)
cout<<"not a valid equation";
else if (a==0 && b!=0)
{ x1=-(c/b);
cout<<endl;
cout<<"root = "<<x1;
cout<<endl;
}
else if ((b*b-4*a*c)>0)
{
x1=((-b+(sqrt((b*b)-4*a*c)))/2*a);
x2=((-b-(sqrt((b*b)-4*a*c)))/2*a);
cout<<"the two roots of your quadratic equation are = "<<x1<<" "<<x2;
}
else if ((b*b-4*a*c)<0)
{
cout<<"not a real root"<<endl;
}
return 0;
}
| true |
e1b098f7b6aed78d747a9c04e5c9405fd8181fc5 | C++ | stungeye/Advent-of-Code-2020-CPP | /BinaryBoarding/BinaryBoarding/PassengerRoster.cpp | UTF-8 | 984 | 3.109375 | 3 | [] | no_license | #include "PassengerRoster.h"
#include <algorithm>
#include <iterator>
PassengerRoster::PassengerRoster(const std::vector<std::string>& codes) {
std::transform(codes.cbegin(), codes.cend(), std::back_inserter(boarding_passes),
[](auto code) -> BoardingPass { return BoardingPass(code); });
std::sort(boarding_passes.begin(), boarding_passes.end(), std::less<>());
}
BoardingPass PassengerRoster::max_boarding_pass() const {
return *std::max_element(boarding_passes.cbegin(), boarding_passes.cend());
}
BoardingPass PassengerRoster::first_empty_seat() const {
// Error if nothing is found because we'll still try to dereference boarding_passes.end().
return *std::adjacent_find(boarding_passes.cbegin(), boarding_passes.cend(),
[](const BoardingPass& bp1, const BoardingPass& bp2) -> bool {
return bp1 + 1 != bp2;
}) + 1;
}
| true |
3c44937a0afefe03a94099292d890dabfbf8b91d | C++ | Aiyuan-h/programming-language | /c++/20140222/20140222/20140222.cpp | UTF-8 | 323 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include<cstring>
int main()
{
using namespace std;
char ch;
int space =0;
int total =0;
cin.get (ch);
while(ch!='.')
{
if(ch==' ')
++space;
++total;
cin.get(ch);
}
cout<<space<<"space,"<<total;
// cout<<""endl<<cout<<"\n";
cin.get();
cin.get();
return 0;
} | true |
1597e338020cd6aa88088066cd049fa04bf9e2a3 | C++ | hoklavat/beginner-algorithms | /MORE/Dynamic(NumberOfWays).cpp | UTF-8 | 678 | 4.0625 | 4 | [] | no_license | //Dynamic(NumberOfWays)
//Task: find number of ways to obtain given number by summing specified numbers. numbers can be used multiple times.
//Reference: dynamic programming.
#include <iostream>
using namespace std;
//numbers used to reach n are 3, 5 and 10.
int count(int n){
int T[n+1];
int i;
for(int j = 0; j < n+1; j++)
T[j] = 0;
T[0] = 1;
for(i = 3; i <= n; i++)
T[i] += T[i-3];
for(i = 5; i <= n; i++)
T[i] += T[i-5];
for(i = 10; i <= n; i++)
T[i] += T[i-10];
return T[n];
}
int main(void){
int n = 20;
cout << "Count for " << n << " is " << count(n) << endl;
n = 13;
cout <<"Count for "<< n<< " is " << count(n) << endl;
return 0;
} | true |
4ea0dfaafbc5c0a6f350e8c6750b1eff88ff6e4b | C++ | Doyarun/TestTask | /TaskThree/Time.cpp | UTF-8 | 2,280 | 3.390625 | 3 | [] | no_license | #include "Time.h"
using namespace std;
Time::Time() : _hour(0), _minute(0), _second(0) {}
Time::Time(int h, int m, int s) : _hour(h), _minute(m), _second(s) { optimize(); }
void Time:: optimize(){
_minute += _second / 60;
_second = _second % 60;
_minute += ((_second < 0) ? -1 : 0);
_second += ((_second < 0) ? 60 : 0);
_hour += _minute / 60;
_minute = _minute % 60;
_hour += ((_minute < 0) ? -1 : 0);
_minute += ((_minute < 0) ? 60 : 0);
}
int Time::hour() const {
return _hour;
}
int Time::minute() const {
return _minute;
}
int Time::second() const {
return _second;
}
void Time:: SetH(int h) {
_hour = h;
}
void Time::SetM(int m) {
_minute = m;
}
void Time::SetS(int s) {
_second = s;
}
ostream& operator<< (ostream & o, const Time & t)
{
o << ((t.hour() < 10) ? "0" : "") << t.hour() << ":"
<< ((t.minute() < 10) ? "0" : "") << t.minute() << ":"
<< ((t.second() < 10) ? "0" : "") << t.second();
return o;
}
Time::Time(Time & other)
{
_hour = other._hour;
_minute = other._minute;
_second = other._second;
}
const Time Time::operator+(const Time & other) const
{
Time result(other.hour() + _hour, other.minute() + _minute, other.second() + _second);
return result;
}
const Time Time::operator-(const Time & other) const
{
Time result(_hour - other.hour(), _minute - other.minute(), _second - other.second());
return result;
}
const Time Time::operator *(int n) const
{
Time result(_hour*n, _minute*n, _second*n);
result.optimize();
return result;
}
const signed int Time::compare(const Time & other) const
{
if (_hour < other.hour())
return -1;
else
if (_hour > other.hour())
return +1;
else
if (_minute < other.minute())
return -1;
else
if (_hour > other.hour())
return +1;
else
if (_second < other.second())
return -1;
else
if (_second > other.second())
return +1;
return 0;
}
const bool Time::operator<(const Time & other) const
{
return (compare(other) < 0);
}
const bool Time::operator>(const Time & other) const
{
return (compare(other) > 0);
}
const bool Time::operator==(const Time & other) const
{
return (compare(other) == 0);
}
Time::~Time()
{
}
| true |
eb6d5a01b0e0851988f519bf7f27c4d93a9167c9 | C++ | m-aleksei/cpp-programs | /1-montecarlo(openmp).cpp | UTF-8 | 690 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <ctime>
#include <math.h>
#include <omp.h>
using namespace std;
double a,b;
double I,S,x,y,f;
int K;
const int N = 100*1024*1024;
double func(double xx)
{
double ff = xx*xx + 3;
return ff;
}
void main()
{
cout<<"Input a = "; cin>>a;
clock_t time = clock();
b = func(a);
K = 0;
omp_set_num_threads(2);
srand(time);
#pragma omp parallel for default(none) shared(N) reduction(+: K)
for(int i=0; i<=N; i++)
{
x = a*abs(double(rand())/RAND_MAX);
y = b*abs(double(rand())/RAND_MAX);
f = func(x);
if (y<=f) K++;
}
S = a * b;
I = K*S/N;
cout<<"Integral = "<<I;
time = clock() - time;
cout<<" time = "<<time<<" msc\n";
int q;
cin>>q;
}
| true |
f1d54fcb533781577974c72d148b87bb35e5a7a7 | C++ | hellowincci/C-Simple-program-using-pointers | /main.cpp | UTF-8 | 6,537 | 3.3125 | 3 | [] | no_license | #include <iostream>
#include <list>
#include <string>
#include <cstdlib>
#include <locale>
using namespace std;
class Users
{
public:
Users();
string userName;
string accessR;
};
Users::Users()
{
userName[20]='\0';
}
class Files
{
public:
string fileName;
list<Users> users;
Files();
};
Files::Files()
{
fileName[20]='\0';
}
list<Files> files;
list<Files>::iterator f;
list<Users>::iterator u;
list<Users> users;
void addUser(string userName,string fileName,string accessR);
void show_menu();
void show_Files();
void RemoveUsersForFile(string fileName, string userName);
void RemoveFile(string fileName);
void RemoveUser(string userName);
//main program
int main()
{
string userName;
string fileName;
string accessR;
string option;
while(true)
{
system("cls");
show_menu();
cin>>option;
while(option!="1" && option!="2" && option!="3" && option!="4" && option!="5" && option!="6")
{
system("cls");
cout<<"\nWrong input selected!\n";
show_menu();
cin>>option;
}
if(option=="1")
{
system("cls");
cout<<"\nInput user name : ";
cin>>userName;
cout<<"\nInput file name : ";
cin>>fileName;
cout<<"\nInput access Right : ";
cin>>accessR;
addUser(userName,fileName,accessR);
cout<<endl<<endl;
system("pause");
}
if(option=="2")
{
system("cls");
show_Files();
cout<<endl;
system("pause");
}
if(option=="3")
{
system("cls");
cout<<"Specify file name: ";
cin>>fileName;
cout<<"Specify user name: ";
cin>>userName;
RemoveUsersForFile(fileName,userName);
cout<<endl<<endl;
system("pause");
}
if(option=="4")
{
system("cls");
cout<<"Enter file name: ";
cin>>fileName;
RemoveFile(fileName);
cout<<endl<<endl;
system("pause");
}
if(option =="5")
{
system("cls");
cout<<"Enter user name: ";
cin>>userName;
// RemoveUser(userName);
cout<<endl<<endl;
system("pause");
}
if(option=="6")
{
break;
}
}
return 0;
system("pause");
}
//end of main
void RemoveUser(string userName, string fileName)
{
list<Users>::iterator u;
bool found_user=false, found_file=false;
for(u=f->users.begin(); u!=f->users.end(); u++)
{
if(u->userName==userName)
{
users.erase(u);
// users.erase(files);
found_user=true;
break;
}
}
found_file=true;
// break;
if(found_file==false)
cout<<"\n No file with name : "<<fileName<<" exists.";
if(found_file==true && found_user==false)
cout<<"\n File with name : "<<fileName<<" contains no user with name : "<<userName;
if(found_file==true && found_user==true)
cout<<"\n User with name : "<<userName<<" deleted from file with name : "<<fileName;
}
void RemoveUsersForFile(string fileName, string userName)
{
list<Users>::iterator u;
bool found_user=false, found_file=false;
for(f=files.begin(); f!= files.end(); f++)
{
if(f->fileName == fileName)
{
for(u=f->users.begin(); u!=f->users.end(); u++)
{
if(u->userName==userName)
{
f->users.erase(u);
found_user=true;
break;
}
}
found_file=true;
break;
}
}
if(found_file==false)
cout<<"\n No file with name : "<<fileName<<" exists.";
if(found_file==true && found_user==false)
cout<<"\n File with name : "<<fileName<<" contains no user with name : "<<userName;
if(found_file==true && found_user==true)
cout<<"\n User with name : "<<userName<<" deleted from file with name : "<<fileName;
}
void RemoveFile(string fileName)
{
list<Files>::iterator f;
for(f=files.begin(); f!= files.end(); f++)
{
if(f->fileName == fileName)
{
files.erase(f);
}
}
}
void show_Files()
{
list<Users>::iterator u;
for(f=files.begin(); f!=files.end(); f++)
{
cout<<"File name : "<<f->fileName<<endl;
cout<<"==================="<<endl;
for(u = f->users.begin(); u!=f->users.end(); u++)
{
cout<<"User Name : "<<u->userName<<endl;
cout<<"Access Right : "<<u->accessR<<endl;
if(++u!=f->users.end())
cout<<"-------------------"<<endl;
--u;
}
cout<<endl;
}
}
void show_menu()
{
cout<<"\n1. Add new user";
cout<<"\n2. View all files and users";
cout<<"\n3. Remove user from existing file";
cout<<"\n4. Exit";
cout<<"\n\nChoose (1-4) -> ";
}
void addUser(string userName,string fileName,string accessR)
{
bool file_found=false;
bool user_found=false;
string confirm ="";
list<Users>::iterator u;
f = files.begin();
while(f!=files.end())
{
if(f->fileName==fileName)
{
file_found=true;
break;
}
f++;
}
if(file_found==false)
{
Files* newF = new Files;
newF->fileName = fileName;
Users* newU = new Users;
newU->userName = userName;
newU->accessR = accessR;
newF->users.push_back(*newU);
files.push_back(*newF);
delete newF;
delete newU;
cout<<"\nNew file created successfully. Specified user added.";
}
if(file_found==true)
{
u = f->users.begin();
while(u!=f->users.end())
{
if(u->userName==userName)
{
user_found = true;
break;
}
u++;
}
if(user_found==false)
{
cout<<"\nFile with name : "<<f->fileName<<" exists. No user with name : "
<<userName<<" found"<<endl<<endl;
cout<<"Add new user with name : "<<userName<<" ? (type 'y' or 'Y' to confirm) : ";
cin>>confirm;
if(confirm == "y" || confirm == "Y")
{
Users* newU = new Users;
newU->userName = userName;
newU->accessR = accessR;
f->users.push_back(*newU);
delete newU;
cout<<"\nNew user added inside the existing file.";
}
}
if(user_found==true)
{
cout<<"\nFile with name : "<<f->fileName<<" exists."<<endl;
cout<<"User with name : "<<u->userName<<" exists."<<endl;
cout<<"\n=====User information is as follows=====\n\n";
cout<<"Username : "<<u->userName<<endl;
cout<<"Access Right: "<<u->accessR<<endl;
cout<<"\n===New user information is as follows===\n\n";
cout<<"Username : "<<userName<<endl;
cout<<"Access Right: "<<accessR<<endl;
cout<<"\nUpdate this user? (type 'y' or 'Y' to confirm) : ";
cin>>confirm;
if(confirm == "y" || confirm == "Y")
{
Users* newU = new Users;
newU->userName = userName;
newU->accessR= accessR;
f->users.push_back(*newU);
delete newU;
cout<<"\nUser updated successfully.";
}
}
}
}
| true |
7800300a3ed7c68ab4c745898af31b0c23913ae7 | C++ | KietNguyen10112000/FileSharingSystem | /FileSharing/FileSystemProtection/FileFolder.h | UTF-8 | 18,087 | 2.78125 | 3 | [] | no_license | #pragma once
#include <string>
#include <vector>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
#ifdef _DEBUG
#define Throw(msg) throw msg L"\nThrow from File \"" __FILEW__ L"\", Line " _STRINGIZE(__LINE__) L"."
#else
#define Throw(msg) throw msg
#endif // DEBUG
#include "../Common/File.h"
enum FOLDER_FLAG
{
NO_SCAN = 1,
SCAN = 2, //scan all file and folder from real storage
LOAD_STRUCTURE = 4, //load from structure file
USE_RELATIVE_PATH = 8,
FOLDER_NAME = 16,
};
enum FILE_FLAG
{
FILE_NAME = 1,
FILE_PATH = 2,
};
template<typename T> class File;
template<typename T>
class Folder
{
private:
friend class File<T>;
public:
Folder<T>* m_parent = nullptr;
int m_index = -1; //index in parent sub folders
std::wstring m_name;
//std::wstring m_path;
std::vector<Folder<T>*> m_subFolders;
std::vector<File<T>*> m_files;
std::wstring* m_iteratorPath = nullptr;
public:
inline Folder() { m_iteratorPath = new std::wstring(); };
Folder(const wchar_t* path, long long flag = FOLDER_FLAG::SCAN | FOLDER_FLAG::FOLDER_NAME, long long reserve = 0);
~Folder();
public:
//2 funcs must have same procotype
//see PrettyPrint() for more detail
template<typename _Func1, typename _Func2, typename ... _Args>
void Traverse(_Func1 preFnc, _Func2 postFnc, _Args&& ... args);
public:
template<typename T>
friend std::wostream& operator<<(std::wostream& wcout, Folder<T>* folder);
inline void PrettyPrint();
//free all sub folders and files
inline void RecursiveFree();
//free this folder only
inline void Free();
private:
inline Folder<T>* Parse(std::wistream& win, void (*load)(std::wistream&, File<T>*) = nullptr);
public:
inline void SaveStructure(std::wostream& wout, void (*)(std::wostream&, File<T>*) = nullptr);
inline void LoadStructure(std::wistream& win, void (*)(std::wistream&, File<T>*) = nullptr);
inline void SaveStructure(const wchar_t* savePath);
inline void LoadStructure(const wchar_t* structureFilePath);
//make all folder hover so when you call to MoveTo() it will hook to an another path
inline void ToRelativePath();
inline void MoveTo(const std::wstring& path);
//like SaveStructure but not save to file
inline std::wstring ToStructureString(void (*save)(std::wostream&, File<T>*) = nullptr);
public:
inline Folder<T>* GetFolderByName(const std::wstring& name);
inline Folder<T>* GetFolder(const std::wstring& path);
inline File<T>* GetFileByName(const std::wstring& name);
inline File<T>* GetFile(const std::wstring& path);
public:
//throw if file exists
inline void AddNew(File<T>* file);
//replace if file exists
//return null if file not exists, return file if it exists
inline File<T>* Add(File<T>* file);
//add folder only, not add its file, throw if folder exists
inline void AddNew(Folder<T>* folder);
//call callback() if file exists.
template<typename _Func, typename ... _Args>
inline void Add(Folder<T>* folder, _Func func, _Args&& ... args);
//return the removed file, null if no file removed
inline File<T>* RemoveFile(const std::wstring& fileName);
inline Folder<T>* RemoveFolder(const std::wstring& folderName);
public:
inline std::wstring Path();
inline auto Name() { return m_name; };
inline auto& Files() { return m_files; };
inline auto& Folders() { return m_subFolders; };
inline bool Empty() { return m_subFolders.empty() && m_files.empty(); };
inline size_t FileCount() { return m_files.size(); };
inline size_t FolderCount() { return m_subFolders.size(); };
//index in parent sub folders
inline auto Index() { return m_index; };
inline auto Parent() { return m_parent; };
};
template<typename T>
class File
{
public:
Folder<T>* m_parent = nullptr;
std::wstring m_name;
T m_data; //point to data of file
public:
inline File() {};
File(const wchar_t* param, FILE_FLAG flag = FILE_NAME, Folder<T>* parent = nullptr);
~File();
public:
template<typename T>
friend std::wostream& operator<<(std::wostream& wcout, File<T>* file);
public:
inline auto& Name() { return m_name; };
inline auto& Data() { return m_data; };
inline auto& ParentFolder() { return m_parent; };
inline std::wstring Path() { return m_parent->Path() + L"\\" + m_name; };
};
template<typename T>
inline Folder<T>::Folder(const wchar_t* path, long long flag, long long reserve)
{
if ((flag & (FOLDER_FLAG::FOLDER_NAME)) != 0)
{
m_name = GetFileName(path);
}
if ((flag & (FOLDER_FLAG::SCAN)) != 0)
{
if (!fs::is_directory(path))
{
Throw(L"Path must be Folder.");
}
try
{
for (const auto& entry : fs::directory_iterator(path))
{
if (entry.is_directory())
{
Folder<T>* temp = new Folder<T>(entry.path().c_str(), flag, reserve + 1);
temp->m_index = m_subFolders.size();
temp->m_parent = this;
m_subFolders.push_back(temp);
}
else
{
File<T>* temp = new File<T>(entry.path().filename().c_str(), FILE_NAME, this);
m_files.push_back(temp);
}
}
}
catch (fs::filesystem_error& e)
{
std::cerr << e.what() << "\n";
}
}
if ((flag & (FOLDER_FLAG::LOAD_STRUCTURE)) != 0)
{
if (!fs::is_regular_file(path))
{
Throw(L"Path must be file.");
}
LoadStructure(path);
}
if (reserve == 0)
{
m_iteratorPath = new std::wstring(path);
if (m_iteratorPath->back() == L'\\') m_iteratorPath->pop_back();
//auto lpath = std::wstring(path);
//MoveTo(lpath.substr(0, lpath.find_last_of(L"\\/")));
}
}
template<typename T>
inline Folder<T>::~Folder()
{
if (m_iteratorPath) delete m_iteratorPath;
}
template<typename T>
template<typename _Func1, typename _Func2, typename ... _Args>
inline void Folder<T>::Traverse(_Func1 preFunc, _Func2 postFunc, _Args&& ...args)
{
//constexpr std::size_t n = sizeof...(_Args);
size_t size = 0;
if (m_iteratorPath)
{
size = m_iteratorPath->size();
//*m_iteratorPath += L'\\' + m_name;
}
if constexpr (!(std::is_same_v<std::decay_t<_Func1>, std::nullptr_t>)) preFunc(this, std::forward<_Args>(args) ...);
for (auto f : m_subFolders)
{
f->m_iteratorPath = m_iteratorPath;
if (m_iteratorPath)
{
*m_iteratorPath += L'\\' + f->m_name;
}
f->Traverse(preFunc, postFunc, std::forward<_Args>(args) ...);
f->m_iteratorPath = nullptr;
if (m_iteratorPath)
{
m_iteratorPath->resize(size);
}
}
if constexpr (!(std::is_same_v<std::decay_t<_Func2>, std::nullptr_t>)) postFunc(this, std::forward<_Args>(args) ...);
/*if (m_iteratorPath)
{
m_iteratorPath->resize(size);
}*/
}
template<typename T>
inline void Folder<T>::PrettyPrint()
{
std::vector<std::pair<Folder<T>*, int>> stack;
Traverse(
[&](Folder<T>* current)
{
if (stack.empty())
{
std::wcout << current->Name() << " /\n";
if (current->FileCount() == 0) stack.push_back({ current, 0 });
else stack.push_back({ current, 1 });
}
else
{
std::wcout << ' ';
for (size_t i = 0; i < stack.size() - 1; i++)
{
if (stack[i].second != 0) std::wcout << L"│ ";
else std::wcout << " ";
}
//bool last = false;
if (current->Parent() != nullptr
&& current->Parent()->FileCount() == 0
&& current->Index() == current->Parent()->FolderCount() - 1)
{
std::wcout << L"└── " << current->Name() << " /\n";
stack.back().second = 0;
//last = true;
}
else
std::wcout << L"├── " << current->Name() << " /\n";
if (current->FileCount() == 0)
{
if(current->FolderCount() == 1)
stack.push_back({ current, 0 });
else
{
stack.push_back({ current, 1 });
}
}
else stack.push_back({ current, 1 });
}
},
[&](Folder<T>* current)
{
if (current->FileCount() != 0)
{
long long j = 0;
for (j = 0; j < current->FileCount() - 1; j++)
{
std::wcout << ' ';
for (size_t i = 0; i < stack.size() - 1; i++)
{
if (stack[i].second != 0) std::wcout << L"│ ";
else std::wcout << " ";
}
std::wcout << L"├── " << current->Files()[j]->Name() << "\n";
//└──
}
std::wcout << ' ';
for (size_t i = 0; i < stack.size() - 1; i++)
{
if (stack[i].second != 0) std::wcout << L"│ ";
else std::wcout << " ";
}
std::wcout << L"└── " << current->Files()[j]->Name() << "\n";
}
if (!stack.empty()) stack.pop_back();
});
}
template<typename T>
inline void Folder<T>::RecursiveFree()
{
Traverse(nullptr,
[](Folder<T>* current)
{
for (auto& f : current->Folders())
{
delete f;
}
current->Folders().clear();
for (auto& f : current->Files())
{
delete f;
}
current->Files().clear();
});
}
template<typename T>
inline void Folder<T>::Free()
{
for (auto& f : m_subFolders)
{
delete f;
}
m_subFolders.clear();
for (auto& f : m_files)
{
delete f;
}
m_files.clear();
}
template<typename T>
inline void Folder<T>::SaveStructure(std::wostream& wout, void (*save)(std::wostream&, File<T>*))
{
auto lo = wout.imbue(std::locale("en_US.utf8"));
//write out the signature
wout << L"FILESYSTEM_STRUCTURE\n";
//wout << Name() << L'\n';
Traverse(
[&](Folder<T>* current)
{
wout << L"<Folder>\n";
wout << current->Name() << L'\n';
wout << current->FileCount() << L'\n';
for (auto& f : current->Files())
{
wout << f->Name() << L'\n';
if (save)
{
save(wout, f); wout << L'\n';
}
}
wout << L"</Folder>\n";
},
[&](Folder<T>* current)
{
wout << L"<Pop />\n";
});
}
template<typename T>
inline void Folder<T>::SaveStructure(const wchar_t* savePath)
{
std::wofstream fout(savePath, std::ios::binary | std::ios::out);
SaveStructure(fout);
fout.close();
}
template<typename T>
inline Folder<T>* Folder<T>::Parse(std::wistream& win, void (*load)(std::wistream&, File<T>*))
{
std::wstring path;
std::getline(win, path);
std::wstring line;
std::getline(win, line);
size_t fileCount = std::stoi(line);
Folder<T>* temp = new Folder<T>();
temp->m_name = path;
for (size_t i = 0; i < fileCount; i++)
{
std::getline(win, line);
File<T>* file = new File<T>();
file->m_name = line;
file->m_parent = temp;
if (load) load(win, file);
temp->m_files.push_back(file);
}
return temp;
}
template<typename T>
inline void Folder<T>::LoadStructure(std::wistream& win, void (*load)(std::wistream&, File<T>*))
{
if (m_subFolders.size() != 0) RecursiveFree();
std::vector<Folder<T>*> stack;
auto lo = win.imbue(std::locale("en_US.utf8"));
std::wstring line;
std::getline(win, line);
if (line != L"FILESYSTEM_STRUCTURE")
{
Throw("File must be a structure file.");
}
std::wstring oriName;
std::getline(win, oriName);
bool hasOriName = false;
if (oriName != L"<Folder>")
{
std::getline(win, line);
hasOriName = true;
}
Folder<T>* root = Parse(win, load);
m_name = root->m_name;
m_files.swap(root->m_files);
for (auto& f : m_files)
{
f->m_parent = this;
}
delete root;
stack.push_back(this);
while (!win.eof())
{
std::getline(win, line);
if (line == L"<Folder>")
{
Folder* parent = stack.back();
Folder<T>* folder = Parse(win, load);
folder->m_index = parent->m_subFolders.size();
folder->m_parent = parent;
parent->m_subFolders.push_back(folder);
stack.push_back(folder);
}
else if (line == L"<Pop />")
{
stack.pop_back();
}
}
if (hasOriName)
{
MoveTo(L"./" + oriName);
}
}
template<typename T>
inline void Folder<T>::LoadStructure(const wchar_t* structureFilePath)
{
std::wifstream fin(structureFilePath, std::ios::binary | std::ios::in);
LoadStructure(fin);
fin.close();
}
template<typename T>
inline void Folder<T>::ToRelativePath()
{
/*std::wstring root = Path().substr(0, m_path.find_last_of(L"\\/"));
Traverse(
[&](Folder<T>* current)
{
current->m_path = MakeRelativePath(root, current->Path());
},
nullptr
);*/
if (m_iteratorPath)
{
*m_iteratorPath = L"";
}
}
template<typename T>
inline void Folder<T>::MoveTo(const std::wstring& path)
{
/*Traverse(
[&](Folder<T>* current)
{
current->m_path = CombinePath(path, current->Path());
},
nullptr
);*/
if (!m_iteratorPath)
{
m_iteratorPath = new std::wstring();
}
*m_iteratorPath = path + L'\\' + m_name;
}
template<typename T>
inline std::wstring Folder<T>::ToStructureString(void (*save)(std::wostream&, File<T>*))
{
std::wostringstream fout;
SaveStructure(fout, save);
return fout.str();
}
template<typename T>
inline Folder<T>* Folder<T>::GetFolderByName(const std::wstring& name)
{
for (auto& f : m_subFolders)
{
if (f->Name() == name) return f;
}
return nullptr;
}
//path must be relative path
template<typename T>
inline Folder<T>* Folder<T>::GetFolder(const std::wstring& path)
{
if (path.empty()) return this;
fs::path relativePath(path);
if (relativePath.is_absolute()) return nullptr;
std::vector<std::wstring> way;
StringSplit(path, L"\\", way);
if (!way.empty() && (*way.begin()).find(L".") != std::wstring::npos) way.erase(way.begin());
if (!way.empty() && *way.begin() == m_name) way.erase(way.begin());
Folder<T>* cur = this;
for (auto& name : way)
{
cur = cur->GetFolderByName(name);
if (!cur)
{
return nullptr;
}
}
return cur;
}
template<typename T>
inline File<T>* Folder<T>::GetFileByName(const std::wstring& name)
{
for (auto& f : m_files)
{
if (f->Name() == name) return f;
}
return nullptr;
}
template<typename T>
inline File<T>* Folder<T>::GetFile(const std::wstring& path)
{
if (path.empty()) return nullptr;
fs::path relativePath(path);
if (relativePath.is_absolute()) return nullptr;
std::vector<std::wstring> way;
StringSplit(path, L"\\", way);
std::wstring fileName;
if (way.empty()) return nullptr;
else
{
fileName = way.back();
way.pop_back();
}
if (!way.empty() && (*way.begin()).find(L".") != std::wstring::npos) way.erase(way.begin());
if (!way.empty() && *way.begin() == m_name) way.erase(way.begin());
Folder<T>* cur = this;
for (auto& name : way)
{
cur = cur->GetFolderByName(name);
if (!cur)
{
return nullptr;
}
}
return cur->GetFileByName(fileName);
}
template<typename T>
inline void Folder<T>::AddNew(File<T>* file)
{
for (auto& f : m_files)
{
if (f->Name() == file->Name())
{
Throw(L"File exists.");
}
}
m_files.push_back(file);
file->m_parent = this;
}
template<typename T>
inline File<T>* Folder<T>::Add(File<T>* file)
{
for (auto& f : m_files)
{
if (f->Name() == file->Name())
{
return f;
}
}
m_files.push_back(file);
file->m_parent = this;
return nullptr;
}
template<typename T>
inline void Folder<T>::AddNew(Folder<T>* folder)
{
folder->m_index = m_subFolders.size();
folder->m_parent = this;
m_subFolders.push_back(folder);
}
template<typename T>
template<typename _Func, typename ..._Args>
inline void Folder<T>::Add(Folder<T>* folder, _Func func, _Args&& ...args)
{
Folder<T>* newFolder = folder;
Folder<T>* exists = nullptr;
newFolder->ToRelativePath();
for (auto& f : m_subFolders)
{
if (f->Name() == folder->Name())
{
exists = f;
break;
}
}
if (exists)
{
newFolder->Traverse(
[&](Folder<T>* current)
{
for (auto& f : current->Files())
{
File<T>* file = exists->GetFile(f->Path());
if (file)
{
if constexpr (!(std::is_same_v<std::decay_t<_Func>, std::nullptr_t>))
{
callback(file, current, std::forward<_Args>(args) ...);
}
}
}
},
nullptr);
}
else
{
m_subFolders.push_back(newFolder);
newFolder->m_parent = this;
}
}
template<typename T>
inline File<T>* Folder<T>::RemoveFile(const std::wstring& fileName)
{
File<T>* re = nullptr;
typename std::vector<File<T>*>::iterator it;
for (it = m_files.begin(); it != m_files.end(); it++)
{
if ((*it)->Name() == fileName)
{
re = (*it);
break;
}
}
if (re != nullptr)
{
m_files.erase(it);
}
return re;
}
template<typename T>
inline Folder<T>* Folder<T>::RemoveFolder(const std::wstring& folderName)
{
Folder<T>* re = nullptr;
typename std::vector<Folder<T>*>::iterator it;
for (it = m_subFolders.begin(); it != m_subFolders.end(); it++)
{
if ((*it)->Name() == folderName)
{
re = (*it);
break;
}
}
if (re != nullptr)
{
m_subFolders.erase(it);
}
return re;
}
template<typename T>
inline std::wstring Folder<T>::Path()
{
if (m_iteratorPath) return *m_iteratorPath;
if (m_parent != nullptr) return m_parent->Path() + L'\\' + m_name;
else
{
return m_name;
}
}
template<typename T>
inline File<T>::File(const wchar_t* param, FILE_FLAG flag, Folder<T>* parent)
{
m_parent = parent;
if ((flag & (FILE_FLAG::FILE_NAME)) != 0)
{
m_name = param;
}
if ((flag & (FILE_FLAG::FILE_PATH)) != 0)
{
/*if (parent == nullptr)
{
Throw(L"Parent folder can't be nullptr.");
}*/
if (m_parent != nullptr) m_parent->AddNew(this);
m_name = param;
auto index = m_name.find_last_of(L"\\/");
m_name = m_name.substr(index + 1);
}
}
template<typename T>
inline File<T>::~File()
{
}
template<typename T>
inline std::wostream& operator<<(std::wostream& wcout, Folder<T>* folder)
{
folder->PrettyPrint();
return wcout;
}
template<typename T>
inline std::wostream& operator<<(std::wostream& wcout, File<T>* file)
{
return wcout << file->Path();
}
| true |
dc31bf3dc3b8d24b0e218d05baa97a4a8da58b7f | C++ | zhangxu128/Linux | /quick.cpp | UTF-8 | 1,037 | 4 | 4 | [] | no_license | #include <iostream>
using namespace std;
void print(int array[],int size){
for(int i = 0 ; i < size; i++){
cout<<array[i]<<" ";
}
cout<<endl;
}
void QuickSort(int array[],int left,int right){
int i = left;
int j = right;
int privot = array[left]; //保存基准值
if(i < j){
while(i < j){
//从后往前找小于基准值的数
while(i<j && array[j]>privot){
j--;
}
//填坑
if(i<j){
array[i] = array[j];
i++;
}
//从前往后找大于基准值的数
while(i<j && array[i] < privot){
i++;
}
//填坑
if(i<j){
array[i] = array[j];
j--;
}
}
//循环结束,交换基准值
array[i] = privot;
//递归左半边
QuickSort(array,left,i-1);
//递归右半边
QuickSort(array,i+1,right);
}
}
int main(void){
int array[] = {9,5,2,7,3,8,6,4,1};
int size = sizeof(array) / sizeof(int);
cout<<"排序前序列:"<<endl;
print(array,size);
cout<<"排序后序列:"<<endl;
QuickSort(array,0,size - 1);
print(array,size);
return 0;
}
| true |
a23011f56aadd66cbd4dbc36811da53c28056be7 | C++ | skyformat99/ppshuai_socketlibrary | /src/SocketLibrary/SocketLibrary/util/Random.h | UTF-8 | 1,898 | 3.125 | 3 | [] | no_license | /*
* File: random.h
* Version: 1.0
* Last modified on Fri Jul 22 16:44:36 1994 by eroberts
* -----------------------------------------------------
* This interface provides several functions for generating
* pseudo-random numbers.
*/
#ifndef RANDOM_H
#define RANDOM_H
#pragma once
#include "../config.h"
#ifndef RAND_MAX
#define RAND_MAX ((int) ((unsigned) ~0 >> 1))
#endif
namespace UTIL
{
class SOCKETLIBRARY_API CRandom
{
public:
/*
* Function: Randomize
* Usage: Randomize();
* -------------------
* This function sets the random seed so that the random sequence
* is unpredictable. During the debugging phase, it is best not
* to call this function, so that program behavior is repeatable.
*/
static void Randomize(int nSend = 0);
/*
* Function: RandomInteger
* Usage: n = RandomInteger(low, high);
* ------------------------------------
* This function returns a random integer in the range low to high,
* inclusive.
*/
static int RandomInteger(); //random number range [0,RAND_MAX]
static int RandomInteger(int nLow, int nHigh);
/*
* Function: RandomReal
* Usage: d = RandomReal(low, high);
* ---------------------------------
* This function returns a random real number in the half-open
* interval [low .. high), meaning that the result is always
* greater than or equal to low but strictly less than high.
*/
static double RandomReal(); //random number range [0,1]
static double RandomReal(double dLow, double dHigh);
/*
* Function: RandomChance
* Usage: if (RandomChance(p)) . . .
* ---------------------------------
* The RandomChance function returns TRUE with the probability
* indicated by p, which should be a floating-point number between
* 0 (meaning never) and 1 (meaning always). For example, calling
* RandomChance(.30) returns TRUE 30 percent of the time.
*/
static bool RandomChance(double p);
};
};
#endif
| true |
e200516c9ca984a40b1d0fdbb7d91e6b842c1cc2 | C++ | TauGames/Rendu | /src/engine/renderers/Probe.hpp | UTF-8 | 4,634 | 2.84375 | 3 | [
"MIT"
] | permissive | #pragma once
#include "resources/Buffer.hpp"
#include "resources/ResourcesManager.hpp"
#include "graphics/Framebuffer.hpp"
#include "renderers/Renderer.hpp"
#include "input/Camera.hpp"
#include "Common.hpp"
/**
\brief A probe can be used to capture the appareance of a scene at a given location as a 360° cubemap.
\details This is often used to render realistic real-time reflections and global illumination effects. It is
recommended to split the rendering, radiance precomputation for GGX shading and irradiance SH decomposition
over multiple frames as those steps are costly. Additional synchronization constraints are described
for each function below.
\ingroup Renderers
*/
class Probe {
public:
/** Constructor
\param position the probe position in the scene
\param renderer the renderer to use to fill the cubemap
\param size the dimensions of the cubemap
\param mips the number of mip levels of the cubemap
\param clippingPlanes the near/far planes to use when rendering each face
\warning If the renderer is using the output of the probe, be careful to not use the probe content in the last rendering step.
*/
Probe(const glm::vec3 & position, std::shared_ptr<Renderer> renderer, uint size, uint mips, const glm::vec2 & clippingPlanes);
/** Update the content of the cubemap. */
void draw();
/** Perform BRDF pre-integration of the probe radiance for increasing roughness and store them in the mip levels.
This also copies a downscaled version of the radiance for future SH computations.
\param clamp maximum intensity value, useful to avoid ringing artifacts
\param first first layer to process (in 1, mip count - 1)
\param count the number of layers to process
*/
void convolveRadiance(float clamp, uint first, uint count);
/** Estimate the SH representation of the cubemap irradiance. The estimation is done on the CPU,
and relies on downlaoding a (downscaled) copy of the cubemap content. For synchronization reasons,
it is recommended to only update irradiance every other frame, and to trigger the copy
(performed by prepareIrradiance) after the coeffs update. This will introduce a latency but
will avoid any stalls.
\param clamp maximum intensity value, useful to avoid temporal instabilities
*/
void estimateIrradiance(float clamp);
/** The cubemap containing the rendering. Its mip levels will store the preconvolved radiance
if convolveRadiance has been called
\return the cubemap texture
*/
Texture * texture() const {
return _framebuffer->texture();
}
/** The cubemap irradiance SH representation, if estimateIrradiance has been called.
\return the irradiance SH coefficients
*/
const std::shared_ptr<UniformBuffer<glm::vec4>> & shCoeffs() const {
return _shCoeffs;
}
/** \return the probe position */
const glm::vec3 & position() const {
return _position;
}
/** Copy assignment operator (disabled).
\return a reference to the object assigned to
*/
Probe & operator=(const Probe &) = delete;
/** Copy constructor (disabled). */
Probe(const Probe &) = delete;
/** Move assignment operator (disabled).
\return a reference to the object assigned to
*/
Probe & operator=(Probe &&) = delete;
/** Move constructor (disabled). */
Probe(Probe &&) = delete;
~Probe();
/**
\brief Decompose an existing cubemap irradiance onto the nine first elements of the spherical harmonic basis.
\details Perform approximated convolution as described in Ramamoorthi, Ravi, and Pat Hanrahan.
"An efficient representation for irradiance environment maps.",
Proceedings of the 28th annual conference on Computer graphics and interactive techniques. ACM, 2001.
\param cubemap the cubemap to extract SH coefficients from
\param clamp maximum intensity value, useful to avoid temporal instabilities
\param shCoeffs will contain the irradiance SH representation
*/
static void extractIrradianceSHCoeffs(const Texture & cubemap, float clamp, std::vector<glm::vec3> & shCoeffs);
private:
std::unique_ptr<Framebuffer> _framebuffer; ///< The cubemap content.
std::shared_ptr<Renderer> _renderer; ///< The renderer to use.
std::unique_ptr<Framebuffer> _copy; ///< Downscaled copy of the cubemap content.
std::shared_ptr<UniformBuffer<glm::vec4>> _shCoeffs; ///< SH representation of the cubemap irradiance.
std::array<Camera, 6> _cameras; ///< Camera for each face.
glm::vec3 _position; ///< The probe location.
Program * _integration; ///< Radiance preconvolution shader.
GPUAsyncTask _downloadTask = 0; ///< Current probe download task (for SH computations on the CPU).
const Mesh * _cube; ///< Skybox cube.
};
| true |
bbb3c6ed543765edd1ba2cad9ab2ad5e2aff1985 | C++ | cygwins/Leetcode | /73.Set Matrix Zeroes/n.cpp | UTF-8 | 994 | 3.109375 | 3 | [] | no_license | /*
* O( m + n )
* record all rows and colums need to be bombed
*/
#include <vector>
#include "catch.hpp"
using std::vector;
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int R = matrix.size(), C = matrix[0].size();
vector< bool > row( R, false ), col( C, false );
for( int i = 0; i < R; ++i )
for( int j = 0; j < C; ++j )
if( !matrix[i][j] )
row[i] = col[j] = true;
for( int i = 0; i < R; ++i )
if( row[i] )
for( int j = 0; j < C; ++j )
matrix[i][j] = 0;
for( int j = 0; j < C; ++j )
if( col[j] )
for( int i = 0; i < R; ++i )
matrix[i][j] = 0;
}
};
TEST_CASE("recording", "[setZeroes]") {
Solution s;
vector< vector< int >> m1 = {{1,1,1},{1,0,1},{1,1,1}},
r1 = {{1,0,1},{0,0,0},{1,0,1}};
s.setZeroes( m1 );
CHECK( m1 == r1 );
}
| true |
18c2074876253d822c532796738dec3872b43bac | C++ | katsuunhi/PTA | /PAT_(Advanced_Level)_Practice/25/1020. Tree Traversals/main.cpp | UTF-8 | 1,078 | 2.953125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
struct node{
int index, value;
};
vector<int> in, post;
vector<node> level;
bool cmp(node a, node b){
return a.index < b.index;
}
/*7
2 3 1 5 7 6 4
1 2 3 4 5 6 7*/
void pre(int postl, int postr, int inl, int inr, int index){
int i = inl;
if(inr < inl) return;
if(postl == postr){
level.push_back({index, post[postl]});
return;
}
while(i <= inr && in[i] != post[postr]) i++;
level.push_back({index, post[postr]});
pre(postl, postl + i - inl - 1, inl, i - 1, 2*index + 1);
pre(postl + i - inl, postr - 1, i + 1, inr, 2*index + 2);
}
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
int n, postl, postr, inl, inr;
cin >> n;
in.resize(n);
post.resize(n);
for(int i = 0; i < n; i ++)
cin >> post[i];
for(int i = 0; i < n; i ++)
cin >> in[i];
pre(0, n-1, 0, n-1, 0);
sort(level.begin(), level.end(), cmp);
cout << level[0].value;
for(int i = 1; i < n; i ++)
cout << " " << level[i].value;
cout << endl;
return 0;
}
| true |
e522209cac4117aab870c98ce9521f8eed79eeec | C++ | l34k1m/disciplinaAED1 | /Produzido/Lista recursividade/Exercício 1/Somatoria/main.cpp | UTF-8 | 210 | 3.125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int somatoria (int n) {
if (n==0) return 0;
else return (n+somatoria(n-1));
}
int main()
{
cout << somatoria(3) << endl;
return 0;
}
| true |
15ecffac6175638c9236c21d982047859e35f061 | C++ | HoangNhat629/Game | /Homework/MiniGameStarter/TrainingFramework/src/Game/StateMachine/GravitySelectState.cpp | UTF-8 | 3,345 | 3 | 3 | [] | no_license | #include "GravitySelectState.h"
#include "StateMachine.h"
#include "../GameWorld.h"
#include <array>
namespace Agvt
{
constexpr float Lerp(float a, float b, float t);
GravitySelectState::GravitySelectState(StateMachine* managingStateMachine) : StateBase(managingStateMachine),
m_sourceAngle{}, m_targetAngle{}, m_animationTimer{}, m_inAnimation(false)
{
}
void GravitySelectState::Update(float deltaTime)
{
if (m_inAnimation)
{
UpdateAnimation(deltaTime);
}
else
{
HandlePlayerInput();
}
}
void GravitySelectState::OnEnter()
{
GameWorld* gameWorld = m_managingStateMachine->GetGameWorld();
gameWorld->m_player->SetAnimationState(PlayerEntity::AnimationState::GravityStop);
}
void GravitySelectState::OnExit()
{
}
void GravitySelectState::HandlePlayerInput()
{
const InputManager* inputManager = m_managingStateMachine->GetInputManager();
GameWorld* gameWorld = m_managingStateMachine->GetGameWorld();
if (inputManager->KeyDown(KeyCode::LEFT))
{
BeginRotationAnimation((size_t)(gameWorld->m_currentGravityDirection), (size_t)GameWorld::GravityDirection::Left);
gameWorld->SetGravity(GameWorld::GravityDirection::Left);
}
else if (inputManager->KeyDown(KeyCode::RIGHT))
{
BeginRotationAnimation((size_t)(gameWorld->m_currentGravityDirection), (size_t)GameWorld::GravityDirection::Right);
gameWorld->SetGravity(GameWorld::GravityDirection::Right);
}
else if (inputManager->KeyDown(KeyCode::SPACE))
{
m_managingStateMachine->ChangeState(StateType::Updating);
}
}
void GravitySelectState::UpdateAnimation(float deltaTime)
{
GameWorld* gameWorld = m_managingStateMachine->GetGameWorld();
constexpr float c_animationTime = 0.1f;
m_animationTimer += deltaTime;
if (m_animationTimer >= c_animationTime)
{
gameWorld->SetWorldRotation(m_targetAngle >= 0.0f ? m_targetAngle : m_targetAngle + 2.0f * PI);
m_inAnimation = false;
m_animationTimer = 0;
}
else
{
gameWorld->SetWorldRotation(Lerp(m_sourceAngle, m_targetAngle, m_animationTimer / c_animationTime));
}
}
void GravitySelectState::BeginRotationAnimation(size_t currentGravityIndex, size_t shiftGravityIndex)
{
constexpr std::array<float, 4> directionToZAngle
{
0.0f, // Down
PI * 0.5f, // Right
PI * 1.0f, // Up
PI * 1.5f // Left
};
constexpr std::array<float, 4> directionToZAngleOffset
{
0.0f, // Down
PI * 0.5f, // Right
PI * 1.0f, // Up
PI * (-0.5f) // Left
};
float currentZAngle = directionToZAngle[currentGravityIndex];
float offsetZAngle = directionToZAngleOffset[shiftGravityIndex];
m_sourceAngle = currentZAngle;
m_targetAngle = currentZAngle + offsetZAngle;
m_inAnimation = true;
}
constexpr float Lerp(float a, float b, float t)
{
return a * (1 - t) + b * t;
}
} | true |
c12cc3935d0a605c755bf7cb2226d063643d47cb | C++ | obellado/cxx.08 | /ex02/mutantstack.hpp | UTF-8 | 684 | 2.984375 | 3 | [] | no_license | #pragma once
#ifndef __MutantStack__HPP__
# define __MutantStack__HPP__
# include <iostream>
# include <list>
# include <vector>
# include <deque>
# include <stack>
# include <exception>
# include <algorithm>
template <typename T>
class MutantStack : public std::stack<T> {
public:
MutantStack() : std::stack<T>() {}
virtual ~MutantStack() {}
MutantStack(const MutantStack & copy) {
*this = copy;
}
MutantStack & operator=(const MutantStack & copy) {
std::stack<T>::operator=(copy);
return (*this);
}
typedef typename std::deque<T>::iterator iterator;
iterator begin() { return (this->c.begin()); }
iterator end() { return (this->c.end()); }
};
#endif | true |
878b828dbdc87161f6dbd9e32da00665fb662e6d | C++ | soma62jp/PRML | /1-1/Matrix.h | UTF-8 | 7,972 | 3.234375 | 3 | [
"MIT"
] | permissive | //--------------------------------------------------//
// File Name: Matrix.h //
// Function: Matrix calculation //
// Copyright(C) 2016 shoarai //
// The MIT License (MIT) //
//--------------------------------------------------//
// https://github.com/shoarai/arith.git
#ifndef _MATRIX_H_
#define _MATRIX_H_
//------------------------------------------//
// インクルード //
//------------------------------------------//
using namespace std;
namespace arith {
//------------------------------------------//
// ク ラ ス //
//------------------------------------------//
class Matrix{
public:
unsigned int m_row; // 行
unsigned int m_col; // 列
double** val; // 行列要素用ポインタ
// vector< vector<double> > val;
public:
explicit Matrix
(unsigned int, unsigned int); // コンストラクタ
Matrix(const Matrix&); // コピーコンストラクタ
virtual ~Matrix(); // デストラクタ
// 行列要素を取り出す
double& operator()(unsigned int row, unsigned int col);
// 行列の代入
Matrix& operator= (const Matrix&);
// 行列との加減算
Matrix operator+ (const Matrix&) const;
Matrix& operator+=(const Matrix&);
Matrix operator- (const Matrix&) const;
Matrix& operator-=(const Matrix&);
// 行列との積
Matrix operator* (const Matrix&) const;
// 数値との乗除算
Matrix operator* (const double&) const;
Matrix& operator*=(const double&);
Matrix operator/ (const double&) const;
Matrix& operator/=(const double&);
// 転置行列
Matrix transpose() const;
};
// 行列要素を初期化する
Matrix::Matrix(unsigned int row, unsigned int col) : m_row(row), m_col(col)
{
// 行の要素数を設定する
/* val.resize(m_row);
for(unsigned int i = 0; i < m_row; i++)
{
// 列の要素数を設定する
val[i].resize(m_col);
}
*/
// 行要素を生成する
val = new double*[m_row];
for (unsigned int i = 0; i < m_row; i++)
{
// 列要素を生成する
val[i] = new double[m_col];
}
// 行列要素を初期化する
for(unsigned int i = 0; i < m_row; i++)
{
for(unsigned int j = 0; j < m_col; j++)
{
val[i][j] = 0;
}
}
}
// 行列要素をオブジェクトで初期化する
Matrix::Matrix(const Matrix& mat) :
m_row(mat.m_row), m_col(mat.m_col)
{
// 行の要素数を設定する
/* val.resize(m_row);
for(unsigned int i = 0; i < m_row; i++)
{
// 列の要素数を設定する
val[i].resize(m_col);
}
*/
// 列要素生成
val = new double*[m_row];
for (unsigned int i = 0; i < m_row; i++)
{
// 行要素生成
val[i] = new double[m_col];
}
// 値代入
for(unsigned int i = 0; i < m_row; i++)
{
for(unsigned int j = 0; j < m_col; j++)
{
val[i][j] = mat.val[i][j];
}
}
}
// 行列要素を破棄する
Matrix::~Matrix()
{
// 行列要素破棄
for (unsigned int i = 0; i < m_row; i++){
delete[] val[i];
}
delete[] val;
}
// 行列要素を取得する
double& Matrix::operator()(unsigned int row, unsigned int col)
{
return val[row][col];
}
// 代入演算子
Matrix& Matrix::operator=(const Matrix& mat)
{
// 行列同士の行数と列数が等しくないとき
if(m_row != mat.m_row || m_col != mat.m_col)
{
string err = "Matrix can't be substituted";
throw err;
}
for(unsigned int i = 0; i < m_row; i++)
{
for(unsigned int j = 0; j < m_col; j++)
{
val[i][j] = mat.val[i][j];
}
}
return *this;
}
// +演算子
Matrix Matrix::operator+(const Matrix& mat) const
{
// 行列同士の行数と列数が等しくないとき
if(m_row != mat.m_row || m_col != mat.m_col){
string err = "Matrix can't be added";
throw err;
}
// 解となる行列
Matrix matAns(m_row, m_col);
// 受け取った2つの行列を加算する
for(unsigned int i = 0; i < m_row; i++)
{
for(unsigned int j = 0; j < m_col; j++)
{
matAns.val[i][j] = val[i][j] + mat.val[i][j];
}
}
return matAns;
}
// +=演算子
Matrix& Matrix::operator+=(const Matrix& mat)
{
// 行列同士の行数と列数が等しくないとき
if(m_row != mat.m_row || m_col != mat.m_col){
string err = "Matrix can't be added";
throw err;
}
// 受け取った2つの行列を加算する
for(unsigned int i = 0; i < m_row; i++)
{
for(unsigned int j = 0; j < m_col; j++)
{
val[i][j] += mat.val[i][j];
}
}
return *this;
}
// -演算子
Matrix Matrix::operator-(const Matrix& mat) const
{
// 行列同士の行数と列数が等しくないとき
if(m_row != mat.m_row || m_col != mat.m_col){
string err = "Matrix can't be subtracted";
throw err;
}
// 解となる行列
Matrix matAns(m_row, m_col);
// 行列減算
for(unsigned int i = 0; i < m_row; i++)
{
for(unsigned int j = 0; j < m_col; j++)
{
matAns.val[i][j] = val[i][j] - mat.val[i][j];
}
}
return matAns;
}
// -=演算子
Matrix& Matrix::operator-=(const Matrix& mat)
{
// 行列同士の行数と列数が等しくないとき
if(m_row != mat.m_row || m_col != mat.m_col){
string err = "Matrix can't be subtracted";
throw err;
}
// 行列加算
for(unsigned int i = 0; i < m_row; i++){
for(unsigned int j = 0; j < m_col; j++)
{
val[i][j] -= mat.val[i][j];
}
}
return *this;
}
// 行列同士の乗算
Matrix Matrix::operator*(const Matrix& mat) const
{
// 被乗数の行列の列数=乗数の行列の行数
if(m_col != mat.m_row){
string err = "Matrix can't be producted";
throw err;
}
// 解となる行列(被乗数の行列の列数、乗数の行列の行数)
Matrix matAns(m_row, mat.m_col);
// 行列の乗算
for(unsigned int i = 0; i < m_row; i++){
for(unsigned int j = 0; j < mat.m_col; j++)
{
for(unsigned int k = 0; k < m_row; k++)
{
matAns.val[i][j] += val[i][k] * mat.val[k][j];
}
}
}
return matAns;
}
// 行列と値の乗算
Matrix Matrix::operator*(const double& in_val) const
{
// 解となる行列
Matrix matAns(m_row, m_col);
for(unsigned int i = 0; i < m_row; i++)
{
for(unsigned int j = 0; j < m_col; j++)
{
matAns.val[i][j] = val[i][j] * in_val;
}
}
return matAns;
}
// 行列と値の乗算
Matrix& Matrix::operator*=(const double& in_val)
{
for(unsigned int i = 0; i < m_row; i++)
{
for(unsigned int j = 0; j < m_col; j++)
{
val[i][j] *= in_val;
}
}
return *this;
}
// 行列と値の除算
Matrix Matrix::operator/(const double& in_val) const
{
// 解となる行列
Matrix matAns(m_row, m_col);
for(unsigned int i = 0; i < m_row; i++)
{
for(unsigned int j = 0; j < m_col; j++)
{
matAns.val[i][j] = val[i][j] / in_val;
}
}
return matAns;
}
// 行列と値の除算
Matrix& Matrix::operator/=(const double& in_val)
{
for(unsigned int i = 0; i < m_row; i++)
{
for(unsigned int j = 0; j < m_col; j++)
{
val[i][j] /= in_val;
}
}
return *this;
}
// 転置行列を求める
Matrix Matrix::transpose() const
{
// 解となる行列(行と列を反対に設定)
Matrix matAns(m_col, m_row);
for(unsigned int i = 0; i < m_row; i++)
{
for(unsigned int j = 0; j < m_col; j++)
{
matAns.val[j][i] = val[i][j];
}
}
return matAns;
}
}
#endif // _MATRIX_H_
| true |
ced574acb1c9df928b2e148aa296d84565a59dfe | C++ | DESPEL/code | /cosa.cpp | UTF-8 | 1,496 | 3.0625 | 3 | [] | no_license | #include <iostream>
#define ir_(b) ;return b; }
#define ff_(b) { b
std::string* sanitize(std::string &s, std::string r = "") ff_(for) (char &c : std::string(s)) (c == ' ') ? r : r += c, s = r ir_(&s)
std::string CaesarEncrypt(std::string s, const int offset) ff_(for) (char &c : *sanitize(s)) (c == ' ') ? c : c = 'a' + (tolower(c) - 'a' + offset + 26) % 26 ir_(s)
std::string VignereEncrypt(std::string s, const std::string key, bool r = false, int idx = 0) ff_(for) (char &c : *sanitize(s)) c = 'a' + (tolower(c) - 'a' + ((key[idx] - 'a') * ((r) ? -1 : 1)) + 26) % 26, idx = (idx + 1) % key.size() ir_(s)
std::string CaesarDecrypt(std::string s, const int offset) ff_( ) ir_(CaesarEncrypt(s, offset * -1))
std::string VignereDecrypt(std::string s, std::string key) ff_() ir_(VignereEncrypt(s, key, true))
int main() {
std::string a = "ABCdef asd";
std::cout << CaesarEncrypt(a, 5) << '\n';
std::cout << CaesarDecrypt(CaesarEncrypt("abcdef asd", 3), 3) << '\n';
std::string key = "abcd";
std::cout << VignereDecrypt(VignereEncrypt("abcdez asd", key), key) << '\n';
/*
int offset = 5;
std::string s = "abc d99";
for(char &c : *sanitize(s)) c = std::string("abcdefghijklmnopqrstuvwxyz0123456789")[(std::string("abcdefghijklmonpqrstuvwxyz0123456789").find(tolower(c)) + offset + std::string("abcdefghijklmonpqrstuvwxyz0123456789").size()) % std::string("abcdefghijklmonpqrstuvwxyz0123456789").size()];
*/
//std::cout << s << '\n';
return 0;
}
| true |
9f8e797056db308688f8768d5c078a63206c680a | C++ | FIRST1778/navxmxp | /roborio/c++/navx_frc_cpp/src/TimestampedQuaternionHistory.h | UTF-8 | 702 | 2.546875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* TimestampedQuaternionHistory.h
*
* Created on: Jul 29, 2015
* Author: Scott
*/
#ifndef SRC_TIMESTAMPED_QUATERNION_HISTORY_H_
#define SRC_TIMESTAMPED_QUATERNION_HISTORY_H_
#include <stdint.h>
#include <mutex>
#include <TimestampedQuaternion.h>
class TimestampedQuaternionHistory {
protected:
TimestampedQuaternion* history;
int history_size;
int curr_index;
int num_valid_samples;
std::mutex history_mutex;
public:
TimestampedQuaternionHistory(int num_samples);
void Add(float w, float x, float y, float z, long new_timestamp);
bool Get( long requested_timestamp, TimestampedQuaternion& out );
};
#endif /* SRC_TIMESTAMPED_QUATERNION_HISTORY_H_ */
| true |
bf194522a1a862919ff7518eab482d3fe43c77f1 | C++ | anna-fomina/stepik-c-part2 | /task_1_2.cpp | UTF-8 | 750 | 3.125 | 3 | [] | no_license | #include <iostream>
struct Base {
int x;
Base(int x = 0) : x(x) {}
virtual void print() const {
std::cout << "Base" << std::endl;
}
};
struct D1 : Base {
void print() const {
std::cout << "D1" << std::endl;
}
};
struct D2 : Base {
void print() const {
std::cout << "D2" << std::endl;
}
};
struct D3 : D1, D2 {
};
Base const * D1BaseToD2Base(Base const * base)
{
return (Base*)(D2*)(D3*)(D1*)base;
}
void task_1_2() {
//D3 p;
//D1 * d1 = &p;
//Base * d1base = d1;
//d1base->print();
//Base const * d2base = D1BaseToD2Base(d1base);
//d2base->print();
int a = 27;
int const b = 412;
int * pa = &a;
//int const c = a;
//int d = b;
//int const * p1 = pa;
//int * const * p2 = &pa;
//int const ** p3 = &pa;
return;
} | true |
43094c51b9d153c2a82832faab8b47ba723b2be6 | C++ | nolanderc/glt | /include/vec/vec.hpp | UTF-8 | 1,471 | 2.8125 | 3 | [
"MIT"
] | permissive | //
// Created by Christofer Nolander on 2017-12-27.
//
#pragma once
#include "vec_core.hpp"
namespace glt {
// Define common vector types
// 2D vectors
typedef vec2<int> vec2i;
typedef vec2<float> vec2f;
typedef vec2<double> vec2d;
// 3D vectors
typedef vec3<int> vec3i;
typedef vec3<float> vec3f;
typedef vec3<double> vec3d;
// 4D vectors
typedef vec4<int> vec4i;
typedef vec4<float> vec4f;
typedef vec4<double> vec4d;
// Define equality operators
template <class T>
bool operator==(const glt::vec2<T>& a, const glt::vec2<T>& b) {
return (a.x == b.x && a.y == b.y);
}
template <class T>
bool operator==(const glt::vec3<T>& a, const glt::vec3<T>& b) {
return (a.x == b.x && a.y == b.y && a.z == b.z);
}
template <class T>
bool operator==(const glt::vec4<T>& a, const glt::vec4<T>& b) {
return (a.x == b.x && a.y == b.y && a.z == b.z && a.w == b.w);
}
// Define inequality operators
template <class T>
bool operator!=(const glt::vec2<T>& a, const glt::vec2<T>& b) {
return (a.x != b.x && a.y != b.y);
}
template <class T>
bool operator!=(const glt::vec3<T>& a, const glt::vec3<T>& b) {
return (a.x != b.x && a.y != b.y && a.z != b.z);
}
template <class T>
bool operator!=(const glt::vec4<T>& a, const glt::vec4<T>& b) {
return (a.x != b.x && a.y != b.y && a.z != b.z && a.w != b.w);
}
}
| true |
8f67558bafba325d6e2cf3a07539a7438f93854a | C++ | KobeyMyhre/SoliPong | /Splash.cpp | UTF-8 | 569 | 2.53125 | 3 | [] | no_license |
#include "Splash.h"
#include "menuestate.h"
#include "sfwdraw.h"
#include <iostream>
void splash::init(int a_font)
{
d = a_font;
}
void splash::play() { timer = 7.f; }
void splash::draw()
{
char buffer[64];
sprintf_s(buffer, "Loading..");
sfw::drawString(d, buffer, 100, 100, 20, 20);
sfw::drawLine(100, 80, 100 + 500 * (timer / 7.f), 80);
if (timer <= 2.5f)
sfw::drawString(d, "Almost Done.", 300, 300, 20, 20);
}
void splash::step()
{
timer -= sfw::getDeltaTime();
}
menueState splash::next()
{
if (timer < 0)
return Enter_Option;
return Splash;
} | true |
cd7df08697066ab200fcc3ca7005370ecc4bb407 | C++ | shivendrakrjha/Dynamic-Programming | /UnboundedKnapsack/max_coin_change.cpp | UTF-8 | 596 | 2.859375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
vector<int> coins = {1, 2, 3};
int sum = 5;
vector<vector<int>> dp;
dp.resize(coins.size() + 1);
for(int i = 0; i < coins.size() + 1; i++)
dp[i].resize(sum + 1, 0);
for(int i = 0; i < coins.size() + 1; i++)
dp[i][0] = 1;
for(int i = 1; i < coins.size() + 1; i++)
for(int j = 1; j < sum + 1; j++)
{
if(coins[i - 1] <= j)
dp[i][j] = dp[i][j - coins[i - 1]] + dp[i - 1][j];
else if(coins[i - 1] > j)
dp[i][j] = dp[i - 1][j];
}
cout << "Number of ways: " << dp[coins.size()][sum] << endl;
return 0;
}
| true |
cc0ed885b0d0456dcb750e6b132d6ab85bf55ed3 | C++ | breakTBB/acm | /OJ/51nod/1268.cc | UTF-8 | 1,490 | 2.84375 | 3 | [] | no_license | #include <stdio.h>
#include <cstring>
#include <algorithm>
using namespace std;
#define CLR(a,b) memset(a,b,sizeof(a))
#define INF 0x3f3f3f3f
#define LL long long
int dp[20000005];
int main()
{
int n;
int num[22];
int k;
int sum = 0;
scanf ("%d %d",&n,&k);
for (int i = 1 ; i <= n ; i++)
{
scanf ("%d",&num[i]);
sum += num[i];
}
if (sum < k)
printf ("No\n");
else if (sum == k)
printf ("Yes\n");
else
{
for (int i = 1 ; i <= n ; i++)
{
for (int j = k ; j >= num[i] ; j--)
dp[j] = max(dp[j] , dp[j-num[i]] + num[i]);
}
if (dp[k] == k)
printf ("Yes\n");
else
printf ("No\n");
}
return 0;
}
// 深度优先搜索解法
#include <iostream>
#include <cstdio>
const int MAXN = 22;
int N, K;
int A[MAXN];
// 从a[dep]开始搜索, 剩K
bool dfs(int rest, int dep)
{
// 搜索完毕
if (dep == N)
{
return false;
}
// 这个数加上之前的数能组成K
if (rest == A[dep])
{
return true;
}
// 这个数比需要的数小
if (rest > A[dep])
{
rest -= A[dep];
// 加到和中去 继续搜索
if (dfs(rest, dep + 1))
{
return true;
}
rest += A[dep];
}
return dfs(rest, dep + 1);
}
int main1()
{
scanf("%d %d", &N, &K);
for (int i = 0; i < N; i++)
{
scanf("%d", A + i);
}
if (dfs(K, 0))
{
printf("Yes\n");
}
else
{
printf("No\n");
}
return 0;
}
| true |
e747a901ed379e4d33d88e2d33f8e0ea6ebf9004 | C++ | ernestyalumni/HrdwCCppCUDA | /Voltron/Source/IO/Epoll/EpollFd.cpp | UTF-8 | 1,817 | 2.765625 | 3 | [
"MIT"
] | permissive | //------------------------------------------------------------------------------
/// \file EpollFd.h
/// \author Ernest Yeung
/// \email ernestyalumni@gmail.com
/// \brief Create a new epoll instance and encapsulate it.
/// \ref http://man7.org/linux/man-pages/man2/epoll_create.2.html
/// http://cs241.cs.illinois.edu/coursebook/Networking#non-blocking-io
//------------------------------------------------------------------------------
#include "EpollFd.h"
#include "Cpp/Utilities/TypeSupport/UnderlyingTypes.h"
//#include "Utilities/ErrorHandling/ErrorHandling.h"
#include <sys/epoll.h>
#include <unistd.h> // ::close
using Cpp::Utilities::TypeSupport::get_underlying_value;
//using Utilities::ErrorHandling::HandleClose;
namespace IO
{
namespace Epoll
{
EpollFd::EpollFd(int size, const bool close_upon_destruction):
fd_{create_epoll_with_size_hint(size)},
close_upon_destruction_{close_upon_destruction}
{}
EpollFd::EpollFd(const EpollFlags flags, const bool close_upon_destruction):
fd_{create_epoll(flags)},
close_upon_destruction_{close_upon_destruction}
{}
EpollFd::~EpollFd()
{
if (close_upon_destruction_)
{
int return_value {::close(fd_)};
//HandleClose()(return_value);
}
}
EpollFd::HandleEpollCreate::HandleEpollCreate() = default;
/*
void EpollFd::HandleEpollCreate::operator()(const int result_value)
{
this->operator()(
result_value,
"create new epoll instance (::epoll_create or ::epoll_create1)");
}
*/
int EpollFd::create_epoll_with_size_hint(int size)
{
int return_value {::epoll_create(size)};
HandleEpollCreate()(return_value);
return return_value;
}
int EpollFd::create_epoll(const EpollFlags flags)
{
int return_value {::epoll_create1(get_underlying_value(flags))};
HandleEpollCreate()(return_value);
return return_value;
}
} // namespace Epoll
} // namespace IO
| true |
4ecae23c9a60422b69def9bc18c0216b7a122b4c | C++ | moyin1004/learning | /TimeLine/20190218/netlib/v3/EventLoop.h | UTF-8 | 1,704 | 2.828125 | 3 | [] | no_license | /// @file EventLoop.h
/// @author moyin(moyin1004@163.com)
/// @data 2019-02-20 17:30:23
#ifndef __EVENTLOOP_H__
#define __EVENTLOOP_H__
#include "MutexLock.h"
#include <sys/epoll.h>
#include <vector>
#include <map>
#include <memory>
#include <functional>
namespace wd {
class Acceptor;
class TcpConnection;
class EventLoop {
public:
using TcpConnectionCallback =
std::function<void(const std::shared_ptr<TcpConnection>)>;
using Functor = std::function<void()>;
EventLoop(Acceptor &acceptor);
~EventLoop();
void loop();
void unloop();
void runInLoop(Functor &&cb);
void doPendingFunctors();
void setConnectionCallback(TcpConnectionCallback && cb)
{ _onConnectionCallback = std::move(cb); }
void setMessageCallback(TcpConnectionCallback && cb)
{ _onMessageCallback = std::move(cb); }
void setCloseCallback(TcpConnectionCallback && cb)
{ _onCloseCallback = std::move(cb); }
private:
int creatEpollFd();
int creatEventFd();
void addEpollReadFd(int fd);
void delEpollReadFd(int fd);
void waitEpollFds();
void handleNewConnection();
void handleMessage(int peerfd);
void handleRead();
void wakeup();
private:
int _epollfd;
int _eventfd;
Acceptor &_acceptor;
std::map<int, std::shared_ptr<TcpConnection>> _connections;
std::vector<struct epoll_event> _eventList;
bool _isLooping;
MutexLock _mutex;
std::vector<Functor> _pendingFunctors; //等待执行的函数,临界资源
TcpConnectionCallback _onConnectionCallback;
TcpConnectionCallback _onMessageCallback;
TcpConnectionCallback _onCloseCallback;
};
} //end of namespace wd
#endif
| true |
381e98fff6ca9edfda2acc7ac7bd49d2a0bfffdc | C++ | hzjTurbo/pat_Practice | /PAT (Basic Level) Practise (中文)/b1032.cpp | UTF-8 | 406 | 2.625 | 3 | [] | no_license | //pat_b1032
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 100000 + 5;
int iScore[maxn] = { 0 };
int main(){
int N;
cin >> N;
while (N--){
int trem, score;
cin >> trem >> score;
iScore[trem] += score;
}
int index = 0;
for (int i = 0; i < maxn; i++){
if (iScore[index] < iScore[i])
index = i;
}
cout << index << " " << iScore[index] << endl;
return 0;
} | true |
b20cdfdbad94426cbefd46cb4f82c838d5a772e6 | C++ | rheehot/Algorithm-40 | /BOJ/11729/11729.cpp | UHC | 1,422 | 3.640625 | 4 | [] | no_license | #include <iostream>
#include <cmath>
void Hanoi(int n, int from, int tmp, int to) {
if (n == 1) {
printf("%d %d\n", from, to);
}
else {
Hanoi(n - 1, from, to, tmp);
printf("%d %d\n", from, to);
Hanoi(n - 1, tmp, from, to);
}
}
int main() {
int n;
scanf("%d", &n);
printf("%d\n", (int)pow(2, n) - 1);
Hanoi(n, 1, 2, 3);
return 0;
}
/*
밡 ְ ù ° 뿡 ݰ ٸ n ִ. ݰ ū ִ.
µ Ģ ù ° 뿡 ° ű Ѵ.
Ǹ ٸ ž ű ִ.
Ʒ ͺ ۾ƾ Ѵ.
۾ ϴµ ʿ ̵ ϴ α ۼ϶. , ̵ Ƚ ּҰ Ǿ Ѵ.
Ʒ 5 ̴.
Է
ù° ٿ ù ° 뿡 N (1 N 20) ־.
ù° ٿ ű Ƚ K Ѵ.
° ٺ Ѵ. ° ٺ K ٿ A B ĭ ̿ ΰ ϴµ,
̴ A° ž ִ B° ž űٴ ̴.
*/ | true |
d7307bd0011768db23885360dae67395bb9b0e57 | C++ | AminTakhtiNejad/laplacian_filter_hls | /filter.cpp | SHIFT_JIS | 3,339 | 2.6875 | 3 | [] | no_license | /**
* Laplacian filter by AXI4-Stream input/output.
* Achieves 1 clk/pixel.
*/
#include <stdio.h>
#include <string.h>
#include <ap_int.h>
#include <hls_stream.h>
#include <ap_axi_sdata.h>
#define HORIZONTAL_PIXEL_WIDTH 240
int laplacian_fil(int x0y0, int x1y0, int x2y0, int x0y1, int x1y1, int x2y1, int x0y2, int x1y2, int x2y2);
int conv_rgb2y(int rgb);
int lap_filter_axim(hls::stream<ap_axiu<32,1,1,1> >& in, hls::stream<ap_axiu<32,1,1,1> >& out)
{
#pragma HLS INTERFACE axis port=in
#pragma HLS INTERFACE axis port=out
#pragma HLS INTERFACE s_axilite port=return
ap_axiu<32, 1, 1, 1> val; // input value
ap_axiu<32, 1, 1, 1> lap; // output value
int i=0, j=0;
unsigned int y_buf[2][HORIZONTAL_PIXEL_WIDTH];
#pragma HLS array_partition variable=y_buf block factor=2 dim=1
#pragma HLS resource variable=y_buf core=RAM_2P
unsigned int window[3][3]; // filter window
#pragma HLS array_partition variable=window complete
do {
#pragma HLS DEPENDENCE variable=y_buf inter false
#pragma HLS PIPELINE
#pragma HLS LOOP_TRIPCOUNT min=240*120 max=240*120
val = in.read();
int y = conv_rgb2y(val.data);
window[0][0] = window[0][1]; // VtgWX^ :-)
window[0][1] = window[0][2];
window[0][2] = y_buf[0][i];
window[1][0] = window[1][1];
window[1][1] = window[1][2];
window[1][2] = y_buf[1][i];
window[2][0] = window[2][1];
window[2][1] = window[2][2];
window[2][2] = y; // ݂̓
y_buf[0][i] = y_buf[1][i]; // Vtg :-<
y_buf[1][i] = y;
int lapval = laplacian_fil(window[0][0], window[0][1], window[0][2],
window[1][0], window[1][1], window[1][2],
window[2][0], window[2][1], window[2][2]);
lap.data = (lapval<<16)|(lapval<<8)|lapval;
lap.last = val.last; // copy tlast
if (j >= 2 && i >= 2) // ̕͏o͂Ȃ̂Ő2f
out.write(lap);
if (val.user){
i = 0;
j++;
}else{
i++;
}
}while (!val.last);
return 0;
}
// RGBYւ̕ϊ
// RGB̃tH[}bǵA{8'd0, R(8bits), G(8bits), B(8bits)}, 1pixel = 32bits
// PxMŶ݂ɕϊBΐAY = 0.299R + 0.587G + 0.114B
// "YUVtH[}bgy YUV<->RGBϊ"QlɂBhttp://vision.kuee.kyoto-u.ac.jp/~hiroaki/firewire/yuv.html
//@2013/09/27 : float ~߂āAׂint ɂ
int conv_rgb2y(int rgb){
int r,g,b;
int y_f;
int y;
r = (rgb >> 16) & 0xFF;
g = (rgb >> 8) & 0xFF;
b = rgb & 0xFF;
y_f = 77*r + 150*g + 29*b; //y_f = 0.299*r + 0.587*g + 0.114*b;̌W256{
y = y_f >> 8; // 256Ŋ
return(y);
}
// vVAtB^
// x0y0 x1y0 x2y0 -1 -1 -1
// x0y1 x1y1 x2y1 -1 8 -1
// x0y2 x1y2 x2y2 -1 -1 -1
int laplacian_fil(int x0y0, int x1y0, int x2y0, int x0y1, int x1y1, int x2y1, int x0y2, int x1y2, int x2y2)
{
int y;
y = -x0y0 -x1y0 -x2y0 -x0y1 +8*x1y1 -x2y1 -x0y2 -x1y2 -x2y2;
if (y<0)
y = 0;
else if (y>255)
y = 255;
return(y);
}
| true |
1170eebc3d71369e0725c8b0aae9a49cc085c521 | C++ | oledjan/Blm | /Blm/biosec_lib/archiveEntry.h | UTF-8 | 1,506 | 2.609375 | 3 | [] | no_license | #ifndef __archiveEntry_h__
#define __archiveEntry_h__
#include <vector>
#include <memory>
#include "libarchive/archive_entry.h"
#include "libarchive/archive.h"
#include "fileEncryptor.h"
namespace blm_utils{
enum class EntryFileType{
REGULAR,
DIRECTORY
};
class ArchiveEntry {
public:
ArchiveEntry();
~ArchiveEntry();
struct archive_entry* getEntry() const;
std::vector<char> readAttribute(const std::string& name) const;
void writeAttribute(const std::string& name, void* val, size_t size);
void setPathnameWithEncryption(const std::wstring &pathName, std::shared_ptr<blm_utils::IFileEncryptor> encryptor);
void setPathnameW(const std::wstring& pathname);
std::wstring getPathnameW() const;
void setSize(std::int64_t size);
void setPermissions(std::int64_t permissons);
void setMtime(time_t mTime);
time_t getMtime();
void setFileType(EntryFileType filetype);
EntryFileType getFileType() const;
std::wstring getPathnameWithEncryption(std::shared_ptr<blm_utils::IFileEncryptor> encryptor) const;
DWORD readFileAttributes() const;
void writeFileAttributes(DWORD attributes);
private:
static const std::size_t kRandomStringLength_ = 0x20;
static const char* attributesKey() {
return "fAttr";
}
ArchiveEntry(const ArchiveEntry &);
ArchiveEntry &operator=(const ArchiveEntry &);
struct archive_entry* entry_;
static const char* pathnameEncryptedAttribute() {
return "nameEcnrypted";
}
};
} // blm_utils
#endif // __archiveEntry_h__
| true |
729b78ed623951b47f191cd5526a544381f7a8a1 | C++ | jfcarr/arduino-c-cpp | /1-simple/CTest/CTest.ino | UTF-8 | 202 | 2.65625 | 3 | [] | no_license |
void setup() { pinMode(LED_BUILTIN, OUTPUT); }
void loop() {
int delayValue = 250;
digitalWrite(LED_BUILTIN, HIGH);
delay(delayValue);
digitalWrite(LED_BUILTIN, LOW);
delay(delayValue);
}
| true |
d06800883fd697de801bbc335eec831d549e35fe | C++ | SOMAS2020/somas-demo | /src/server.cpp | UTF-8 | 4,426 | 3.125 | 3 | [] | no_license | #include <zmqpp/zmqpp.hpp>
#include <bits/stdc++.h>
#include "client.hpp"
#include "consts.hpp"
// get_clients gets a mapping from the port string to the `clients/<teamname>_<portnum>`
// representation of the client.
// Health checks like port number >=1024 and repeat port numbers are run.
void get_clients(std::vector<Client *> &clients)
{
if (!std::filesystem::exists("clients"))
{
std::cerr << "'clients' directory does not exist!" << std::endl;
std::exit(EXIT_FAILURE);
}
std::regex path_regex("clients/[a-zA-Z0-9]+_[0-9]{4}");
std::unordered_set<std::string> used_ports;
// iterate through all directories in `clients`
for (const auto &p : std::filesystem::directory_iterator("clients"))
if (p.is_directory())
{
const std::string path = p.path();
if (!std::regex_match(path, path_regex))
{
std::cerr << "Ignoring '" << path << "': does not match required regex" << std::endl;
continue;
}
try
{
Client *c = new Client(path);
auto port = c->get_port();
if (used_ports.count(port))
{
std::stringstream ss;
ss << "Error for '" << c << "': port number '"
<< port << "' already used" << std::endl;
throw ss.str();
}
used_ports.insert(port);
clients.push_back(c);
}
catch (std::string &e)
{
std::stringstream ss;
ss << "Failed to create client for path: '" << path << "': " << e;
throw ss.str();
}
}
}
// build_clients runs the build.sh scripts of the client.
void build_clients(const std::vector<Client *> &clients)
{
for (const auto &x : clients)
{
try
{
x->build();
}
catch (std::string &e)
{
std::stringstream ss;
ss << "Can't build '" << *x << "': " << e << std::endl;
throw ss.str();
}
}
}
// run_clients kills all processes on the port then runs the run.sh scripts
// of the clients.
void run_clients(const std::vector<Client *> &clients)
{
for (const auto &x : clients)
{
try
{
x->run();
}
catch (std::string &e)
{
std::stringstream ss;
ss << "Can't run '" << *x << "': " << e << std::endl;
throw ss.str();
}
}
}
void send_first_hello(const std::vector<Client *> &clients)
{
for (const auto &x : clients)
{
std::cerr << "Trying to send first hello to '" << *x << "'" << std::endl;
// try to see if we can get back the port
const auto port = x->get_port();
auto got = x->request(port);
if (got != port)
{
std::stringstream ss;
ss << "got != want: " << got << " != " << port << std::endl;
throw ss.str();
}
std::cerr << *x << " OK! " << std::endl;
}
}
void teardown(const std::vector<Client *> clients) {
for (const auto &x : clients)
{
x->~Client();
}
}
int main(int argc, char *argv[])
{
std::vector<Client *> clients;
try {
get_clients(clients);
std::cerr << "Got clients: " << std::endl;
for (const auto &x : clients)
std::cerr << "\t" << *x << std::endl;
std::cerr << "Building clients!" << std::endl;
build_clients(clients);
std::cerr << "Finished starting clients!" << std::endl;
std::cerr << "Starting clients!" << std::endl;
run_clients(clients);
std::cerr << "Finished starting clients!" << std::endl;
std::cerr << "Sending first requests!" << std::endl;
send_first_hello(clients);
std::cerr << "Finished requests!" << std::endl;
}
catch (std::string& e)
{
teardown(clients);
std::cerr << e << std::endl;
return EXIT_FAILURE;
}
catch (std::exception& e)
{
teardown(clients);
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
catch (...)
{
teardown(clients);
std::cerr << "Unknown exception occurred" << std::endl;
return EXIT_FAILURE;
}
}
| true |
b93f2ed69e775a62b5c465a55966569627d43617 | C++ | me-cooper/esp_controlled_via_esp_over_wifi | /client_1.ino | UTF-8 | 1,602 | 2.578125 | 3 | [] | no_license | #include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
HTTPClient sender;
//Wlan-Daten eures Netzwerks eintragen
const char* ssid = "WLAN_SSID";
const char* password = "WLAN_PASSWD";
void setup()
{
Serial.begin(115200);
Serial.println("ESP Gestartet");
WiFi.begin(ssid, password);
Serial.print("Verbindung wird hergestellt ...");
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Verbunden! IP-Adresse: ");
Serial.println(WiFi.localIP());
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
//Status des Relais vom Server abfragen
sender.begin("http://192.168.178.56/state");
sender.GET();
//Inhalt der Webseite http://192.168.178.56/state wird in die Variable returned_data geschrieben
String returned_data = sender.getString();
//Ausgabe nur zu debuggin-Zwecke im seriellen Monitor
Serial.println(returned_data);
//Wenn Status = 1 ist, dann Relais über den Link ausschalten
if(returned_data == "1"){
sender.begin("http://192.168.178.56/off");
sender.GET();
}
//Wenn Status = 0 ist, dann Relais über den Link anschalten
if(returned_data == "0"){
sender.begin("http://192.168.178.56/on");
sender.GET();
}
//Der Anfrage 1000ms Zeit geben, bevor die Verbindung zum Server wieder beendet wird
delay(1000);
sender.end();
}
//Nach dem Befehl 5 Sekunden warten bevor der nächste ausfegührt wird
delay(5000);
}
| true |
a73a7b4e46f5979e3c114228d44c24da4ecaaa39 | C++ | Alexzerntev/C-Cpp-Projects | /Syspro/syspro1/tests/bitcoin_tree_test.cpp | UTF-8 | 2,071 | 3.0625 | 3 | [] | no_license | #include "gtest/gtest.h"
#include "../error_handler/error_handler.h"
#include "../data_structures/bitcoin_tree/bitcoin_tree.h"
#include "../string/string_handler.h"
namespace
{
class BitcoinTreeTest : public testing::Test
{
protected:
BitcoinTreeTest()
{
}
~BitcoinTreeTest() override
{
}
void SetUp() override
{
}
void TearDown() override
{
}
};
TEST_F(BitcoinTreeTest, CreateNodeTest)
{
int dump = 0;
BitcoinTreeNode *node = create_bitcoin_node(0, 20, NULL, &dump);
ASSERT_EQ(node->id, 0);
ASSERT_TRUE(node->next == NULL);
ASSERT_TRUE(node->to_child == NULL);
ASSERT_TRUE(node->from_child == NULL);
destroy_bitcoin_nodes(node);
}
TEST_F(BitcoinTreeTest, AddNodeTest)
{
int dump = 0;
BitcoinTreeNode *node = create_bitcoin_node(0, 10, NULL, &dump);
int result = add_bitcoin_node(&node, 1, 20, NULL, &dump);
if (result != SUCCESS)
{
FAIL();
}
result = add_bitcoin_node(&node, 2, 30, NULL, &dump);
if (result != SUCCESS)
{
FAIL();
}
ASSERT_EQ(node->value, 30);
ASSERT_EQ(node->id, 2);
ASSERT_EQ(node->next->value, 20);
ASSERT_EQ(node->next->id, 1);
ASSERT_EQ(node->next->next->value, 10);
ASSERT_EQ(node->next->next->id, 0);
ASSERT_TRUE(node->next->next->next == NULL);
destroy_bitcoin_nodes(node);
}
TEST_F(BitcoinTreeTest, AddBitcoinTransactionNodeTest)
{
int dump = 0;
BitcoinTreeNode *node = create_bitcoin_node(1, 10, NULL, &dump);
BitcoinTreeNode *node1 = create_bitcoin_node(2, 20, NULL, &dump);
BitcoinTreeNode *node2 = create_bitcoin_node(3, 30, NULL, &dump);
add_bitcoin_transaction_node(node, node1);
add_bitcoin_transaction_node(node, node2);
ASSERT_EQ(node->value, 10);
ASSERT_EQ(node->id, 1);
ASSERT_EQ(node->next->value, 20);
ASSERT_EQ(node->next->id, 2);
ASSERT_EQ(node->next->next->value, 30);
ASSERT_EQ(node->next->next->id, 3);
ASSERT_TRUE(node->next->next->next == NULL);
destroy_bitcoin_nodes(node);
}
}; // namespace | true |
304ce4a4d2aea82e5890a0152bc85ba7c7dd8efc | C++ | Daviswww/Submissions-by-UVa-etc | /AOJ ITP1/AOJ 041 - Dice I.cpp | UTF-8 | 883 | 2.8125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
const int
a[6] = {1, 2, 3, 4, 5, 6},
w[6] = {3, 2, 6, 1, 5, 4},
e[6] = {4, 2, 1, 6, 5, 3},
n[6] = {2, 6, 3, 4, 1, 5},
s[6] = {5, 1, 3, 4, 6, 2};
int main()
{
string str;
int ary[6] = {0}, ax[6];
for(int i = 0; i < 6; i++)
{
cin >> ary[i];
}
cin >> str;
for(int i = 0; i < str.size(); i++)
{
if(str[i] == 'W')
{
for(int i = 0; i < 6; i++)
{
ax[i] = ary[w[i]-1];
}
}
if(str[i] == 'E')
{
for(int i = 0; i < 6; i++)
{
ax[i] = ary[e[i]-1];
}
}
if(str[i] == 'N')
{
for(int i = 0; i < 6; i++)
{
ax[i] = ary[n[i]-1];
}
}
if(str[i] == 'S')
{
for(int i = 0; i < 6; i++)
{
ax[i] = ary[s[i]-1];
}
}
for(int i = 0; i < 6; i++)
{
ary[i] = ax[i];
}
}
cout << ary[0] << endl;
return 0;
}
| true |
fad428f129ce0685b3a4b67ac514172b528b3987 | C++ | dineshmakkar079/My-DS-Algo-code | /interviewbit/Letter_Phone.cpp | UTF-8 | 1,688 | 3.5 | 4 | [] | no_license | /*
Time : Sat Aug 19 2017 16:13:49 GMT+0530 (IST)
URL : https://www.interviewbit.com/problems/letter-phone/
Given a digit string, return all possible letter combinations that the number could represent.
A
mapping of digit to letters (just like on the telephone buttons) is given below.
The digit 0
maps to 0 itself.
The digit 1 maps to 1 itself.
Input: Digit string "23"
Output: ["ad", "ae", "af",
"bd", "be", "bf", "cd", "ce", "cf"].
Make sure the returned strings are lexicographically sorted.
*/
#include <bits/stdc++.h>
using namespace std;
void letterCombHelper(string s,int start,int end,vector<string>& ans,map<char,string>& m){
if(start>end)
return;
if(start==end){
char c = s[start];
string pat = m[c];
int l = pat.length();
for(int i=0;i<l;i++){
ans.push_back(string(1,pat[i]));
}
return;
}
string pat = m[s[start]];
int prev = ans.size();
letterCombHelper(s,start+1,end,ans,m);
int now = ans.size();
for(int i=1;i<pat.length();i++){
for(int j=prev;j<now;j++){
string old = ans[j];
string curr = pat[i] + ans[j];
ans.push_back(curr);
}
}
for(int j=prev;j<now;j++){
ans[j] = pat[0] + ans[j];
}
}
vector<string> Solution::letterCombinations(string A) {
map<char, string> m; map<char,string>& mapkeys = m;
m['0']="0";m['1']="1";m['2']="abc";m['3']="def";m['4']="ghi";m['5']="jkl";
m['6']="mno";m['7']="pqrs";m['8']="tuv";m['9']="wxyz";
vector<string> a;
vector<string>& ans = a;
letterCombHelper(A,0,A.length()-1,ans,mapkeys);
return ans;
}
int main(){
return 0;
}
| true |
73ff50ea351751307476b587ce788e00f9341def | C++ | troy-dem/le_garage | /one_led_matrix_test/one_led_matrix_test.ino | UTF-8 | 829 | 2.6875 | 3 | [] | no_license | #include "LedControl.h"
/*
pin 2 is connected to the DataIn
pin 4 is connected to the CLK
pin 3 is connected to LOAD
***** Please set the number of devices you have *****
*/
LedControl lc=LedControl(12,10,11,1);
const int addrL = 0; // first LED matrix - Left robot eye
/*const int addrR = 1; // second LED matrix - Right robot eye*/
void setup() {
/*The MAX72XX is in power-saving mode on startup*/
lc.shutdown(addrL,false);
/*lc.shutdown(addrR,false);*/
/* Set the brightness to max values */
lc.setIntensity(addrL,8);
/*lc.setIntensity(addrR,15);*/
/* and clear the display */
lc.clearDisplay(addrL);
/*lc.clearDisplay(addrR);*/
delay(300);
}
void loop() {
// put your main code here, to run repeatedly:
lc.setRow(0,2,B10110000);
delay(1000);
lc.setRow(0,6,B00010000);
delay(700);
}
| true |
9276c71166bfef3d7f1f47d9eb8add8020828d79 | C++ | WayWingsDev/SIMUL_DSA | /HOG/cvModifiedPeopleDetect/otherPeople/tutorial/tutorial3.cpp | UTF-8 | 11,452 | 3.0625 | 3 | [] | no_license | /*This function takes in a the path and names of 64x128 pixel images, the size of the cell to be
used for calculation of hog features(which should be 8x8 pixels, some modifications will have to be
done in the code for a different cell size, which could be easily done once the reader understands
how the code works), a default block size of 2x2 cells has been considered and the window size
parameter should be 64x128 pixels (appropriate modifications can be easily done for other say
64x80 pixel window size). All the training images are expected to be stored at the same location and
the names of all the images are expected to be in sequential order like a1.jpg, a2.jpg, a3.jpg ..
and so on or a(1).jpg, a(2).jpg, a(3).jpg ... The explanation of all the parameters below will make
clear the usage of the function. The synopsis of the function is as follows :
prefix : it should be the path of the images, along with the prefix in the image name for
example if the present working directory is /home/saurabh/hog/ and the images are in
/home/saurabh/hog/images/positive/ and are named like pos1.jpg, pos2.jpg, pos3.jpg ....,
then the prefix parameter would be "images/positive/pos" or if the images are
named like pos(1).jpg, pos(2).jpg, pos(3).jpg ... instead, the prefix parameter
would be "images/positive/pos("suffix : it is the part of the name of the image
files after the number for example for the above examples it would be ".jpg" or ").jpg"
cell : it should be CvSize(8,8), appropriate changes need to be made for other cell sizes
window : it should be CvSize(64,128), appropriate changes need to be made for other window sizes
number_samples : it should be equal to the number of training images, for example if the
training images are pos1.jpg, pos2.jpg ..... pos1216.jpg, then it should be 1216
start_index : it should be the start index of the images' names for example for the above case it
should be 1 or if the images were named like pos1000.jpg, pos1001.jpg, pos1002.jpg
.... pos2216.jpg, then it should be 1000
end_index : it should be the end index of the images' name for example for the above cases it should be 1216 or 2216
savexml : if you want to store the extracted features, then you can pass to it the name of an xml
file to which they should be saved
normalization : the normalization scheme to be used for computing the hog features, any of the
opencv schemes could be passed or -1 could be passed if no normalization is to be done
*/
CvMat* train_64x128(char *prefix, char *suffix, CvSize cell,CvSize window, int number_samples, int start_index,
int end_index, char *savexml = NULL, int canny = 0,int block = 1, int normalization = 4)
{
char filename[50] = "\0", number[8];
int prefix_length;
prefix_length = strlen(prefix);
int bins = 9;
/* A default block size of 2x2 cells is considered */
int block_width = 2, block_height = 2;
/* Calculation of the length of a feature vector for
an image (64x128 pixels)*/
int feature_vector_length;
feature_vector_length = (((window.width - cell.width * block_width)/ cell.width) + 1) *(((window.height - cell.height * block_height)/cell.height) + 1) * 36;
/* Matrix to store the feature vectors for
all(number_samples) the training samples */
CvMat* training = cvCreateMat(number_samples,feature_vector_length, CV_32FC1);
CvMat row;
CvMat* img_feature_vector;
IplImage** integrals;
int i = 0, j = 0;
printf("Beginning to extract HoG features from positive images\n");
strcat(filename, prefix);
/* Loop to calculate hog features for each
image one by one */
for (i = start_index; i <= end_index; i++)
{
cvtInt(number, i);
strcat(filename, number);
strcat(filename, suffix);
IplImage* img = cvLoadImage(filename);
/* Calculation of the integral histogram for
fast calculation of hog features*/
integrals = calculateIntegralHOG(img);
cvGetRow(training, &row, j);
img_feature_vector = calculateHOG_window(integrals, cvRect(0, 0, window.width, window.height), normalization);
cvCopy(img_feature_vector, &row);
j++;
printf("%s\n", filename);
filename[prefix_length] = '\0';
for (int k = 0; k < 9; k++)
{
cvReleaseImage(&integrals[k]);
}
}
if (savexml != NULL)
{
cvSave(savexml, training);
}
return training;
}
/* This function is almost the same as train_64x128(...), except the fact that it can
take as input images of bigger sizes and generate multiple samples out of a single
image.
It takes 2 more parameters than train_64x128(...), horizontal_scans and
vertical_scans to determine how many samples are to be generated from the image. It
generates horizontal_scans x vertical_scans number of samples. The meaning of rest of the
parameters is same.
For example for a window size of 64x128 pixels, if a 320x240 pixel image is
given input with horizontal_scans = 5 and vertical scans = 2, then it will generate to
samples by considering windows in the image with (x,y,width,height) as
(0,0,64,128),
(64,0,64,128), (128,0,64,128), .....,
(0,112,64,128), (64,112,64,128) .....
(256,112,64,128)
The function takes non-overlapping windows from the image except the last row and last
column, which could overlap with the second last row or second last column. So the values
of horizontal_scans and vertical_scans passed should be such that it is possible to perform
that many scans in a non-overlapping fashion on the given image. For example horizontal_scans
= 5 and vertical_scans = 3 cannot be passed for a 320x240 pixel image as that many vertical scans
are not possible for an image of height 240 pixels and window of height 128 pixels.
*/
CvMat* train_large(char *prefix, char *suffix,CvSize cell, CvSize window, int number_images,
int horizontal_scans, int vertical_scans,int start_index, int end_index,
char *savexml = NULL, int normalization = 4)
{
char filename[50] = "\0", number[8];
int prefix_length;
prefix_length = strlen(prefix);
int bins = 9;
/* A default block size of 2x2 cells is considered */
int block_width = 2, block_height = 2;
/* Calculation of the length of a feature vector for
an image (64x128 pixels)*/
int feature_vector_length;
feature_vector_length = (((window.width -
cell.width * block_width) / cell.width) + 1) *
(((window.height - cell.height * block_height)
/ cell.height) + 1) * 36;
/* Matrix to store the feature vectors for
all(number_samples) the training samples */
CvMat* training = cvCreateMat(number_images
* horizontal_scans * vertical_scans,
feature_vector_length, CV_32FC1);
CvMat row;
CvMat* img_feature_vector;
IplImage** integrals;
int i = 0, j = 0;
strcat(filename, prefix);
printf("Beginning to extract HoG features
from negative images\n");
/* Loop to calculate hog features for each
image one by one */
for (i = start_index; i <= end_index; i++)
{
cvtInt(number, i);
strcat(filename, number);
strcat(filename, suffix);
IplImage* img = cvLoadImage(filename);
integrals = calculateIntegralHOG(img);
for (int l = 0; l < vertical_scans - 1; l++)
{
for (int k = 0; k < horizontal_scans - 1; k++)
{
cvGetRow(training, &row, j);
img_feature_vector = calculateHOG_window(
integrals, cvRect(window.width * k,
window.height * l, window.width,
window.height), normalization);
cvCopy(img_feature_vector, &row);
j++;
}
cvGetRow(training, &row, j);
img_feature_vector = calculateHOG_window(
integrals, cvRect(img->width - window.width,
window.height * l, window.width,
window.height), normalization);
cvCopy(img_feature_vector, &row);
j++;
}
for (int k = 0; k < horizontal_scans - 1; k++)
{
cvGetRow(training, &row, j);
img_feature_vector = calculateHOG_window(
integrals, cvRect(window.width * k,
img->height - window.height, window.width,
window.height), normalization);
cvCopy(img_feature_vector, &row);
j++;
}
cvGetRow(training, &row, j);
img_feature_vector = calculateHOG_window(integrals,
cvRect(img->width - window.width, img->height -
window.height, window.width, window.height),
normalization);
cvCopy(img_feature_vector, &row);
j++;
printf("%s\n", filename);
filename[prefix_length] = '\0';
for (int k = 0; k < 9; k++)
{
cvReleaseImage(&integrals[k]);
}
cvReleaseImage(&img);
}
printf("%d negative samples created \n",
training->rows);
if (savexml != NULL)
{
cvSave(savexml, training);
printf("Negative samples saved as %s\n",
savexml);
}
return training;
}
/* This function trains a linear support vector machine for object classification. The synopsis is
as follows :
pos_mat : pointer to CvMat containing hog feature vectors for positive samples. This may be
NULL if the feature vectors are to be read from an xml file
neg_mat : pointer to CvMat containing hog feature vectors for negative samples. This may be
NULL if the feature vectors are to be read from an xml file
savexml : The name of the xml file to which the learnt svm model should be saved
pos_file: The name of the xml file from which feature vectors for positive samples are to be read.
It may be NULL if feature vectors are passed as pos_mat
neg_file: The name of the xml file from which feature vectors for negative samples are to be read.
It may be NULL if feature vectors are passed as neg_mat
*/
void trainSVM(CvMat* pos_mat, CvMat* neg_mat, char *savexml,char *pos_file = NULL, char *neg_file = NULL)
{
/* Read the feature vectors for positive samples */
if (pos_file != NULL)
{
printf("positive loading...\n");
pos_mat = (CvMat*) cvLoad(pos_file);
printf("positive loaded\n");
}
/* Read the feature vectors for negative samples */
if (neg_file != NULL)
{
neg_mat = (CvMat*) cvLoad(neg_file);
printf("negative loaded\n");
}
int n_positive, n_negative;
n_positive = pos_mat->rows;
n_negative = neg_mat->rows;
int feature_vector_length = pos_mat->cols;
int total_samples;
total_samples = n_positive + n_negative;
CvMat* trainData = cvCreateMat(total_samples,
feature_vector_length, CV_32FC1);
CvMat* trainClasses = cvCreateMat(total_samples,
1, CV_32FC1 );
CvMat trainData1, trainData2, trainClasses1,
trainClasses2;
printf("Number of positive Samples : %d\n",
pos_mat->rows);
/*Copy the positive feature vectors to training
data*/
cvGetRows(trainData, &trainData1, 0, n_positive);
cvCopy(pos_mat, &trainData1);
cvReleaseMat(&pos_mat);
/*Copy the negative feature vectors to training
data*/
cvGetRows(trainData, &trainData2, n_positive,
total_samples);
cvCopy(neg_mat, &trainData2);
cvReleaseMat(&neg_mat);
printf("Number of negative Samples : %d\n",
trainData2.rows);
/*Form the training classes for positive and
negative samples. Positive samples belong to class
1 and negative samples belong to class 2 */
cvGetRows(trainClasses, &trainClasses1, 0, n_positive);
cvSet(&trainClasses1, cvScalar(1));
cvGetRows(trainClasses, &trainClasses2, n_positive,
total_samples);
cvSet(&trainClasses2, cvScalar(2));
/* Train a linear support vector machine to learn from
the training data. The parameters may played and
experimented with to see their effects*/
CvSVM svm(trainData, trainClasses, 0, 0,
CvSVMParams(CvSVM::C_SVC, CvSVM::LINEAR, 0, 0, 0, 2,
0, 0, 0, cvTermCriteria(CV_TERMCRIT_EPS,0, 0.01)));
printf("SVM Training Complete!!\n");
/*Save the learnt model*/
if (savexml != NULL)
{
svm.save(savexml);
}
cvReleaseMat(&trainClasses);
cvReleaseMat(&trainData);
}
| true |
9214e161ce1147ed37d66d691d390a6882bfcea0 | C++ | gbrlas/AVSP | /CodeJamCrawler/dataset/14_4065_55.cpp | UTF-8 | 2,323 | 2.53125 | 3 | [] | no_license | package com.main;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class CookieClicker {
public static void main(String... args) {
BufferedReader br = null;
BufferedWriter bw = null;
String temp[] = null;
Double farm;
Double cookiesPerSec;
Double result;
Double sec = 0.0;
int multiplier = 1;
try {
br = new BufferedReader(new FileReader(System.getProperty("user.home") + "\\B-small-attempt5.in"));
bw = new BufferedWriter(new FileWriter(System.getProperty("user.home") + "\\B-small-attempt5.out"));
PrintWriter fileOut = new PrintWriter(bw);
long numberInp = Integer.parseInt(br.readLine());
for (int index = 1; index <= numberInp; index++) {
multiplier = 1;
sec = 0.0;
temp = br.readLine().split(" ");
farm = Double.parseDouble(temp[0]);
cookiesPerSec = Double.parseDouble(temp[1]);
result = Double.parseDouble(temp[2]);
if (farm >= result) {
sec = result/2;
fileOut.println("Case #"+index+": "+new BigDecimal(sec).setScale(7, RoundingMode.HALF_UP));
} else {
if ((farm/(2)+(result/(2+cookiesPerSec))) < result/(2)) {
sec = sec + new BigDecimal(farm/2).setScale(7, RoundingMode.HALF_UP).doubleValue();
while ((farm/(2+multiplier*cookiesPerSec)+(result/(2+multiplier*cookiesPerSec+cookiesPerSec))) < result/(2+multiplier*cookiesPerSec)) {
sec = sec + farm/(2+multiplier*cookiesPerSec);
multiplier++;
}
sec = sec + new BigDecimal(result/(2+multiplier*cookiesPerSec)).setScale(7, RoundingMode.HALF_UP).doubleValue();
fileOut.println("Case #"+index+": "+new BigDecimal(sec).setScale(7, RoundingMode.HALF_UP));
} else {
sec = result/2;
fileOut.println("Case #"+index+": "+new BigDecimal(sec).setScale(7, RoundingMode.HALF_UP));
}
}
}
fileOut.flush();
bw.flush();
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
bw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
| true |