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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
66fdc50752bf9933f40ec92330e21553e4358f46 | C++ | andreip/sdl2_playground | /src/Game.h | UTF-8 | 676 | 2.640625 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <SDL2/SDL.h>
#include "SlotMachine.h"
class Game {
public:
// initializes SDL logic.
Game()
: mWindow(nullptr),
mRenderer(nullptr)
{
}
// cleanup SDL logic.
~Game() { free(); }
void init();
void loop(); // game loop
private:
void free();
// rendering state
SDL_Event mEvent;
SDL_Window *mWindow;
SDL_Renderer *mRenderer;
SlotMachine *mSlotMachine;
// screen data
constexpr static int SCREEN_WIDTH = 640;
constexpr static int SCREEN_HEIGHT = 480;
// slot machine box
constexpr static int SLOT_MACHINE_HEIGHT = 200;
constexpr static int SLOT_MACHINE_WIDTH = SCREEN_WIDTH - 100;
};
| true |
c24b2fe9ea40451ee60faec4045c4e485da608d8 | C++ | sgzwiz/misc_microsoft_gamedev_source_code | /misc_microsoft_gamedev_source_code/misc_microsoft_gamedev_source_code/extlib/Rockall/Code/Rockall/Tests/TestHeaps.cpp | UTF-8 | 7,237 | 2.59375 | 3 | [] | no_license |
// Ruler
// 1 2 3 4 5 6 7 8
//345678901234567890123456789012345678901234567890123456789012345678901234567890
/********************************************************************/
/* */
/* The standard layout. */
/* */
/* The standard layout for 'cpp' files in this code is as */
/* follows: */
/* */
/* 1. Include files. */
/* 2. Constants local to the class. */
/* 3. Data structures local to the class. */
/* 4. Data initializations. */
/* 5. Static functions. */
/* 6. Class functions. */
/* */
/* The constructor is typically the first function, class */
/* member functions appear in alphabetical order with the */
/* destructor appearing at the end of the file. Any section */
/* or function this is not required is simply omitted. */
/* */
/********************************************************************/
#include "Barrier.hpp"
#include "TestHeaps.hpp"
#include "Thread.hpp"
/********************************************************************/
/* */
/* Static structure initialization. */
/* */
/* Static structure initialization sets the initial value for */
/* all static structures. */
/* */
/********************************************************************/
STATIC BARRIER Barrier;
STATIC LONG GlobalThreadID = 0;
STATIC THREAD Threads;
/********************************************************************/
/* */
/* Execute a heap test. */
/* */
/* Create a number of heaps and threads and run a test. */
/* */
/********************************************************************/
BOOLEAN TEST_HEAPS::ExecuteTestThreads
(
SBIT32 NumberOfHeaps,
SBIT32 NumberOfThreads,
SBIT32 *Time,
BOOLEAN ThreadSafe,
BOOLEAN Zero
)
{
AUTO SNATIVE Data[2] = { 0,0 };
//
// Create all the heaps.
//
if ( CreateHeaps( NumberOfHeaps,NumberOfThreads,ThreadSafe,Zero ) )
{
REGISTER SBIT32 Count;
//
// Setup the control information for
// all the threads.
//
Data[0] = NumberOfThreads;
Data[1] = ((SNATIVE) this);
GlobalThreadID = 0;
//
// Get the start time.
//
(*Time) = ((SBIT32) GetTickCount());
//
// Start all the threads.
//
for ( Count=0;Count < NumberOfThreads;Count ++ )
{
Threads.StartThread
(
((NEW_THREAD) ExecuteTestThread),
((VOID*) Data)
);
}
//
// Wait for all threads to complete.
//
(VOID) Threads.WaitForThreads();
//
// Get the end time.
//
(*Time) = (((SBIT32) GetTickCount()) - (*Time));
//
// Delete all the heaps.
//
DeleteHeaps();
return True;
}
return False;
}
/********************************************************************/
/* */
/* Execute a test thread. */
/* */
/* Execute a test thread on each heap as fast as possible. */
/* */
/********************************************************************/
VOID TEST_HEAPS::ExecuteTestThread( VOID *Parameter )
{
REGISTER SNATIVE *Data = ((SNATIVE*) Parameter);
TRY
{
REGISTER SBIT32 NumberOfThreads = ((SBIT32) Data[0]);
//
// Ensure the thread data looks sane.
//
if ( (NumberOfThreads >= 0) && (GlobalThreadID >= 0) )
{
AUTO VOID *Allocation[ MaxAddress ];
REGISTER SBIT32 Count;
REGISTER TEST_HEAPS *TestHeap = ((TEST_HEAPS*) Data[1]);
REGISTER SBIT32 Thread = (InterlockedIncrement( & GlobalThreadID )-1);
//
// Wait for all the threads to arrive.
//
Barrier.Synchronize( NumberOfThreads );
//
// Decrement the ID to be tidy.
//
InterlockedDecrement( & GlobalThreadID );
//
// Create a number of allocations.
//
for ( Count=0;Count < MaxAddress;Count ++ )
{
REGISTER SBIT32 Size = ((rand() % MaxSize) + 1);
TestHeap -> New( & Allocation[ Count ],Size,Thread );
}
//
// Generate a random allocation pattern.
//
for ( Count=0;Count < (MaxCommands - (MaxAddress*2));Count ++ )
{
REGISTER VOID **Address = & Allocation[ (rand() % MaxAddress) ];
REGISTER SBIT32 Size = ((rand() % MaxSize) + 1);
//
// We randomly insert a 'Resize' operation
// into the command stream.
//
if ( (rand() % ResizeRate) != 1 )
{
//
// We have picked an allocation to
// replace to delete the current
// pointer and create a new a new
// pointer.
//
TestHeap -> Delete( (*Address),Thread );
TestHeap -> New( Address,Size,Thread );
Count ++;
}
else
{ TestHeap -> Resize( Address,Size,Thread ); }
}
//
// Delete all outstanding of allocations.
//
for ( Count=(MaxAddress-1);Count >= 0;Count -- )
{ TestHeap -> Delete( Allocation[ Count ],Thread ); }
}
else
{ Failure( "Thread data is wrong" ); }
}
#ifdef DISABLE_STRUCTURED_EXCEPTIONS
catch ( FAULT &Message )
{
//
// Print the exception message and exit.
//
DebugPrint( "Exception caught: %s\n",(char*) Message );
exit(1);
}
catch ( ... )
{
//
// Print the exception message and exit.
//
DebugPrint( "Exception caught: (unknown)\n" );
exit(1);
}
#else
__except ( EXCEPTION_EXECUTE_HANDLER )
{
//
// Print the exception message and exit.
//
DebugPrint( "Structured exception caught: (unknown)\n" );
exit(1);
}
#endif
}
| true |
9ba7f10ffb972818f8b84dbd07d0ac0e3c1a21ea | C++ | LengdonB/Pipelined-AVL | /AVL OOP/Temp/LeafNode.cpp | UTF-8 | 642 | 3.03125 | 3 | [] | no_license | #include "LeafNode.h"
#include<iostream>
//initializes the instance of LeafNode
LeafNode::LeafNode()
{
parent = NULL;
}
LeafNode::LeafNode(IPipe * pipe)
{
parent = NULL;
nextFunction = pipe;
}
void LeafNode::executePipe(int value, Node * current)
{
nextFunction->start(value, current);
}
void LeafNode::setPipe(IPipe * pipe)
{
nextFunction = pipe;
}
void LeafNode::setLeft(Node * lft)
{
}
void LeafNode::setRight(Node * rt)
{
}
void LeafNode::setParent(Node * pa)
{
parent = pa;
}
Node * LeafNode::getLeft()
{
return nullptr;
}
Node * LeafNode::getRight()
{
return nullptr;
}
Node * LeafNode::getParent()
{
return parent;
}
| true |
de25e03ca91378a674a31210b77e737dc36dce50 | C++ | Junchi-Liang/AI_assignment1 | /demo_ui.h | UTF-8 | 1,776 | 3.0625 | 3 | [] | no_license | #ifndef DEMO_UI_H
#define DEMO_UI_H
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
namespace demo_ui_ns
{
int main_menu()
{
int input_num;
while (1)
{
printf("Please input your choice:\n1. Create new map\n2. Read map from file\n3. Execute A* (WA* etc)\n4. Save result in file\n5. Save map in file\n6. Exit\n\nEnter your choice(1-6): ");
scanf("%d", &input_num);
if (input_num >= 1 && input_num <= 6)
break;
printf("please input a number from 1 to 6!\n\n");
}
return input_num;
}
int choose_algorithm()
{
int input_num;
while (1)
{
printf("Please input algorithm:\n1.Uniform Cost Search\n2.A*\n3.Weighted A*\n4.Sequential A*\n5.Integrated A*\n\nEnter your choice(1-5): ");
scanf("%d", &input_num);
if (input_num >= 1 && input_num <= 5)
break;
printf("please input a number from 1 to 5!\n\n");
}
return input_num;
}
int choose_heuristic()
{
int input_num;
while (1)
{
printf("Please input heurisric:\n0.h0\n1.h1\n2.h2\n3.h3\n4.h4\n5.h5\n\nEnter your choice(0-5): ");
scanf("%d", &input_num);
if (input_num >= 0 && input_num <= 5)
break;
printf("please input a number from 0 to 5!\n\n");
}
return input_num;
}
void setting_for_seq_integ(double &w1, double &w2, int &n_heuristic, int &admissible, std::vector<int> &list_heuristic)
{
int i, j;
printf("w1: ");
scanf("%lf", &w1);
printf("w2: ");
scanf("%lf", &w2);
printf("number of heuristic functions(except h0): ");
scanf("%d", &n_heuristic);
printf("admissible heuristic function: ");
scanf("%d", &admissible);
list_heuristic.clear();
for (i = 1; i <= n_heuristic; i++)
{
printf("heuristic function%d: ", i);
scanf("%d", &j);
list_heuristic.push_back(j);
}
}
}
#endif
| true |
6b3b83cb3c47bf0163db54940756c604daec9196 | C++ | HarryLong/CubeInSpace | /gl_core/camera.h | UTF-8 | 2,910 | 3.015625 | 3 | [] | no_license | #ifndef CAMERA_H
#define CAMERA_H
#include "glm_wrapper.h"
#include <QObject>
class QTimer;
class Camera : public QObject{
Q_OBJECT
public:
enum Direction {
UP, DOWN, LEFT, RIGHT, FORWARD, BACK
};
enum Type {
ORTHO, FREE
};
Camera();
~Camera();
void reset();
//Given a specific moving direction, the camera will be moved in the appropriate direction
//For a spherical camera this will be around the look_at point
//For a free camera a delta will be computed for the direction of movement.
void move(Camera::Direction dir);
void move(Direction dir, float amount);
//Change the yaw and pitch of the camera based on the 2d movement of the mouse
void rotate(float x, float y);
//Setting Functions
//Changes the camera mode, only three valid modes, Ortho, Free, and Spherical
void setType(Type cam_mode);
//Set the position of the camera
void setPosition(glm::vec3 pos);
//Set's the look at point for the camera
void lookAt(glm::vec3 pos);
//Changes the Field of View (FOV) for the camera
void setFOV(double fov);
//Change the viewport location and size
void setAspect(double m_aspect);
//Change the clipping distance for the camera
void setClipping(double near_clip_distance, double far_clip_distance);
glm::vec3 getCameraDirection() const;
//Getting Functions
Camera::Type getType() const;
// void GetViewport(int &loc_x, int &loc_y, int &width, int &height);
void getTransforms(glm::mat4 & proj, glm::mat4 & view);
public slots:
void setTranslationSensitivity(float sensitivity);
void setRotationSensitivity(float sensitivity);
void increment_fov(double amount);
void update();
signals:
void cameraDirectionChanged(float camera_direction_x, float camera_directiony, float camera_direction_z);
private:
//This function updates the camera
//Depending on the current camera mode, the projection and viewport matricies are computed
//Then the position and location of the camera is updated
void init_connections();
//Change the pitch (up, down) for the free camera
void pitch(float radians);
//Change yaw (left, right) for the free camera
void yaw(float radians);
void emit_camera_direction_changed();
Camera::Type camera_type;
double m_aspect;
double m_fov;
double m_near_clip;
double m_far_clip;
float m_camera_yaw;
float m_camera_pitch;
glm::vec3 m_camera_position;
glm::vec3 m_camera_position_delta;
glm::vec3 m_camera_look_at;
glm::vec3 m_camera_direction;
glm::vec3 m_camera_up;
glm::mat4 m_proj;
glm::mat4 m_view;
glm::mat4 m_MVP;
float m_translation_sensitivity;
float m_rotation_sensitivity;
QTimer * m_timer;
static const float _MAX_TRANSLATION_SCALE;
static const float _MAX_ROTATION_SCALE;
};
#endif
| true |
df666085eaea4e2eaa97e7eaf229b2decc5d240e | C++ | dorimeer/computer-graphics2 | /src/main.cpp | UTF-8 | 4,007 | 2.96875 | 3 | [] | no_license | #include <chrono>
#include <cmath>
#include <fstream>
#include <iostream>
// #include <thread>
#include <vector>
#include <file_representation.h>
#include <point.h>
#include <tree.h>
// #include <triangle.h>
using namespace std::chrono;
int main(int argc, char *argv[])
{
if (argc != 3)
{
std::cerr << "wrong number of arguments\nCorrect format is:\n./ray_tracer --source=<path to your *.obj> "
"--output=<path to output image>\n";
return -1;
}
// get source and output file
std::string source;
std::string output;
for (int i = 1; i < argc; i++)
{
std::string_view arg(argv[i]);
if (arg.starts_with("--source")) source = arg.substr(9);
if (arg.starts_with("--output")) output = arg.substr(9);
}
if (source.empty() || output.empty())
{
std::cerr << "wrong arguments\nSource or output file is missing";
return -1;
}
auto start = high_resolution_clock::now();
// read file and insert in tree
tree tr;
std::ifstream fin(source);
std::string line;
std::vector<point> vertexes;
std::vector<point> vertexes_normals;
while (fin >> line)
{
// read every vertex
if (line == "v")
{
double x, y, z;
fin >> x >> y >> z;
vertexes.push_back({x, y, z});
}
if (line == "vn")
{
double x, y, z;
fin >> x >> y >> z;
vertexes_normals.push_back({x, y, z});
}
// read every triangle
if (line == "f")
{
size_t ver1, ver2, ver3;
size_t vn1, vn2, vn3;
fin >> ver1;
fin.ignore(2, '\\');
fin >> vn1;
fin.ignore(10, ' ');
fin >> ver2;
fin.ignore(2, '\\');
fin >> vn2;
fin.ignore(10, ' ');
fin >> ver3;
fin.ignore(2, '\\');
fin >> vn3;
fin.ignore(10, '\n');
triangle triangl = {{vertexes[ver1 - 1],
vertexes[ver2 - 1],
vertexes[ver3 - 1]},
{vertexes_normals[vn1-1],
vertexes_normals[vn2-1],
vertexes_normals[vn3-1]}};
tr.insert(triangl);
}
}
auto read_end = high_resolution_clock::now();
std::cout << "read and insert in tree took " << duration_cast<milliseconds>(read_end - start).count() << "ms\n";
const int64_t height = 500;
const int64_t width = 500;
std::vector<std::vector<color>> image(width, std::vector<color>(height, {0, 0, 0}));
const point light = {5, 5, 5};
const point camera = {10, 10, 0};
double h_pov = 0.6;
double v_pov = 0.6;
// calculate every pixel value
for (int64_t i = 0; i < width; i++)
for (int64_t j = 0; j < height; j++)
{
// here we think that out object is located in coordinate {0, 0, 0}
// and our camera is looking into square {-1, 0, -1}...{1, 0, 1}
point plane_point = {(2.0 * i - width) / width * h_pov, 0, (j * 2.0 - height) / height * v_pov};
double res = tr.intersect(camera, plane_point, light);
// if -2 than there is no intersection
// otherwise according to formula
if (res == -2) continue;
unsigned char color = (std::fabs(res) + 0.5) / 1.5 * 255;
image[i][j] = {color, color, color};
}
auto end = high_resolution_clock::now();
std::cout << "ray tracing itself took " << duration_cast<milliseconds>(end - read_end).count() << "ms\n";
save_to_file(image, output);
auto total_end = high_resolution_clock::now();
std::cout << "write to file took " << duration_cast<milliseconds>(total_end - end).count() << "ms\n";
std::cout << "the whole program took " << duration_cast<milliseconds>(total_end - start).count() << "ms\n";
} | true |
aa278fba835132010fa043b6a6c9d5699f09d9a9 | C++ | kushagraSahu/Coding | /a12q1.cpp | UTF-8 | 1,705 | 4.15625 | 4 | [] | no_license | //Reverse a stack using a stack.
#include<iostream>
using namespace std;
struct node{
node* next;
char data;
};
void printList(node *head){
while(head){
cout << head->data << "-->";
head = head->next;
}
cout << "Null" << endl;
return ;
}
void push_into_newstack(node* &head2,char value){
node *currentnode;
currentnode=new node;
currentnode->data=value;
currentnode->next=NULL;
if(head2==NULL){
head2=currentnode;
}
else{
currentnode->next=head2;
head2=currentnode;
}
return;
}
void push(node* &head){
node *currentnode;
char value;
cin >> value;
while(value!='$'){
currentnode=new node;
currentnode->data=value;
currentnode->next=NULL;
if(head==NULL){
head=currentnode;
}
else{
currentnode->next=head;
head=currentnode;
}
cin >> value;
}
}
void top(node* &head){
cout << head->data << endl;
return;
}
void pop(node* &head){
if(head==NULL){
cout << "Stack is empty!" << endl;
}
node* temp=head;
head=temp->next;
delete temp;
cout << "New Top : ";
top(head);
}
int main(){
node* head1=NULL;
cout << "Start pushing elements into stack1 till $ : ";
push(head1);
printList(head1);
node* head2=NULL;
char val;
while(head1!=NULL){
val=head1->data;
push_into_newstack(head2, val);
head1=head1->next;
}
delete head1;
cout << "Reversed stack : ";
printList(head2);
printList(head1);
return 0;
}
| true |
bfd4f290d029cc6ac884eb01b3cce16a5eb4bc6d | C++ | LingtaoKong/cppmetrics | /src/meter.h | UTF-8 | 1,957 | 2.75 | 3 | [] | no_license |
#ifndef METRICS_METER_H_
#define METRICS_METER_H_
#include "atomic.h"
#include <iostream>
#include <math.h>
namespace com
{
namespace xiaomi
{
namespace mfs
{
namespace metrics
{
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Class EWMA
//
// An exponentially weighted moving average
//
// @see <a href=http://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average" />
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static const int METER_TICK_INTERVAL_SEC = 5;
static const double M1_ALPHA = 1.0f - exp(-(double) METER_TICK_INTERVAL_SEC / 60 / 1.0f);
static const double M5_ALPHA = 1.0f - exp(-(double) METER_TICK_INTERVAL_SEC / 60 / 5.0f);
static const double M15_ALPHA = 1.0f - exp(-(double) METER_TICK_INTERVAL_SEC / 60 / 15.0f);
#define NANOS_PER_SECONDS 1000000000
class EWMA
{
public:
EWMA(double alpha, uint64_t interval);
virtual ~EWMA();
public:
void tick(MfsAtomic & counter);
void tick(uint64_t counter);
double get_rate();
private:
double m_rate;
double m_alpha;
uint64_t m_interval;
MfsAtomic m_inited;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Class Meter
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Meter
{
public:
Meter();
virtual ~Meter();
public:
void inc();
void inc(int value);
void reset();
uint64_t get_count();
double get_one_min_rate();
double get_five_min_rate();
double get_fifteen_min_rate();
void tick_if_necessary();
private:
MfsAtomic m_counter;
MfsAtomic m_counted;
MfsAtomic m_tick;
EWMA m_m1_rate;
EWMA m_m5_rate;
EWMA m_m15_rate;
};
}
}
}
}
#endif /* METRICS_METER_H_ */
| true |
b752feb7cd1ef4e7b522b2bc7b0b630e79db629b | C++ | lisaRen/cocos2dx | /Classes/EnemyAI.cpp | UTF-8 | 1,366 | 2.75 | 3 | [] | no_license | #include "EnemyAI.h"
EnemyAI::EnemyAI(EnemyType enemyType, Point heroPos):m_enemyType(enemyType),m_heroPos(heroPos)
{
}
EnemyAI::~EnemyAI()
{
}
Point EnemyAI::moveTo()
{
Size winSize = Director::getInstance()->getWinSize();
Point pos = m_heroPos;
switch (m_enemyType.type)
{
case 0:
pos.x = pos.x + CCRANDOM_0_1() * 10;
pos.y = pos.y + 50;
break;
case 1:
pos.x = pos.x + CCRANDOM_0_1() * 10;
pos.y = pos.y + 50;
break;
case 2:
pos.x = pos.x + CCRANDOM_0_1() * 10;
pos.y = pos.y + 50;
break;
case 3:
if (CCRANDOM_0_1() * 10 >= 5) {
pos.x = m_heroPos.x + CCRANDOM_0_1() * 50;
pos.y = winSize.height - 200 - CCRANDOM_0_1() * 100;
}
pos.x = 10 + CCRANDOM_0_1() * winSize.width - 10;
pos.y = winSize.height - 200;
break;
case 4:
if (CCRANDOM_0_1() * 10 >= 4) {
pos.x = m_heroPos.x + CCRANDOM_0_1() * 30;
pos.y = winSize.height - 150 - CCRANDOM_0_1() * 100;
}
pos.x = 10 + CCRANDOM_0_1() * winSize.width - 10;
pos.y = winSize.height - 150 + CCRANDOM_0_1() * 50;
break;
case 5:
if (CCRANDOM_0_1() * 10 >= 3) {
pos.x = m_heroPos.x + CCRANDOM_0_1() * 10;
pos.y = winSize.height - 100 + CCRANDOM_0_1() * 100;
}
pos.x = 10 + CCRANDOM_0_1() * winSize.width - 10;
pos.y = winSize.height - 100 + +CCRANDOM_0_1() * 100;
break;
default:
break;
}
return pos;
}
| true |
f8acc111e9d5ebd3874d579b5e7ed4687719c3d1 | C++ | ffauskanger/DAT154_Assignment-2 | /Assignment2/Assignment2.cpp | UTF-8 | 10,162 | 2.78125 | 3 | [] | no_license | // Assignment2.cpp : Defines the entry point for the application.
//
#include "framework.h"
#include "Assignment2.h"
#include "Draw.h"
#include <list>
#include "Car.h"
using namespace std;
#define MAX_LOADSTRING 100
// Global Variables:
HINSTANCE hInst; // current instance
WCHAR szTitle[MAX_LOADSTRING]; // The title bar text
WCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
int eastState = 0;
int southState = 2;
list <Car> northList;
list <Car> westList;
list <Car> eastList;
list <Car> southList;
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
// Initialize global strings
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadStringW(hInstance, IDC_ASSIGNMENT2, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_ASSIGNMENT2));
MSG msg;
// Main message loop:
while (GetMessage(&msg, nullptr, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ASSIGNMENT2));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_ASSIGNMENT2);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassExW(&wcex);
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hInst = hInstance; // Store instance handle in our global variable
HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
// States for traffic lights
bool state1[] = { true, false, false }; // red
bool state2[] = { true, true, false }; // red and yellow
bool state3[] = { false, false, true }; // green
bool state4[] = { false, true, false }; // yellow
bool** states;
states = new bool* [4];
states[0] = state1;
states[1] = state2;
states[2] = state3;
states[3] = state4;
int rpn = 0;
int rpw = 0;
int pw = 50;
int pn = 50;
// Size
RECT rect;
GetWindowRect(hWnd, &rect);
switch (message)
{
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
break;
case WM_CREATE:
SetTimer(hWnd, TIMER_TRAFFIC, 3000, (TIMERPROC)NULL);
SetTimer(hWnd, TIMER_RANDOM_SPAWN, 1000, (TIMERPROC)NULL);
SetTimer(hWnd, TIMER_CAR, 100, (TIMERPROC)NULL);
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
// Drawing instructions
// Roads
roads(hdc, rect);
// Traffic lights
// East + West
trafficlight(hdc, 750, 550, states[eastState]);
trafficlight(hdc, 1100, 230, states[eastState]);
// South + North
trafficlight(hdc, 750, 230, states[southState]);
trafficlight(hdc, 1100, 550, states[southState]);
// Cars
for (Car car : westList)
{
car.Draw(hdc);
}
for (Car car : eastList)
{
car.Draw(hdc);
}
for (Car car : northList)
{
car.Draw(hdc);
}
for (Car car : southList)
{
car.Draw(hdc);
}
EndPaint(hWnd, &ps);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_LBUTTONDOWN:
{
westList.push_back(*(new Car(true, false, 0, 500)));
eastList.push_back(*(new Car(true, true, 1600, 400)));
northList.push_back(*(new Car(false, false, 900, 0)));
southList.push_back(*(new Car(false, true, 980, 900)));
InvalidateRect(hWnd, NULL, true);
break;
// Part 2: Traffic light change state
//if (state == 0) state = 1; else if(state == 1) state = 2; else if(state == 2) state = 3; else state = 0;
//if (southState == 0) southState = 1; else if (southState == 1) southState = 2; else if (southState == 2) southState = 3; else southState = 0;
//InvalidateRect(hWnd, NULL, true);
}
case WM_RBUTTONDOWN:
{
break;
}
case WM_KEYDOWN:
{
switch (wParam)
{
case VK_LEFT:
pw -= 10;
break;
case VK_RIGHT:
pw += 10;
break;
case VK_UP:
pn += 10;
break;
case VK_DOWN:
pn -= 10;
break;
}
}
case WM_TIMER:
switch (wParam)
{
case TIMER_RANDOM_SPAWN:
{
rpn = rand() % 100;
rpw = rand() % 100;
if (rpn > pn)
{
northList.push_back(*(new Car(false, false, 900, 0)));
southList.push_back(*(new Car(false, true, 980, 900)));
}
if (rpw > pw)
{
westList.push_back(*(new Car(true, false, 0, 500)));
eastList.push_back(*(new Car(true, true, 1500, 400)));
}
InvalidateRect(hWnd, NULL, true);
break;
}
case TIMER_TRAFFIC:
{
// Setting states for traffic lights
if (eastState == 0) eastState = 1; else if (eastState == 1) eastState = 2; else if (eastState == 2) eastState = 3; else eastState = 0;
if (southState == 0) southState = 1; else if (southState == 1) southState = 2; else if (southState == 2) southState = 3; else southState = 0;
InvalidateRect(hWnd, NULL, true);
break;
}
case TIMER_CAR:
{
int lastWest = 50000;
for (Car& c : westList)
{
if ((eastState == 2 || (c.getX() < 800 || c.getX() > 801)) && c.getX() < (lastWest - 50))
{
c.Move();
}
lastWest = c.getX();
}
int lastEast = -50000;
for (Car& c : eastList)
{
if ((eastState == 2 || (c.getX() < 1100 || c.getX() > 1101) && c.getX() > lastEast + 50))
{
c.Move();
}
lastEast = c.getX();
}
int lastNorth = 50000;
for (Car& c : northList)
{
if ((southState == 2 || (c.getY() < 300 || c.getY() > 301) && c.getY() < lastNorth - 50))
{
c.Move();
}
lastNorth = c.getY();
}
int lastSouth = -50000;
for (Car& c : southList)
{
if ((southState == 2 || (c.getY() < 550 || c.getY() > 551) && c.getY() > lastSouth + 50))
{
c.Move();
}
lastSouth = c.getY();
}
InvalidateRect(hWnd, NULL, true);
break;
}
default: break;
}
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
| true |
0880e3c9707f7dea030352ebec35de131af94a54 | C++ | Emil88PL/Cpp | /open a file/main.cpp | UTF-8 | 1,546 | 3.8125 | 4 | [] | no_license | #include <iostream>
#include <fstream> //cooperation with files
#include <cstdlib> // for exit
using namespace std;
string firstname, lastname;
int phone;
int main()
{
string line;
int nr_line = 1;
fstream file;
file.open("data.txt", ios::in );
if (file.good() == false)
{
cout << "File dosn't exist!";
exit(0);
}
while (getline(file, line))
{
switch(nr_line)
{
case 1: firstname = line; break;
case 2: lastname = line; break;
case 3: phone = atoi(line.c_str()); break;
}
nr_line++;
}
file.close();
cout << firstname << endl;
cout << lastname << endl;
cout << phone << endl;
return 0;
}
// somehow working
/*
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
string imie, nazwisko;
int nr_tel;
int main()
{
string linia;
int nr_linii=1;
fstream plik;
plik.open("wizytowka.txt", ios::in);
if(plik.good()==false) cout<<"Nie mozna otworzyc pliku!";
while (getline(plik, linia))
{
switch (nr_linii)
{
case 1: imie=linia; break;
case 2: nazwisko=linia; break;
case 3: nr_tel=atoi(linia.c_str()); break;
}
nr_linii++;
}
plik.close();
cout<<"imie: "<<imie<<endl;
cout<<"nazwisko: "<<nazwisko<<endl;
cout<<"telefon: "<<nr_tel<<endl;
return 0;
}
*/
| true |
fa9db0e23d7812c2e83d96817e91dca110444496 | C++ | mstojcevich/threadmentor-docker | /projects/example/thread.cpp | UTF-8 | 352 | 3.015625 | 3 | [] | no_license | #include "thread.h"
#include <cstdio>
HelloThread::HelloThread(char *name) : name(name) {
ThreadName.seekp(0, ios::beg);
ThreadName << name << '\0';
}
void HelloThread::ThreadFunc() {
Thread::ThreadFunc();
char buf[256];
int written = sprintf(buf,
"Hello from thread %s!\n",
name);
write(STDOUT_FILENO, buf, written);
Thread::Exit();
}
| true |
378c644b7a7f85146dc694e0f2120dc9ccc51a0a | C++ | jhaberstro/joh-engine | /src/joh/graphics/Resource.hpp | UTF-8 | 1,783 | 2.6875 | 3 | [] | no_license | #ifndef JOH_GRAPHICS_RESOURCE_HPP
#define JOH_GRAPHICS_RESOURCE_HPP
#include "joh/graphics/GraphicsForwards.hpp"
#include "joh/graphics/ResourceDescription.hpp"
namespace joh
{
namespace graphics
{
class Resource
{
public:
Resource();
Resource(ResourceDescription const& description);
virtual ~Resource();
ResourceAccess::Enum GetAccess() const;
ResourceType::Enum GetType() const;
ResourceUsage::Enum GetUsage() const;
private:
uint8_t access_;
uint8_t type_;
uint8_t usage_;
};
inline Resource::Resource()
: access_(ResourceAccess::None),
type_(ResourceType::Unknown),
usage_(ResourceUsage::Default) {
}
inline Resource::Resource(ResourceDescription const& description)
: access_(static_cast< uint8_t >(description.GetAccess())),
type_(static_cast< uint8_t >(description.GetType())),
usage_(static_cast< uint8_t >(description.GetUsage())) {
}
inline Resource::~Resource() {
}
inline ResourceAccess::Enum Resource::GetAccess() const {
return static_cast< ResourceAccess::Enum >(access_);
}
inline ResourceType::Enum Resource::GetType() const {
return static_cast< ResourceType::Enum >(type_);
}
inline ResourceUsage::Enum Resource::GetUsage() const {
return static_cast< ResourceUsage::Enum >(usage_);
}
}
}
#endif // JOH_GRAPHICS_RESOURCE_HPP
| true |
a359249da869fc7550662fb3645015a1b72fb7ad | C++ | Zuldruck/indie_studio_2018 | /Src/Component/ParticleComponent/ParticleComponent.hpp | UTF-8 | 10,781 | 2.796875 | 3 | [] | no_license | /*
** EPITECH PROJECT, 2019
** tek2
** File description:
** ParticleComponent
*/
#ifndef PARTICLECOMPONENT_HPP_
#define PARTICLECOMPONENT_HPP_
#include "Component.hpp"
namespace ind {
class IObject;
/**
* @brief ParticleComponent is a Class which allows to create and manipulate a IParticleSystemSceneNode
*
*/
class ParticleComponent : public Component {
public:
/**
* @brief Construct a new ParticleComponent
*
* @param owner Object which own the component
* @param isActivated If the component is activate by default
*/
ParticleComponent(IObject *owner, bool isActivated = true);
/**
* @brief Destroy the ParticleComponent
*
*/
~ParticleComponent();
/**
* @brief Update the component
*
* @param delta Time since the last update
*/
void update(float delta);
/**
* @brief pause the particle component
*
*/
virtual void pause(void);
/**
* @brief Show the particles
*
*/
void activate(void) noexcept;
/**
* @brief Hide the particles
*
*/
void desactivate(void) noexcept;
/**
* @brief Create a box-haped emitter of particles
*
* @param box The box for the emitter
* @param direction Direction and speed of particle emission
* @param minParticlesPerSecond Minimal amount of particles emitted per second
* @param maxParticlesPerSecond Maximal amount of particles emitted per second
* @param minStartColor Minimal initial start color of a particle. The real color of every particle is calculated as random interpolation between minStartColor and maxStartColor
* @param maxStartColor Maximal initial start color of a particle. The real color of every particle is calculated as random interpolation between minStartColor and maxStartColor
* @param lifeTimeMin Minimal lifetime of a particle, in milliseconds
* @param lifeTimeMax Maximal lifetime of a particle, in milliseconds
* @param maxAngleDegrees Maximal angle in degrees, the emitting direction of the particle will differ from the original direction
* @param minStartSize Minimal initial start size of a particle. The real size of every particle is calculated as random interpolation between minStartSize and maxStartSize
* @param maxStartSize Maximal initial start size of a particle. The real size of every particle is calculated as random interpolation between minStartSize and maxStartSize
*/
void addBoxEmitter(
const irr::core::aabbox3df & box = irr::core::aabbox3df(-10, 28, -10, 10, 30, 10),
const irr::core::vector3df & direction = irr::core::vector3df(0.0f, 0.03f, 0.0f),
irr::u32 minParticlesPerSecond = 5,
irr::u32 maxParticlesPerSecond = 10,
const irr::video::SColor & minStartColor = irr::video::SColor(255, 0, 0, 0),
const irr::video::SColor & maxStartColor = irr::video::SColor(255, 255, 255, 255),
irr::u32 lifeTimeMin = 2000,
irr::u32 lifeTimeMax = 4000,
irr::s32 maxAngleDegrees = 0,
const irr::core::dimension2df & minStartSize = irr::core::dimension2df(5.0f, 5.0f),
const irr::core::dimension2df & maxStartSize = irr::core::dimension2df(5.0f, 5.0f)) noexcept;
/**
* @brief Create a ring-haped emitter of particles
*
* @param center Center of ring
* @param radius Distance of points from center, points will be rotated around the Y axis at a random 360 degrees and will then be shifted by the provided ringThickness values in each axis.
* @param ringThickness thickness of the ring or how wide the ring is
* @param direction Direction and speed of particle emission.
* @param minParticlesPerSecond Minimal amount of particles emitted per second.
* @param maxParticlesPerSecond Maximal amount of particles emitted per second.
* @param minStartColor Minimal initial start color of a particle. The real color of every particle is calculated as random interpolation between minStartColor and maxStartColor.
* @param maxStartColor Maximal initial start color of a particle. The real color of every particle is calculated as random interpolation between minStartColor and maxStartColor.
* @param lifeTimeMin Minimal lifetime of a particle, in milliseconds.
* @param lifeTimeMax Maximal lifetime of a particle, in milliseconds.
* @param maxAngleDegrees Maximal angle in degrees, the emitting direction of the particle will differ from the original direction.
* @param minStartSize Minimal initial start size of a particle. The real size of every particle is calculated as random interpolation between minStartSize and maxStartSize.
* @param maxStartSize Maximal initial start size of a particle. The real size of every particle is calculated as random interpolation between minStartSize and maxStartSize.
*/
void addRingEmitter(
const irr::core::vector3df & center,
irr::f32 radius,
irr::f32 ringThickness,
const irr::core::vector3df & direction = irr::core::vector3df(0.0f, 0.03f, 0.0f),
irr::u32 minParticlesPerSecond = 5,
irr::u32 maxParticlesPerSecond = 10,
const irr::video::SColor & minStartColor = irr::video::SColor(255, 0, 0, 0),
const irr::video::SColor & maxStartColor = irr::video::SColor(255, 255, 255, 255),
irr::u32 lifeTimeMin = 2000,
irr::u32 lifeTimeMax = 4000,
irr::s32 maxAngleDegrees = 0,
const irr::core::dimension2df & minStartSize = irr::core::dimension2df(5.0f, 5.0f),
const irr::core::dimension2df & maxStartSize = irr::core::dimension2df(5.0f, 5.0f)) noexcept;
/**
* @brief Add a gravity effect to particles
*
* @param gravity Direction and force of gravity
* @param timeForceLost Time in milli seconds when the force of the emitter is totally lost and the particle does not move any more. This is the time where gravity fully affects the particle
*/
void addGravityAffector(
const irr::core::vector3df & gravity = irr::core::vector3df(0.0f, -0.03f, 0.0f),
irr::u32 timeForceLost = 1000) noexcept;
/**
* @brief Add an attraction effect to particles
*
* @param point Point to attract particles to.
* @param speed Speed in units per second, to attract to the specified point.
* @param attract Whether the particles attract or detract from this point.
* @param affectX Whether or not this will affect the X position of the particle.
* @param affectY Whether or not this will affect the Y position of the particle.
* @param affectZ Whether or not this will affect the Z position of the particle.
*/
void addAttractionAffector(
const irr::core::vector3df & point,
irr::f32 speed = 1.0f,
bool attract = true,
bool affectX = true,
bool affectY = true,
bool affectZ = true) noexcept;
/**
* @brief Add a fade out effect to particles
*
* @param targetColor Color where to the color of the particle is changed
* @param timeNeededToFadeOut How much time in milli seconds should the affector need to change the color to the targetColor
*/
void addFadeOutAffector(
const irr::video::SColor & targetColor = irr::video::SColor(0, 0, 0, 0),
irr::u32 timeNeededToFadeOut = 1000) noexcept;
/**
* @brief Add the position offset to the current box position
*
* @return irr::core::aabbox3df Newly adapted box position
*/
irr::core::aabbox3df addPositionOffsetToBox(void) noexcept;
/**
* @brief Set the Callback Function of the particleSystem
*
* @param callbackFunction Callback Function of the particleSystem
*/
void setCallbackFunction(const std::function<irr::core::aabbox3df(void)> & callbackFunction) noexcept;
/**
* @brief Set a Position Offset to the particleSystem, in addition of the current owner's position
*
* @param positionOffset Position Offset of the particleSystem
*/
void setPositionOffset(irr::core::vector3df positionOffset) noexcept;
/**
* @brief Get the Position Offset of the particleSystem
*
* @return irr::core::vector3df Position Offset of the particleSystem
*/
irr::core::vector3df getPositionOffset(void) const noexcept;
/**
* @brief Get the particleSystem
*
* @return irr::scene::IParticleSystemSceneNode* particleSystem
*/
irr::scene::IParticleSystemSceneNode * getParticleSystem(void) const noexcept;
protected:
irr::scene::IParticleSystemSceneNode * _particleSystem;
std::function<irr::core::aabbox3df(void)> _callbackFunction;
irr::core::vector3df _positionOffset;
int _maxParticlesPerSecond;
};
}
#endif /* !PARTICLECOMPONENT_HPP_ */
| true |
629ee598a06137cd659bcd06fe303d40bbe7a7c5 | C++ | stephangerve/matrix-class | /LinearSystemSolver.cpp | UTF-8 | 1,521 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include "Matrix.h"
#include "Vector.h"
#include "LinearSystemSolver.h"
LinearSystemSolver::LinearSystemSolver(){
}
LinearSystemSolver::~LinearSystemSolver(){
}
Vector* LinearSystemSolver::naiveGaussian(Matrix* A, Vector* b){
int n = A->numColumns();
//Matrix* Ab = augment(A,b);
double entry = 0.0;
Vector* x = new Vector();
x = b;
for(int k = 1; k <= n - 1; k++){
for(int i = k + 1; i <= n; i++){
for(int j = k; j <= n; j++){
//entry = Ab->operator()(i,j) - (Ab->operator()(i,k)/Ab->operator()(k,k)) * Ab->operator()(k,j);
entry = A->operator()(i,j) - (A->operator()(i,k)/A->operator()(k,k)) * A->operator()(k,j);
//Ab->set(i,j,entry);
A->set(i,j,entry);
}
//entry = Ab->operator()(i,n+1) - (Ab->operator()(i,k)/Ab->operator()(k,k))*Ab->operator()(k,n+1);
entry = x->operator[](i - 1) - (A->operator()(i,k)/A->operator()(k,k))*b->operator[](k - 1);
//Ab->set(i,n+1,entry);
x->set(i - 1, entry);
A->printMatrix();
x->printVector();
std::cout << std::endl << std::endl;
}
}
return x;
}
Matrix* LinearSystemSolver::lowerTriangular(Matrix* A){
return NULL;
}
Matrix* LinearSystemSolver::upperTriangular(Matrix* A){
return NULL;
}
Matrix* LinearSystemSolver::augment(Matrix* A, Vector* b){
int m = A->numRows();
int n = A->numColumns();
Matrix* Ab = new Matrix(m,n + 1);
for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++){
Ab->set(i,j,A->operator()(i,j));
}
Ab->set(i,n+1,b->operator[](i-1));
}
return Ab;
}
| true |
92d4acd2bb396b18b083dd8230589ca1b82adbc2 | C++ | intel/riggingtools | /kp2rig/src/KpSolidObject.hpp | UTF-8 | 2,589 | 2.859375 | 3 | [
"MIT"
] | permissive | #ifndef KpSolidObject_hpp
#define KpSolidObject_hpp
#include <vector>
#include "Pose.hpp"
#include "RigPose.hpp"
class KpSolidObject : public Pose
{
public:
KpSolidObject() = default;
KpSolidObject( std::string kpType,
const std::map< KEYPOINT_TYPE, int > & kpLayout );
KpSolidObject( const KpSolidObject & rhs );
virtual ~KpSolidObject(){}
virtual Pose * Clone() const { return new KpSolidObject( *this ); }
virtual void Keypoint( std::array< double, 3 > value, int index );
virtual void Keypoint( std::array< double, 3 > value, KEYPOINT_TYPE type );
virtual const std::array< double, 3 > & Keypoint( KEYPOINT_TYPE type ) const;
virtual std::array< double, 3 > & Keypoint( KEYPOINT_TYPE type );
virtual bool HasKeypoint( KEYPOINT_TYPE type ) const;
virtual class RigPose & GenerateRig();
virtual void FromRigPose( const class RigPose & rigPose );
virtual void InputDataToArray( std::vector< double > & serializedList );
virtual size_t InputDataSize() const { return FRAME_DATA_SIZE; }
virtual const class RigPose & RigPose() const;
virtual class RigPose & RigPose();
virtual std::string Category() const { return "solidObject"; }
virtual bool ValidateRig() const;
virtual void CoordinateSystem( std::array< double, 3 > value );
virtual const std::array< double, 3 > & CoordinateSystem() const;
private:
std::array< double, 3 > _location;
class RigPose _rigPose;
bool _rigCreated = false;
const int FRAME_DATA_SIZE = 3;
std::array< double, 3 > _coordinateSystem;
};
inline const RigPose & KpSolidObject::RigPose() const
{
return _rigPose;
}
inline RigPose & KpSolidObject::RigPose()
{
return _rigPose;
}
inline void KpSolidObject::Keypoint( std::array< double, 3 > value, int index )
{
_location = value;
(void)index; // Avoids a compiler warning
}
inline void KpSolidObject::Keypoint( std::array< double, 3 > value, KEYPOINT_TYPE type )
{
_location = value;
(void)type; // Avoids a compiler warning
}
inline const std::array< double, 3 > & KpSolidObject::Keypoint( KEYPOINT_TYPE type ) const
{
return _location;
(void)type; // Avoids a compiler warning
}
inline std::array< double, 3 > & KpSolidObject::Keypoint( KEYPOINT_TYPE type )
{
return const_cast< std::array< double, 3 > &>(static_cast<const Pose &>(*this).Keypoint( type ) );
}
inline bool KpSolidObject::HasKeypoint( KEYPOINT_TYPE type ) const
{
return _kpLayout.count( type ) == 1;
}
inline const std::array< double, 3 > & KpSolidObject::CoordinateSystem() const
{
return _coordinateSystem;
}
#endif
| true |
0a59c0aee570d11939ed74bfe841a57412f1b094 | C++ | Maldela/Macrodyn-Qt | /Jobs/floathisto2d.cpp | UTF-8 | 5,290 | 2.75 | 3 | [] | no_license | ///////////////////////////////////////////////////////////////////////////////
//
// Module name: floathisto_2d.C
// Contents: member functions of the class floathisto_2d
//
// Author: Andreas Starke
// Last modified:
// By:
//
///////////////////////////////////////////////////////////////////////////////
#include "floathisto2d.h"
///////////////////////////////////////////////////////////////////////////////
//
// member function: floathisto_2d
// purpose: constructor
//
// author: Andreas Starke
// last modified:
//
///////////////////////////////////////////////////////////////////////////////
floathisto_2d::floathisto_2d ( qreal x_qMin, qreal x_max, int x_res,
qreal y_qMin, qreal y_max, int y_res ):
x(0,x_qMin,x_max,x_res),
y(0,y_qMin,y_max,y_res) {
hits = new double * [x_res];
for( int k=0; k<x_res; k++ ) {
hits[k] = new double[y_res];
}
reset();
};
///////////////////////////////////////////////////////////////////////////////
//
// member function: ~floathisto_2d
// purpose: destructor
//
// author: Andreas Starke
// last modified:
//
///////////////////////////////////////////////////////////////////////////////
floathisto_2d::~floathisto_2d (void) {
for( int k=0; k<get_x_res(); k++ ) {
delete [] hits[k];
}
delete [] hits;
};
///////////////////////////////////////////////////////////////////////////////
//
// member function: reset
// purpose: reset values of histogramm
//
// author: Andreas Starke
// last modified:
//
///////////////////////////////////////////////////////////////////////////////
void floathisto_2d::reset ( void ) {
for( int k=0; k<get_x_res(); k++ ) {
for( int l=0; l<get_y_res(); l++ ) {
hits[k][l]=0;
}
}
};
///////////////////////////////////////////////////////////////////////////////
//
// member function: inc
// purpose:
//
// author: Andreas Starke
// last modified:
//
///////////////////////////////////////////////////////////////////////////////
void floathisto_2d::set_to ( qreal x_val, qreal y_val, double value ) {
// if( x.is_in_range(x_val) && y.is_in_range(y_val) ) {
x.set_val(x_val);
y.set_val(y_val);
hits[x.get_dval()][y.get_dval()]=value;
// }
};
///////////////////////////////////////////////////////////////////////////////
//
// member function: operator()
// purpose: overload operator()
//
// author: Andreas Starke
// last modified:
//
///////////////////////////////////////////////////////////////////////////////
double floathisto_2d::operator () ( int x_cell, int y_cell ) const {
if( x.is_in_range(x_cell) && y.is_in_range(y_cell)) {
return hits[x_cell][y_cell];
} else {
return -1;
}
};
double floathisto_2d::operator () ( qreal x_value, qreal y_value ) {
if( x.is_in_range(x_value) && y.is_in_range(y_value)) {
x.set_val(x_value);
y.set_val(y_value);
return hits[x.get_dval()][y.get_dval()];
} else {
return -1;
}
};
///////////////////////////////////////////////////////////////////////////////
//
// member function: get_x_res
// purpose: return the set x resolution
//
// author: Andreas Starke
// last modified:
//
///////////////////////////////////////////////////////////////////////////////
int floathisto_2d::get_x_res ( void ) const {
return x.get_res() ;
};
///////////////////////////////////////////////////////////////////////////////
//
// member function: get_y_res
// purpose: return the set y resolution
//
// author: Andreas Starke
// last modified:
//
///////////////////////////////////////////////////////////////////////////////
int floathisto_2d::get_y_res ( void ) const {
return y.get_res() ;
};
///////////////////////////////////////////////////////////////////////////////
//
// member function: get_x_d_var
// purpose: return discretisation for x
//
// author: Andreas Starke
// last modified:
//
///////////////////////////////////////////////////////////////////////////////
void floathisto_2d::get_x_d_var ( d_var * to_get ) const {
(*to_get) = x;
};
///////////////////////////////////////////////////////////////////////////////
//
// member function: get_y_d_var
// purpose: return discretisation for y
//
// author: Andreas Starke
// last modified:
//
///////////////////////////////////////////////////////////////////////////////
void floathisto_2d::get_y_d_var ( d_var * to_get ) const {
(*to_get) = y;
};
///////////////////////////////////////////////////////////////////////////////
//
// member function: get_max_hits
// purpose:
//
// author: Andreas Starke
// last modified:
//
///////////////////////////////////////////////////////////////////////////////
double floathisto_2d::get_max ( void ) const {
int k,l;
double histqMax=0;
for( k=0; k<get_x_res(); k++) {
for( l=0; l<get_y_res(); l++) {
histqMax = qMax(histqMax,hits[k][l]);
}
}
return histqMax;
};
double floathisto_2d::get_qMin ( void ) const {
int k,l;
double histqMin=0;
for( k=0; k<get_x_res(); k++) {
for( l=0; l<get_y_res(); l++) {
histqMin = qMin(histqMin,hits[k][l]);
}
}
return histqMin;
};
// eof
| true |
ac7c4cd90c1c4512430177914790a7934a218c71 | C++ | Just4yk4a/LabWork | /OAIP/lab 10/Project 5.12/Source.cpp | UTF-8 | 1,087 | 3.53125 | 4 | [] | no_license | #include <iostream>
#include <ctime>
using namespace std;
void Random(int **array, int &size)
{
int a, b;
cout << "Enter interval: ";
cin >> a >> b;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
array[i][j] = a + rand() % (b - a);
}
}
}
void Print(int **array, int &size)
{
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
cout<<array[i][j]<<" ";
}
cout << endl;
}
}
int* suchPosition (int **array, int &size)
{
int *array1 = new int[size];
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (array[i][j] < 0 && array1[i] < 0) array1[i] = j+1;
}
}
return array1;
}
int main()
{
int size;
cout << "Enter size of array: ";
cin >> size;
int **array = new int*[size];
for (int i = 0; i < size; i++)
{
array[i] = new int[size];
}
Random(array, size);
Print(array, size);
int *array1 = new int[size];
array1 = suchPosition(array,size);
for (int i = 0; i < size; i++)
{
if (array[i]>=0)
cout<<array1[i] << " ";
else cout << " << " ";
}
system("pause");
return 0;
} | true |
9cee3a809bf00032d1f59e3e52e42f4a427cce23 | C++ | ghensto/Cpp | /AdvancedfileIO.cpp | UTF-8 | 1,182 | 4.15625 | 4 | [] | no_license | // This program will read a file and compare the numbers
// inside it
#include <iostream>
#include <fstream>
using namespace std;
int const SIZE = 12;
int main()
{
// Variables
fstream iFile;
int numbers;
int array[SIZE];
int highest;
int lowest;
int count = 0;
float sum = 0;
float ave;
iFile.open("C:\\temp\\numbers.txt");
// Verify if the file is open
if (!iFile)
cout << "Error\n";
else
{
// Read the numbers
while (iFile >> numbers)
{
array[count] = numbers;
sum += numbers;
count++;
}
// Find biggest number
highest = array[0];
for (int count = 0; count < SIZE; count++)
if (array[count] > highest)
highest = array[count];
cout << "The highest value is " << highest << endl;
// Find smallest number
lowest = array[0];
for (int count = 0; count < SIZE; count++)
if (array[count] < lowest)
lowest = array[count];
cout << "The lowest value is " << lowest << endl;
// Display the sum
cout << "The sum of the numbers is " << sum << endl;
// Find and display the average
ave = sum / SIZE;
cout << "The average of the numbers is " << ave << endl;
// Close the file
iFile.close();
}
return 0;
} | true |
7888542f1b7b525e1e17f19045db4d0b953bd79b | C++ | Neverous/team | /CODES/convexGraham.cpp | UTF-8 | 1,353 | 3.5 | 4 | [] | no_license | /* Otoczka wypukła algorytmem Grahama */
std::pair<int, int> ref;
inline static const long long int cross(const std::pair<int, int> &A, const std::pair<int, int> &B, const std::pair<int, int> &C);
inline static const bool specialSort(const std::pair<int, int> &A, const std::pair<int, int> &B);
inline static void convexHull(std::vector<std::pair<int, int> > point, std::vector<std::pair<int, int> > &convex);
inline static void convexHull(std::vector<std::pair<int, int> > point, std::vector<std::pair<int, int> > &convex)
{
ref = point[0];
for(int p = 0; p < points; ++ p)
if(point[p] < ref)
ref = point[p];
sort(point.begin(), point.end(), specialSort);
for(int p = 0; p < points; ++ p)
{
while(convex.size() > 1 && cross(convex[convex.size() - 2], convex.back(), point[p]) <= 0)
convex.pop_back();
convex.push_back(point[p]);
}
return;
}
inline static const bool specialSort(const std::pair<int, int> &A, const std::pair<int, int> &B)
{
long long int side = cross(ref, A, B);
if(side > 0)
return true;
if(side == 0)
return A < B;
return false;
}
inline static const long long int cross(const std::pair<int, int> &A, const std::pair<int, int> &B, const std::pair<int, int> &C)
{
return (long long int)(B.first - A.first) * (C.second - A.second) - (long long int)(B.second - A.second) * (C.first - A.first);
}
| true |
72b43bd754410c04972ad4d51511bbbb72435bbd | C++ | sdolard/fcgi_js_web_server | /fcgi_js_web_server_core/abstract_socket.h | UTF-8 | 2,301 | 2.609375 | 3 | [] | no_license | #ifndef ABSTRACTSOCKET_H
#define ABSTRACTSOCKET_H
#include <QSslSocket>
#include <QTimerEvent>
// Abstract socket
class AbstractSocketPrivate;
class AbstractSocket : public QSslSocket
{
Q_OBJECT
public:
// Server read mode
enum ReadMode {
rmStream = 0x00, // as stream > no end
rmLine = 0x01 // as line > end of line
};
AbstractSocket( QObject * parent = 0);
virtual ~AbstractSocket();
// Returns duration as milliseconds
// Default 30000 ms
qint64 expirationDelay() const;
AbstractSocket & setExpirationDelay(qint64 ms);
// Returns true if there is no activity on socket since more than expirationDelay()
bool isExpired() const;
// Returns a human readable version of ReadMode
static QString toString(ReadMode);
signals:
// Emit when socket is expired
void expired(int socketDescriptor);
// Emit when client has closed socket
void clientCloseConnection(int socketDescriptor);
protected:
// Private implementation
// Protected cos of inheritance
AbstractSocketPrivate * const d_ptr;
// Private constructor used in inheritance
AbstractSocket(AbstractSocketPrivate &dd, QObject *parent);
// ReadMode getter
virtual ReadMode readMode() const;
// ReadMode setter
virtual AbstractSocket & setReadMode(ReadMode);
// Basic log method.
// Write params and "this" pointer
virtual const AbstractSocket & log(const QString &) const;
// Used to manage socket expiration delay
virtual void timerEvent(QTimerEvent *);
private:
// dpointer functions
Q_DECLARE_PRIVATE(AbstractSocket);
// Not copiable
Q_DISABLE_COPY(AbstractSocket);
// Connect private signals
void connectPrivateSignals();
private slots:
// Those slots, emited by this, can not be manage in private implementation
void onBytesWritten(qint64 bytes);
void onReadyRead();
void onConnected();
void onDisconnected();
void onError(QAbstractSocket::SocketError socketError);
void onHostFound();
void onProxyAuthenticationRequired( const QNetworkProxy & , QAuthenticator * );
void onStateChanged( QAbstractSocket::SocketState socketState );
void onAboutToClose();
void onReadChannelFinished();
};
#endif // ABSTRACTSOCKET_H
| true |
96f599d91b55c13f633639f6f7c204108dc0953a | C++ | baijiasheng/muduotest | /include/EventLoop.h | UTF-8 | 1,999 | 2.890625 | 3 | [] | no_license | #pragma once
#include <vector>
#include <atomic>
#include <functional>
#include <memory>
#include <mutex>
#include "NonCopyable.h"
#include "TimeStamp.h"
#include "CurrentThread.hpp"
#include "Poller.h"
#include "Channel.h"
using namespace std;
using Functor = function<void()>; //一种函数封装
using ChannelList = vector<Channel *>;
/*
* 事件循环类,主要包含两大模块 channel poller(epoll的抽象)
*/
class EventLoop : NonCopyable
{
public:
EventLoop();
~EventLoop();
//开启事件循环
void loop();
//退出事件循环
void quit();
TimeStamp get_poll_returnTime() const { return poll_return_time_; }
//在当前loop中执行cb
void run_in_loop(Functor cb);
//把cb放入队列中,唤醒loop所在线程执行cb(pending_functor)
void queue_in_loop(Functor cb);
//唤醒loop所在线程
void wakeup();
//poller的方法
void update_channel(Channel *channel);
void remove_channel(Channel *channel);
bool has_channel(Channel *channel);
//判断eventloop对象是否在自己的线程中
bool is_in_loopThread() const { return threadId_ == Current_thread::tid(); }
private:
void handle_read(); //wake up
void do_pending_functors(); //执行回调
private:
atomic_bool looping_;
atomic_bool quit_;
const pid_t threadId_; //记录当前loop所在线程id
TimeStamp poll_return_time_; //poller返回的发生事件的时间点
unique_ptr<Poller> poller_;
int wakeup_fd; //当main loop获取一个新用户的channel,通过轮询算法,选择一个subloopp,通过该成员唤醒subloop,处理channel
unique_ptr<Channel> wakeup_channel_; //包装wakefd
ChannelList active_channels; //eventloop 所管理的所有channel
atomic_bool calling_pending_functors_; //标识当前loop是否有需要执行的回调操作
vector<Functor> pending_Functors_; //loop所执行的所有回调操作
}; | true |
1cc991695dbe369d64f5dd9a20ef1b6ce7578273 | C++ | krajeshshau/CPP | /bitwise.cpp | UTF-8 | 1,938 | 4.0625 | 4 | [] | no_license | #include <stdio.h>
#include<iostream>
using namespace std;
int main(void) {
int x = 19, y = 20;
cout<<(x << 1)<<endl; //Left shift i.e multiplication by 2 => 38
cout<<(x >> 1)<<endl; //Right shift i.e division by 2 => 9
(x & 1) ? cout<<"Odd"<<endl : cout<<"Even"<<endl; //To check Odd Even.
cout<<(x&y)<<endl; // Anding => 16
cout<<(x|y)<<endl; //ORing => 23
cout<<(x^y)<<endl; //The result of bitwise XOR operator is 1 if the corresponding bits of two operands are opposite.
cout<<(~x)<<endl; //It changes 1 to 0 and 0 to 1, Inverting every bit of a number/1’s complement.
cout<<(~x + 1)<<endl; //Two’s complement of the number: 2’s complement of a number is 1’s complement + 1.
//The Quickest way to swap two numbers:
x ^= y; y ^= x; x ^= y;
//How to set a bit at n’th position in the number ‘num’ :
{ int num = 10, pos = 2; //pos start from 0th bit
num = num | (1 << pos);
cout<<num<<endl;
}
//How to unset/clear a bit at n’th position in the number ‘num’
{ int num = 7, pos = 1;
num = num & (~(1 << pos));
cout<<num<<endl;
}
//Toggling a bit at nth position :
//Toggling means to turn bit ‘on'(1) if it was ‘off'(0) and to turn ‘off'(0) if it was ‘on'(1)
{ int num = 4, pos = 1;
num = num ^ (1 << pos);
cout<<num<<endl;
}
//Checking if bit at nth position is set or unset:
{ int num = 4, pos = 1;
bool flag = false;
flag = num & (1 << pos);
cout<<flag<<endl;
}
{
char ch = 'A';
ch = ch | ' '; //Upper case English alphabet to lower case
cout<<ch<<endl;
ch = ch & '_'; // Lower case English alphabet to upper case
cout<<ch<<endl;
}
{ //To count set bit
int count = 0;
int x = 10;
while (x)
{
x &= (x-1);
count++;
}
cout<<count<<endl;
}
return 0;
} | true |
f65d3b5e10462031faf3f16d9e22dc7f2dea3709 | C++ | Cem-Alagozlu/MyEngine | /Minigin/PhysicsManager.cpp | UTF-8 | 1,336 | 2.515625 | 3 | [] | no_license | #include "MiniginPCH.h"
#include "PhysicsManager.h"
namespace cem
{
PhysicsManager::PhysicsManager()
{
}
PhysicsManager::~PhysicsManager()
{
}
void PhysicsManager::AddComponent(std::shared_ptr<CollisionComponent> collisionComponent)
{
m_pCollisionComponents.push_back(collisionComponent);
}
void PhysicsManager::RemoveComponent(std::shared_ptr<CollisionComponent> collisionComponent)
{
auto it = std::find(m_pCollisionComponents.begin(), m_pCollisionComponents.end(), collisionComponent);
if (it != m_pCollisionComponents.end())
{
m_pCollisionComponents.erase(it);
}
}
void PhysicsManager::Update()
{
for (size_t i = 0; i < m_pCollisionComponents.size(); i++)
{
for (size_t j = 0; j < m_pCollisionComponents.size(); j++)
{
if (i == j)
{
continue;
}
if (m_pCollisionComponents[i]->GetCollisionType() == CollisionComponent::CollisionType::Static
&&
m_pCollisionComponents[j]->GetCollisionType() == CollisionComponent::CollisionType::Static
)
{
continue;
}
if (m_pCollisionComponents[i]->IsOverlapping(m_pCollisionComponents[j]))
{
for (CollisionComponent::CollisionCallBack compCall : m_pCollisionComponents[i]->GetCallBacks())
{
compCall(m_pCollisionComponents[i], m_pCollisionComponents[j]);
}
}
}
}
}
} | true |
39e8fe4463a4c3c742e3f263a13221a093e37fc3 | C++ | royeom/Algorithm | /SWEA/1251.cpp | UTF-8 | 2,109 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <queue>
#include <cstring>
#define MAX 1001
int island_num;
double E;
long long island[MAX][MAX];
long long parents[MAX];
long long find(long long first){
if(parents[first] == first)
return first;
else
return parents[first] = find(parents[first]);
}
bool Union(long long first, long long second){
long long parent_first = find(first);
long long parent_second = find(second);
if(parent_first == parent_second)
return true;
parents[parent_first] = parent_second;
return false;
}
int main(){
int test_case_num;
scanf("%d", &test_case_num);
for(int i=1; i <= test_case_num; ++i){
std::priority_queue<std::pair<long long, std::pair<long long, long long> > > pq;
memset(island, 0, MAX);
memset(parents, 0, MAX);
scanf("%d", &island_num);
std::vector<long long> x, y;
x.resize(island_num);
y.resize(island_num);
for(int j=0; j<island_num; ++j)
scanf("%lld", &x[j]);
for(int j=0; j<island_num; ++j)
scanf("%lld", &y[j]);
scanf("%lf", &E);
for(long long j=0; j<island_num; ++j)
parents[j] = j;
for(long long j=0; j<island_num; ++j){
for(long long k=j+1; k<island_num; ++k){
island[j][k] = (x[k]-x[j])*(x[k]-x[j]) + (y[k]-y[j])*(y[k]-y[j]);
island[k][j] = island[j][k];
pq.push(std::make_pair(-island[j][k], std::make_pair(j, k)));
}
}
double size = 0;
int count = 0;
while(!pq.empty()){
if(count == island_num-1)
break;
long long dist = -pq.top().first;
long long first = pq.top().second.first;
long long second = pq.top().second.second;
pq.pop();
bool isUnion = Union(first, second);
if(isUnion)
continue;
size += dist;
count++;
}
size = size * E;
printf("#%d %.0f\n", i, size);
}
} | true |
d23ca1ae813e0f895a225b18edb380e1ea752d92 | C++ | notdatboi/Matrices | /ShapeWrapper.hpp | UTF-8 | 635 | 2.640625 | 3 | [] | no_license | #ifndef SHAPE_WRAPPER_HPP
#define SHAPE_WRAPPER_HPP
#include"Matrix.hpp"
const int SCREEN_HEIGHT = 600;
const int SCREEN_WIDTH = 800;
class ShapeWrapper
{
private:
std::vector<sf::Vertex> vertices;
public:
ShapeWrapper(const double posX = 0, const double posY = 0);
std::vector<sf::Vertex>& getVertices();
void draw(sf::RenderTarget& target) const;
void transform(const Matrix& t);
void rotate(const double angle); // in radians
void scale(const double x, const double y);
void translate(const double x, const double y);
void applyPerspective(const double x, const double y);
};
#endif | true |
1b1979e76d5aea576fc4d463d38199111694982d | C++ | MrPickle311/QuickCurses | /tests/Core/TestingGoodies.hpp | UTF-8 | 2,262 | 3.765625 | 4 | [] | no_license | #pragma once
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
template<typename T>
std::vector<T> mergeVectors(const std::vector<T>& left_vector,const std::vector<T>& right_vector)
{
std::vector<T> new_values;
size_t const new_size {left_vector.size() + right_vector.size()};
new_values.resize(new_size);
auto ptr = std::copy(left_vector.begin(), left_vector.end(),new_values.begin());
std::copy(right_vector.begin(), right_vector.end(),ptr);
new_values.shrink_to_fit();
return new_values;
}
//make specializations to print various types
template<typename T>
struct Printer
{
void operator() (const T& element)
{
std::cout << element << " ";
}
};
template<>
struct Printer<std::vector<std::pair<int,std::string>>>
{
void operator() (const std::vector<std::pair<int,std::string>>& element)
{
for(auto& e: element)
std::cout << "( " << e.first << " , " << e.second << " ) ";
}
};
//predefined data generators
template <typename T>
class DataGenerator
{
public:
std::vector<T> generate(size_t count) const;
};
template<>
class DataGenerator<int>
{
public:
std::vector<int> generate(size_t count) const
{
std::vector<int> v;
v.resize(count);
for (size_t i = 0; i < count; ++i)
v.push_back(i);
return v;
}
};
template<>
class DataGenerator<std::string>
{
public:
std::vector<std::string> generate(size_t count) const
{
std::vector<std::string> v;
v.reserve(count);
for (size_t i = 0; i < count; ++i)
v.push_back("string data");
return v;
}
};
template<>
class DataGenerator<std::vector<std::pair<int,std::string>>>
{
public:
std::vector<std::vector<std::pair<int,std::string>>> generate(size_t count) const
{
std::vector<std::vector<std::pair<int,std::string>>> v;
v.reserve(count);
for (size_t i = 0; i < count; i++)
{
std::vector<std::pair<int,std::string>> v1;
v1.reserve(count / 4);
for (size_t i = 0; i < count / 4; i++)
v1.push_back(std::make_pair(4,std::to_string(i)));
v.push_back(v1);
}
return v;
}
}; | true |
d9f4c2cfabb6ca9e4529c30804cdf04f5303aab0 | C++ | alexmeier2828/project_1 | /source/view/squareView.cpp | UTF-8 | 555 | 2.578125 | 3 | [] | no_license | #include "squareView.hpp"
#include <SFML/Graphics.hpp>
#include <iostream>
using namespace project_1::view;
SquareView::SquareView(int x, int y){
this->p_x = x*10;
this->p_y = y*10;
this->frame = 1;
_animatedSprite = new AnimatedSprite(10, 10, 2, "/Users/alexmeier/Desktop/workspace/project_1/resources/tile-1.png");
_animatedSprite->setPosition(p_x, p_y);
}
void SquareView::Draw(sf::RenderWindow &window){
window.draw(*_animatedSprite);
if(random() * 1.0/RAND_MAX > 0.5){
_animatedSprite->Tick();
}
}
| true |
8f20ed8865d53c18cf2c0aed37e87767d7778e29 | C++ | carrot77/EasyWindows | /EasyWindows/Control.h | UTF-8 | 3,482 | 2.875 | 3 | [] | no_license | #pragma once
#include <Windows.h>
#include <string>
#include <functional>
#include <list>
#define DEEP_COPY_DECL(T) \
T(T&&) noexcept = default; \
inline Control *deep_move(Control&& c) noexcept override { \
return new T(std::move(dynamic_cast<T&>(c)));\
}
template <class ...Params>
class EventHandler {
std::list<std::function<void(Params...)>> registrations;
public:
EventHandler() = default;
EventHandler(const EventHandler&) = delete;
EventHandler(EventHandler&&) noexcept = default;
EventHandler& operator =(const EventHandler&) = delete;
EventHandler& operator =(EventHandler&&) = default;
EventHandler& operator +=(std::function<void(Params...)> func) {
registrations.push_back(func);
return *this;
}
void clear() { registrations.clear(); }
EventHandler& operator -=(std::function<void(Params...)> func) {
registrations.remove(func);
return *this;
}
void Invoke(Params... args) {
for (const auto& func : registrations) {
func(args...);
}
}
};
template <class T>
class Observable {
T value;
public:
EventHandler<const T&, const T&> changed; // first the old, second the new value
operator T() const {
return value;
}
Observable<T>& operator =(const T& newValue) {
if (value != newValue) {
T tmp = value;
value = newValue;
changed.Invoke(tmp, value);
}
return *this;
}
};
template <class T, size_t K>
struct ObservableArray : std::array<T,K> {
EventHandler<const ObservableArray<T, K>&> changed;
const T& operator [](size_t ind) const {
return std::array<T, K>::operator [](ind);
}
ObservableArray& set(size_t ind, const T& val) {
if (val != std::array<T, K>::operator [](ind)) {
std::array<T, K>::operator [](ind) = val;
changed.Invoke(*this);
}
}
ObservableArray(const std::array<T,K> &base) : std::array<T,K>(base){}
};
class Control
{
static unsigned id_counter;
unsigned id;
SIZE last_known_size;
protected:
Control* parent;
Control();
Control(Control&&) noexcept;
Control(unsigned id);
std::wstring class_name;
uint32_t window_style;
EventHandler<Control*, HDC, PAINTSTRUCT&> paint;
virtual void create();
std::list<Control*> controls;
HWND hwnd;
std::wstring title;
int32_t x, y, width, height;
static Control* get_control_by_id(unsigned id);
virtual Control* deep_move(Control &&control) noexcept;
virtual void handle_size_changed(SIZE new_size);
const std::wstring& get_title() const;
virtual Control& set_title(const std::wstring&);
virtual void control_moved(Control *_old, Control *_new);
virtual void control_deleted(Control *_old);
public:
virtual ~Control();
enum Anchor {
Anchor_Top = 1,
Anchor_Left = Anchor_Top << 1,
Anchor_Bottom = Anchor_Left << 1,
Anchor_Right = Anchor_Bottom << 1,
Anchor_All = Anchor_Top | Anchor_Left | Anchor_Bottom | Anchor_Right
};
const unsigned& get_id() const;
const std::list<Control*> &get_controls() const;
RECT get_rectangle() const;
Control &set_rectangle(const RECT&);
SIZE get_size() const;
Control& set_size(const SIZE&);
POINT get_location() const;
Control& set_location(const POINT&);
const HWND& get_hwnd() const;
virtual Control& add_control(Control& control);
virtual Control& add_control(Control&& control);
virtual void remove_control(Control& control);
Control& set_anchor(Anchor);
Anchor get_anchor() const;
bool has_anchor(Anchor) const;
Control& add_anchor(Anchor);
Control& remove_anchor(Anchor);
EventHandler<Control*, SIZE &> size_changed;
private:
Anchor anchor;
};
| true |
0939457c0f7cfbf4dbcc3edd6a8ed2f7418b3910 | C++ | avinashvrm/Data-Structure-And-algorithm | /Dynamic Programming/Longest String Chain.cpp | UTF-8 | 886 | 2.734375 | 3 | [] | no_license | class Solution {
public:
int longestStrChain(vector<string>& words)
{
sort(words.begin(), words.end(), [](string a, string b) {
if(a.length() == b.length())
return a>b;
else
return a.length() < b.length();
});
unordered_map<string,int> mp;
mp[words[0]] = 1;
int res = 1;
for(int i = 1;i<words.size();i++)
{
mp[words[i]] = 1;
for(int j = 0;j<words[i].size();j++)
{
string s = words[i];
s.erase(s.begin()+j);
if(mp[s])
{
cout<<"here"<<" ";
mp[words[i]] = max(mp[words[i]],mp[s] + 1);
}
}
res = max(res,mp[words[i]]);
}
return res;
}
};
| true |
8789aaa9fb0a2143c20baf86ae93c518a54f4a71 | C++ | me1lopig/Recursividad | /sumaCifras/sumaCifras.cpp | UTF-8 | 1,126 | 3.84375 | 4 | [] | no_license | // sumaCifras.cpp
// comparacion entre rcursion e iteracion
// uma de las cifras de un numero entero
//
#include <iostream>
using namespace std;
int sumaRecursiva(long n)
{
if (n <= 9)
{
// caso base
return n;
}
else
{
// caso recursivo
return sumaRecursiva(n / 10) + n % 10;
}
}
int sumaIterativa(long n)
{
int suma = 0;
// caso iterativo
while (n%10 !=0) // condicion para detener el bucle
{
suma += (n % 10);
n /= 10;
}
return suma;
}
int main()
{
long numero;
cout << "Calculo de la suma de las cifras de un numero" << endl;;
cout << "Digita un numero entero : ";
cin >> numero;
cout << "Caso recursivo " << endl;
cout << "La suma de las cifras de " << numero << " es: " << sumaRecursiva(numero) << endl;
cout << endl;
cout << "Para el caso iterativo " << endl;
cout << "La suma de las cifras de " << numero << " es: " << sumaIterativa(numero) << endl;
cout << endl;
cout << "Pulsa una tecla para terminar " << endl;
cin.get();
return 0;
}
| true |
db1f47272ac384ff2125e8af4d08438d6c13bb8c | C++ | ali-alaei/RRT | /RRT algorithm/Navigator.h | UTF-8 | 951 | 2.515625 | 3 | [] | no_license | #ifndef NAVIGATOR_H
#define NAVIGATOR_H
#include <cmath>
#include "Nodes.h"
#include "Obstacles.h"
#include <iostream>
#include <vector>
#define baseSize 100
#define radius
class Navigator
{
Nodes* nearestNode;
Nodes* randomNode;
Nodes* newNode;
Nodes* startNode;
Nodes* destNode;
Nodes* flagNode;
std::vector <Nodes*> nodesList;
std::vector <Obstacles*> obstaclesList;
std::vector <Nodes*> pathList;
public:
Navigator(Nodes* start,Nodes* dest);
~Navigator();
bool checkIfNewNodeIsNearDestination(Nodes*,Nodes*,float);
void setDestFather();
void reverse(std::vector<Nodes*>&);
bool obstacleIsBetweenRandomAndNearestNodes(Obstacles*);
void getRandomState();
void getNearestNode();
void buildObstacles(int, std::vector<Obstacles*>&);
bool isValidExpansion();
bool isValidExpansion2();
bool goTowardsNode(int);
void addNode(std::vector<Nodes*>&);
bool isGoalReached();
private:
void nodesDistanceToRandNode();
};
#endif
| true |
da12ed36d0831b8796cd394a725af3a020b58f9a | C++ | williamkosasih19/bob | /source/prins.cpp | UTF-8 | 451 | 2.90625 | 3 | [] | no_license | /* prins.cpp *
* prints string */
#include "include/prins.h"
#include <iostream>
#include <string>
using namespace std;
extern bool fault;
prins::prins(string new_to_print, int new_mode)
{
to_print=new_to_print;
mode=new_mode;
}
void prins::run()
{
if(fault)
return;
switch(mode)
{
case 0:
cout<<to_print;
break;
case 1:
cout<<to_print<<endl;
break;
}
}
| true |
34e85ce242be1d4aa6b6a8ee1171c4f93a55bc9d | C++ | ChokMania/Old_CPP-Modules | /Old-CPP Module 01/ex03/Zombie.hpp | UTF-8 | 449 | 2.671875 | 3 | [] | no_license | #ifndef OLD_CPP_MODULES_ZOMBIE_HPP
# define OLD_CPP_MODULES_ZOMBIE_HPP
# include <iostream>
class Zombie
{
public:
Zombie(std::string name, std::string type = "default");
~Zombie(void);
Zombie(void);
void setType(std::string type);
void setName(std::string name);
std::string getType(void);
std::string getName(void);
void announce(void) const;
private:
std::string _type;
std::string _name;
};
#endif //OLD_CPP_MODULES_ZOMBIE_HPP
| true |
96996ac8c494ac990114b50e1e93e64a06f95ff3 | C++ | smacinnes/CGLab | /raytrace/Separated/imageplane.h | UTF-8 | 596 | 2.59375 | 3 | [] | no_license | #ifndef IMAGEPLANE_H
#define IMAGEPLANE_H
#include "OpenGP/Image/Image.h"
#include "camera.h"
using namespace OpenGP;
using Colour = Vec3;
// Class defining all properties of the image plane
class ImagePlane {
private:
int wResolution,hResolution; // default is 640x480
float viewingAngle,distToCam,hwRatio,halfWidth;
Vec3 center;
public:
Image<Colour> image;
Vec3 llc,pixRi,pixUp;
// constructor for wRes,hRes,viewingAngle and distToCam
ImagePlane(int,int,float,float);
void setup(const Camera&);
};
#endif // IMAGEPLANE_H
| true |
c4104f28f8f6d25f167769cda64ffd699b5caa0b | C++ | connormanning/arbiter | /arbiter/util/util.hpp | UTF-8 | 7,062 | 3.09375 | 3 | [
"MIT"
] | permissive | #pragma once
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <algorithm>
#ifndef ARBITER_IS_AMALGAMATION
#include <arbiter/util/exports.hpp>
#include <arbiter/util/types.hpp>
#endif
#ifdef ARBITER_CUSTOM_NAMESPACE
namespace ARBITER_CUSTOM_NAMESPACE
{
#endif
namespace arbiter
{
/** General utilities. */
ARBITER_DLL std::unique_ptr<std::string> findHeader(
const http::Headers& headers,
std::string key);
/** Returns @p path, less any trailing glob indicators (one or two
* asterisks) as well as any possible trailing slash.
*/
ARBITER_DLL std::string stripPostfixing(std::string path);
/** Returns the portion of @p fullPath following the last instance of the
* character `/`, if any instances exist aside from possibly the delimiter
* `://`. If there are no other instances of `/`, then @p fullPath itself
* will be returned.
*
* If @p fullPath ends with a trailing `/` or a glob indication (i.e. is a
* directory), these trailing characters will be stripped prior to the
* logic above, thus the innermost directory in the full path will be
* returned.
*/
ARBITER_DLL std::string getBasename(std::string fullPath);
/** Returns everything besides the basename, as determined by `getBasename`.
* For file paths, this corresponds to the directory path above the file.
* For directory paths, this corresponds to all directories above the
* innermost directory.
*/
ARBITER_DLL std::string getDirname(std::string fullPath);
/** @cond arbiter_internal */
ARBITER_DLL inline bool isSlash(char c) { return c == '/' || c == '\\'; }
/** Returns true if the last character is an asterisk. */
ARBITER_DLL inline bool isGlob(std::string path)
{
return path.size() && path.back() == '*';
}
/** Returns true if the last character is a slash or an asterisk. */
inline bool isDirectory(std::string path)
{
return (path.size() && isSlash(path.back())) || isGlob(path);
}
inline std::string joinImpl(bool first = false) { return std::string(); }
template <typename ...Paths>
inline std::string joinImpl(
bool first,
std::string current,
Paths&&... paths)
{
const bool currentIsDir(current.size() && isSlash(current.back()));
std::string next(joinImpl(false, std::forward<Paths>(paths)...));
// Strip slashes from the front of our remainder.
while (next.size() && isSlash(next.front())) next = next.substr(1);
if (first)
{
// If this is the first component, strip a single trailing slash if
// one exists - but do not strip a double trailing slash since we
// want to retain Windows paths like "C://".
if (
current.size() > 1 &&
isSlash(current.back()) &&
!isSlash(current.at(current.size() - 2)))
{
current.pop_back();
}
}
else
{
while (current.size() && isSlash(current.back()))
{
current.pop_back();
}
if (current.empty()) return next;
}
std::string sep;
if (next.size() && (current.empty() || !isSlash(current.back())))
{
// We are going to join current with a populated subpath, so make
// sure they are separated by a slash.
#ifdef ARBITER_WINDOWS
sep = "\\";
#else
sep = "/";
#endif
}
else if (next.empty() && currentIsDir)
{
// We are at the end of the chain, and the last component was a
// directory. Retain its trailing slash.
if (current.size() && !isSlash(current.back()))
{
#ifdef ARBITER_WINDOWS
sep = "\\";
#else
sep = "/";
#endif
}
}
return current + sep + next;
}
/** @endcond */
/** @brief Join one or more path components "intelligently".
*
* The result is the concatenation of @p path and any members of @p paths
* with exactly one slash preceding each non-empty portion of @p path or
* @p paths. Portions of @p paths will be stripped of leading slashes prior
* to processing, so portions containing only slashes are considered empty.
*
* If @p path contains a single trailing slash preceded by a non-slash
* character, then that slash will be stripped prior to processing.
*
* @code
* join("") // ""
* join("/") // "/"
* join("/var", "log", "arbiter.log") // "/var/log/arbiter.log"
* join("/var/", "log", "arbiter.log") // "/var/log/arbiter.log"
* join("", "var", "log", "arbiter.log") // "/var/log/arbiter.log"
* join("/", "/var", "log", "arbiter.log") // "/var/log/arbiter.log"
* join("", "/var", "log", "arbiter.log") // "/var/log/arbiter.log"
* join("~", "code", "", "test.cpp", "/") // "~/code/test.cpp"
* join("C:\\", "My Documents") // "C:/My Documents"
* join("s3://", "bucket", "object.txt") // "s3://bucket/object.txt"
* @endcode
*/
template <typename ...Paths>
inline std::string join(std::string path, Paths&&... paths)
{
return joinImpl(true, path, std::forward<Paths>(paths)...);
}
/** @brief Extract an environment variable, if it exists, independent of
* platform.
*/
ARBITER_DLL std::unique_ptr<std::string> env(const std::string& var);
/** @brief Split a string on a token. */
ARBITER_DLL std::vector<std::string> split(
const std::string& s,
char delimiter = '\n');
/** @brief Remove whitespace. */
ARBITER_DLL std::string stripWhitespace(const std::string& s);
namespace internal
{
template<typename T, typename... Args>
std::unique_ptr<T> makeUnique(Args&&... args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
template<typename T>
std::unique_ptr<T> clone(const T& t)
{
return makeUnique<T>(t);
}
template<typename T>
std::unique_ptr<T> maybeClone(const T* t)
{
if (t) return makeUnique<T>(*t);
else return std::unique_ptr<T>();
}
} // namespace internal
ARBITER_DLL uint64_t randomNumber();
/** If no delimiter of "://" is found, returns "file". Otherwise, returns
* the substring prior to but not including this delimiter.
*/
ARBITER_DLL std::string getProtocol(std::string path);
/** Strip the type and delimiter `://`, if they exist. */
ARBITER_DLL std::string stripProtocol(std::string path);
/** Get the characters following the final instance of '.', or an empty
* string if there are no '.' characters. */
ARBITER_DLL std::string getExtension(std::string path);
/** Strip the characters following (and including) the final instance of
* '.' if one exists, otherwise return the full path. */
ARBITER_DLL std::string stripExtension(std::string path);
/** Get the characters up to the last instance of "@" in the protocol, or an
* empty string if no "@" character exists. */
ARBITER_DLL std::string getProfile(std::string protocol);
/** Get the characters following the last instance of "@" in the protocol, or
* the original @p protocol if no profile exists.
*/
ARBITER_DLL std::string stripProfile(std::string protocol);
} // namespace arbiter
#ifdef ARBITER_CUSTOM_NAMESPACE
}
#endif
| true |
c6f3fb86ec30194f1fc9741f1006b1e72948df94 | C++ | SchlarmanUlster/COM326 | /Week3Lab1/Week3Lab1/Main.cpp | UTF-8 | 563 | 3.15625 | 3 | [] | no_license | //Week 3 Lab 1
//Author: Joe Schlarman
#include <iostream>
#include <string>
#include "Student.h"
using namespace std;
int main() {
//use default constructor
Student test{};
//use custom constructor
Student me{ "Billy Bragg", "B00578985", "Music theory", 3, 87, 92, 47 };
me.ToString();
//print module grade classifications
cout << me.calculateClassification(me.getModuleOneMark()) << endl;
cout << me.calculateClassification(me.getModuleTwoMark()) << endl;
cout << me.calculateClassification(me.getModuleThreeMark()) << endl;
system("pause");
return 0;
} | true |
50551d7ec1318a6cfd4c59404da17e37c76df994 | C++ | liat92/TetrisGame | /Tetris/Header Files/StatusGame.h | UTF-8 | 1,090 | 2.765625 | 3 | [] | no_license | #ifndef __STATUS_GAME_H
#define __STATUS_GAME_H
#include <iostream>
using namespace std;
#include "Gotoxy.h"
#include <fstream>
class StatusGame
{
//Class attributes:
public:
enum eScore {HARD_DROP = 2,BOMB_EXPLOSION = 50, SINGELE_LINE_CLEAR = 100, ADDITION_LINE = 200};
private:
int xStatusPositionCord;
int yStatusPositionCord;
int numFellBlocks;
int score;
//Class Methods:
public:
StatusGame(int numFellBlocks = 0, int score = 0, int xStatusPositionCord = 0, int yStatusPositionCord = 0);
StatusGame(const StatusGame& other) = delete;
StatusGame(ifstream& in);
//Getting function:
int getXStatusPositionCord()const;
int getYStatusPositionCord()const;
//Show functions:
void show()const;
void show(int& xCord, int& yCord)const;
//Update Score Function:
void clearLineUpdateScore(int numOfRemovedLines, bool isByJoker);
void hardDropUpdateScore(int distance);
void bombExplosionUpdateScore(int numOfSquareExplode);
//Others Function:
void save(ofstream &out) const;
void resetStatus();
void updateNumFellBlocks(int addition = 1);
};
#endif // __STATUS_GAME_H | true |
178a364db02d0d444dec6dbcdfc990a489c2dd09 | C++ | DerThorsten/zgraph | /include/zgraph/algorithm/zbfs.hpp | UTF-8 | 5,629 | 2.5625 | 3 | [
"MIT"
] | permissive | #pragma once
#ifndef ZGRAPH_ALGORITHM_ZBFS_HPP
#define ZGRAPH_ALGORITHM_ZBFS_HPP
#include <range/v3/view/filter.hpp>
#include <range/v3/functional/identity.hpp>
#include <range/v3/view/transform.hpp>
#include "zgraph/graph/zgraph_base.hpp"
#include <queue>
namespace zgraph
{
// template<
// class derived,
// class start_nodes_t,
// class pred_map_t,
// class node_discovery_callback_t,
// class adjacency_filter_t
// >
// void bfs(
// const zgraph_base<derived> & g,
// start_nodes_t && start_nodes,
// pred_map_t && pred_map,
// node_discovery_callback_t && discovery_callback,
// adjacency_filter_t && filter
// ){
// using graph_t = derived;
// using node_index_t = typename zgraph_base<derived>::node_index_t;
// using queue_t = std::queue<node_index_t>;
// using node_set_t = typename graph_t::node_set;
// // cast from crtp base to actual graph
// const auto & graph = g.derived_cast();
// // iterate over the adjacency and yield a triple: <from_node, to_node, edge>
// auto adjacency_uve = [&](const node_index_t u){
// return graph.out_adjacency(u) | ranges::view::transform([u](auto && kv){
// return std::make_tuple(u,kv.first, kv.second);
// });
// };
// // exclude nodes from search via lambda
// auto adjancey_filter = ranges::views::filter(filter);
// // node-set to store discovered nodes
// node_set_t discovered(graph);
// // filter function to to check if a node is *not* discovered
// auto not_discovered = ranges::view::filter([&](const auto & uve_tripple){
// return discovered.find(std::get<1>(uve_tripple)) == discovered.end();
// });
// // create queue and put start node(s) on queue
// queue_t queue;
// for(auto && start_node : start_nodes){
// queue.push(start_node);
// discovered.insert(start_node);
// if(!discovery_callback(start_node)){
// return;
// }
// pred_map[start_node] = start_node;
// }
// while(!queue.empty())
// {
// const auto node = queue.front();
// queue.pop();
// if(!discovery_callback(node)){
// break;
// }
// for(auto [u, v, e] : adjacency_uve(node) | not_discovered | adjancey_filter) {
// std::cout <<" v "<<v<<" via e "<< e <<"\n";
// discovered.insert(v);
// queue.push(v);
// pred_map[v] = u;
// }
// }
// }
// template<class derived>
// void bfs(
// const zgraph_base<derived> & g,
// const typename zgraph_base<derived>::node_index_t & start_node
// ){
// using node_index_t = typename zgraph_base<derived>::node_index_t;
// using pred_map_t = typename derived:: template node_map<node_index_t>;
// pred_map_t pred_map(g.derived_cast());
// bfs(g, std::array<node_index_t,1>{start_node},
// pred_map,
// [](auto && node ){return true;},
// [](auto && uve ){return true;}
// );
// }
template<
class graph_t,
class start_nodes_t,
class pred_map_t,
class node_discovery_callback_t,
class discovered_nodes_set_t,
class process_node_early_callback_t,
class process_node_late_callback_t
>
void sparse_bfs_impl(
const zgraph_base<graph_t> & base_g,
const start_nodes_t & start_nodes,
pred_map_t & pred_map,
discovered_nodes_set_t & discovered_nodes_set,
process_node_early_callback_t && process_node_early_callback,
process_node_late_callback_t && process_node_late_callback
){
using node_index_t = typename graph_t::node_index_t;
using queue_t = std::queue<node_index_t>;
using node_set_t = typename graph_t::node_set;
// get instance from crtp - base
const auto & g = base_g.derived_cast();
// filter function to to check if a node is *not* discovered
auto not_discovered = ranges::view::filter([&](const auto & uve_tripple){
return discovered_nodes_set.find(std::get<1>(uve_tripple)) == discovered_nodes_set.end();
});
// initialize from start nodes
queue_t queue;
for(auto && start_node : start_nodes){
queue.push(start_node);
discovered_nodes_set.insert(start_node);
pred_map[start_node] = start_node;
if(!node_discovery_callback(start_node)){
return;
}
}
auto exit = false;
while(!queue.empty() || !exit)
{
const auto node_u = queue.front();
queue.pop();
if(!process_node_early_callback(node_u)){
break;
}
for(auto [node_v, edge] : adjacency(node_u) | not_discovered ) {
discovered_nodes_set.insert(node_v);
pred_map[node_v] = node_u;
if(!node_discovery_callback(node_v)){
exit = true;
break;
}
queue.push(node_v);
}
if(!process_node_late_callback(node_u) || exit){
break;
}
}
}
} // end namespace zgraph
#endif // ZGRAPH_GRAPH_ZUGRAPH_BASE_HPP | true |
c36677811a7dd71e98ac9214a28aaae476ed0e62 | C++ | Qiyd81/shenlan | /camera_slam/slam14/lesson3/trajectory/draw_trajectory.cpp | UTF-8 | 4,750 | 2.8125 | 3 | [] | no_license | #include <sophus/se3.h>
#include <string>
#include <iostream>
#include <fstream>
// need pangolin for plotting trajectory
#include <pangolin/pangolin.h>
using namespace std;
// path to trajectory file
string trajectory_file = "./trajectory.txt";
// function for plotting trajectory, don't edit this code
// start point is red and end point is blue
void DrawTrajectory(vector<Sophus::SE3, Eigen::aligned_allocator<Sophus::SE3>>);
int main(int argc, char **argv) {
/* 实际上模板和函数一样,是可以有默认参数的,std::vector的声明是
template<
class T,
class Allocator = std::allocator<T>
> class vector;
有两个模板参数,T 是元素类型,而 Allocator 负责提供 vector 需要用到的动态内存。
其中 Allocator 参数有默认值,一般的使用不需要指定这个参数。但有时对内存有特殊需求,就需要提供自己定义的内存管理类。
把容器操作和内存管理分开,这是STL的一个亮点,你在设计容器时也可以学习*/
vector<Sophus::SE3, Eigen::aligned_allocator<Sophus::SE3>> poses;
/// implement pose reading code
// start your code here (5~10 lines)
ifstream file;
file.open(trajectory_file, ios::in);
if( !file )
{
cout << "Open file failure!" << endl;
file.close();
return -1;
}
for(int i=0; i < 620; i++)
{
double data[8];
for(auto &d :data )
file >> d;
Eigen::Quaterniond q( data[7], data[4], data[5], data[6] );
Eigen::Vector3d t(data[1], data[2], data[3] );
Sophus::SE3 T(q, t);
poses.push_back(T);
}
/* // if(file.fail())
if( !file.is_open() )
{
cout << "File lost" << endl;
file.close();
return -1;
}
else // File exist
{
while( !file.eof() )
{
string line;
double tmp, data[8];
int i = 0;
// istream& getline ( istream &is , string &str , char delim );
getline(file, line, '\n');
cout << line << endl;
istringstream line_string(line);
*//* while( line_string >> tmp )
{
data[i] = tmp;
cout << data[i] << " ";
i++;
}
cout << endl;
Eigen::Vector3d t(data[1], data[2], data[3]);
Eigen::Quaterniond q( data[7], data[4], data[5], data[6]);*//*
Eigen::Vector3d t;
Eigen::Quaterniond q;
double timestamp;
line_string >> timestamp >> t[0] >> t[1] >> t[2] >> q.x() >> q.y() >> q.z() >> q.w();
Sophus::SE3 T(q, t);
poses.push_back(T);
}
file.close();
}*/
// end your code here
// draw trajectory in pangolin
DrawTrajectory(poses);
return 0;
}
/*******************************************************************************************/
void DrawTrajectory(vector<Sophus::SE3, Eigen::aligned_allocator<Sophus::SE3>> poses) {
if (poses.empty()) {
cerr << "Trajectory is empty!" << endl;
return;
}
// create pangolin window and plot the trajectory
pangolin::CreateWindowAndBind("Trajectory Viewer", 1024, 768);
// 启动深度测试
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Define Projection and initial ModelView matrix
pangolin::OpenGlRenderState s_cam(
pangolin::ProjectionMatrix(1024, 768, 500, 500, 512, 389, 0.1, 1000),
//对应的是gluLookAt,摄像机位置,参考点位置,up vector(上向量)
pangolin::ModelViewLookAt(0, -0.1, -1.8, 0, 0, 0, 0.0, -1.0, 0.0)
);
pangolin::View &d_cam = pangolin::CreateDisplay()
.SetBounds(0.0, 1.0, pangolin::Attach::Pix(175), 1.0, -1024.0f / 768.0f)
.SetHandler(new pangolin::Handler3D(s_cam));
while (pangolin::ShouldQuit() == false) {
// Clear screen and activate view to render into
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
d_cam.Activate(s_cam);
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glLineWidth(2);
for (size_t i = 0; i < poses.size() - 1; i++) {
glColor3f(1 - (float) i / poses.size(), 0.0f, (float) i / poses.size());
glBegin(GL_LINES);
auto p1 = poses[i], p2 = poses[i + 1];
glVertex3d(p1.translation()[0], p1.translation()[1], p1.translation()[2]);
glVertex3d(p2.translation()[0], p2.translation()[1], p2.translation()[2]);
glEnd();
}
pangolin::FinishFrame();
usleep(5000); // sleep 5 ms
}
} | true |
4c44ed4a201d86dfa6b90500cbc0aff7d4bdb377 | C++ | wencanis/martian_revolutionary_war | /Mars_War/Base.h | UTF-8 | 3,862 | 2.9375 | 3 | [
"MIT"
] | permissive | #ifndef BASE_H_INCLUDED
#define BASE_H_INCLUDED
#include <list>
#include <cmath>
#include "Spaceship.h"
#include "Bullet.h"
#include "Global.h"
// A structure for the shields.
struct Shield
{
bool down; // Whether or not it's been destroyed.
float distance, hp; // Its distance from the side of the map and its hp.
};
bool EraseShipPred(const Spaceship&); // A predicate function for an STL template function.
class Base
{
public:
Base(int, float, float); // Constructor.
// Drawing functions.
void DrawBase() const;
void DrawShips() const;
void DrawBullets() const;
// Accessor Functions.
int GetResources() const { return resources; }
int GetShipsAvailable(int) const; // Depending on which ship the player's looking at.
int GetUpgrade(int) const; // Depending on which upgrade the player's looking at.
int GetUnfinalizedUpgrade(int) const; // Depending on which upgrade the player's looking at.
// More accessors.
bool ShieldDown(); /// Make sure this function is called in conjuction WITH periodic()
bool IsAlive() const { return hp > 0; }
// Even more accessors that are self-explanatory.
void EarnResources(int r) { resources += r; }
void MakePurchase(int); // Depending on which upgrade the player's looking at.
void UndoPurchase(int); // Depending on which upgrade the player's looking at.
void FinalizePurchase();
void GiveLoot(Base&);
void GatherInterest() { resources *= INTEREST_RATE; }
// Accessors...
std::list<Spaceship>& GetShips() { return ships; }
std::list<Bullet>& GetBullets() { return bullets; }
void Peace(Base&); // The peace initializer function (called at beginning of peace).
void NextLevel(); // The nextlevel initializer function.
void Periodic(std::list<Spaceship>&, std::list<Bullet>&); // The periodic function.
// Flagship controls.
void FlagshipMoveUp() { if (flagshipAlive) flagship_p->MoveUp(); }
void FlagshipMoveDown() { if (flagshipAlive) flagship_p->MoveDown(); }
void FlagshipMoveLeft() { if (flagshipAlive) flagship_p->MoveLeft(); }
void FlagshipMoveRight() { if (flagshipAlive) flagship_p->MoveRight(); }
void FlagshipFire();
private:
// Constants: self-explanatory.
static const int BASE_SPAWNING_CHANCES[5], UPGRADE_LIMIT = 20;
static const int INITIAL_RESOURCES = 1000, MIN_LOOT_PERCENTAGE = 15, MAX_LOOT_PERCENTAGE = 30, UPGRADE_COSTS[5], SHIP_KILL_BONUSES[5];
static const float SHIELD_1_HP = 750, SHIELD_2_HP = 1000, SHIELD_1_DISTANCE = 150, SHIELD_2_DISTANCE = 120, SHIELD_WIDTH = 20;
static const float INTEREST_RATE = 1.1, BASE_HP = 1500, BASE_DISTANCE = 50;
void SpawnFlagship(); // Spawn the flagship.
int side; // Which side the base is on.
float x, y, radius, hp; // The base's position, radius for the planet and shield, and hp.
// The first three are self-explanatory, the last two are arrays which store ships in stock and unfinalized upgrade purchases.
int resources, factoryLevel, flagshipLevel, shipsAvailable[5], unfinalizedPurchases[5];
Shield shield1, shield2; // Shields
std::list<Spaceship> ships; // The ships.
std::list<Bullet> bullets; // The bullets.
std::list<Spaceship>::iterator flagship_p; // A pointer that points to the flagship.
bool flagshipAlive, doNotSpawnFlagship; // Self-explanatory booleans for the flagship.
int resourcesForOtherBase; // The amount of bonus resources for the other base at the end of the level for ships destroyed.
// This function gets the base spawning chance for ships and gives its actual spawning chance depending on upgrade levels (It radically (sqrt), decreases as the level of upgrade increases).
int GetChanceFromLevelThroughBaseChance(int bc, int l) const { return -bc / 5 * std::sqrt(l) + bc; }
};
#endif // BASE_H_INCLUDED
| true |
a045b7c5d7fe619b16fe515512433ac543824309 | C++ | jfrancisco-neto/deimos | /include/Deimos/VBO.hpp | UTF-8 | 2,914 | 2.828125 | 3 | [] | no_license |
#ifndef DEIMOS_VBO_H_INCLUDED
#define DEIMOS_VBO_H_INCLUDED
#include <Phobos/BaseAPI.h>
#include <vector>
#include <iterator>
namespace deimos
{
enum VBODataType
{
SHORT,
INT,
FLOAT,
DOUBLE
};
enum VBOType
{
ARRAY,
INDEX //not supported yet
};
enum VBOTarget
{
STATIC,
DYNAMIC,
STREAM
};
enum VBODrawMode
{
TRIANGLE,
TRIANGLE_STRIP,
TRIANGLE_FAN,
LINE,
LINE_LOOP,
LINE_STRIP
};
struct VBOConfig
{
VBOConfig() :
size(0),
type(0),
stride(0),
pointer(0)
{
//empty
}
VBOConfig(int _size, int _type, int _stride, int _pointer) :
size(_size),
type(_type),
stride(_stride),
pointer(_pointer)
{}
int size,
type,
stride,
pointer; //TODO: need a better name
};
class PH_BASE_API VBO
{
public:
typedef std::vector<char> VBOData;
VBO();
VBO(const VBOData& data, int vboTarget,
const VBOConfig& vertexConfig,
const VBOConfig& colorConfig,
const VBOConfig& textureConfig,
bool freeClientData = false);
~VBO();
void create();
void destroy(); //destroy the buffer and free data from gpu side
void bind();
void unbind();
void free(); //free data from client side
void upload(const VBOData& data, int vboTarget);
void draw(int drawMode, int start = 0, int count = -1);
void configVertex(const VBOConfig& cfg);
void configTexture(const VBOConfig& cfg);
void configColor(const VBOConfig& cfg);
template <class T>
void upload(const std::vector<T>& vboData, int vboTarget)
{
m_data.resize(vboData.size() * sizeof(T));
const char *start = reinterpret_cast<const char*>(&vboData[0]),
*end = reinterpret_cast<const char*>(&vboData[vboData.size()])
+ sizeof(T);
std::copy(start, //first adress
end, //last adress. TODO: verify if this is the correct adress
std::back_inserter(m_data));
doUpload(vboTarget);
}
protected:
unsigned int getId()
{
return m_id;
}
private:
void doUpload(int vbotarget);
//non copyable
VBO(const VBO&);
unsigned int m_id; //id is always > 0
bool m_created;
VBOData m_data;
};
}
#endif | true |
d7703c4297210652141d343fc648209a1296762c | C++ | mitshan1994/Graph-Related | /main.cpp | UTF-8 | 565 | 3.046875 | 3 | [] | no_license | //#include <iostream>
//#include <vector>
//#include <utility>
//#include "graph.h"
//
//int main()
//{
// Graph<double> g;
// g.Print();
// //g.AddVertex(3.5);
// //g.AddVertex(4.5);
// //g.AddEdge(3.5, 4.5, 10);
// //g.Print();
// g.AddVertex({ 1, 2, 3 });
// g.Print();
// std::vector<std::pair<double, double>> vs = { {1, 2}, {1, 3} };
// std::vector<Graph<double>::Cost> costs = { 8.7, 9.6 };
// g.AddEdge(vs, costs);
// g.Print();
// std::cout << "Is connected : " << g.IsConnected() << std::endl;
//
// return 0;
//} | true |
f0cede5c4df8d038035ee67eb84e1ba8a969561b | C++ | Rahul-Bhargav/TestHarness | /TestUtilities/ITest.h | UTF-8 | 1,663 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
///////////////////////////////////////////////////////////////////////
// ITest.h - Provides the interface for writing the tests //
// ver 1.0 //
// Language: C++, Visual Studio 2017 //
// Application: Most Projects, CSE687 - Object Oriented Design //
// Author: Bhargav Rahul Surabhi, Syracuse University, //
// brsurabh@syr.edu //
///////////////////////////////////////////////////////////////////////
/*
* Package Operations:
* -------------------
* This package provides classes:
* - ITest Provides an interface for the user to implement a test and execute them using the test harness
*
* Required Files:
* ---------------
* IHostedResource.h
* Logger.h
*
* Maintenance History:
* --------------------
* ver 2.0 : 11 Oct 2018
* - refactored to a different file and namespace
* ver 1.0 : 3 Sep 2018
* - first release
*
* Planned Additions and Changes:
* ------------------------------
* - Maybe add a class that accepts a hosted resource
*/
#include "../HostedUtilities/IHostedResource.h"
#include "../LoggerUtilities/ILogger.h"
#include <string>
#include <memory>
namespace TestUtilities
{
using LogHostedResource = HostedUtilities::IHostedResource<const std::string&>;
using LoggerHostedResourcePtr = std::shared_ptr<LogHostedResource>;
class ITest
{
public:
virtual bool test() = 0;
virtual ~ITest() {};
virtual std::string getName() = 0;
virtual std::string getAuthor() = 0;
virtual void acceptHostedLogger(LoggerHostedResourcePtr hostedResource) = 0;
virtual LoggerHostedResourcePtr getHostedLogger() = 0;
};
}
| true |
1be5ecae6dc5284abbfb8bc0bbb168aa606f343a | C++ | ahvova/hinkaku | /dz1/main.cpp | UTF-8 | 3,633 | 3.25 | 3 | [] | no_license | #include<iostream>
#include<math.h>
#include<fstream>
double sina(double a=2.7,double b=3.1);
double function (double );
int numberofsteps(double,double,double);
int factorial (int);
int main() {
////////// ZADACHA1
double x;
double y;
std::cout<<" \n";
std::cout<<" \n";
std::cout<<" \n";
std::cout<<" \n";
std::cout<<" \n";
std::cout<<" \n";
std::cout<<"функция1 сумма синусов прямоугольного треугольника\n";
std::cout<<"Введите больший катет или 0 по умолчанию\n";
std::cin>>x;
std::cout<<"Введите меньший катет или 0 по умолчанию\n";
std::cin>>y;
if (x<0 || y<0) {
std::cerr<<"ОШИБКА!Катеты не могут принимать отрицательные значения\n";
// return 1;
}
if (x==0 ^ y==0) {
std::cerr<<"ОЩИБКА!Один из катетов не может быть равен нулю\n";
// return 3;
}
if (x==0 && y==0) {
std::cout<<"сумма синусов="<<sina()<<'\n';
}
if (x!=0 && y!=0) {
std::cout<<"сумма синусов="<<sina(x, y)<<'\n';
}
std::cout<<" \n";
std::cout<<" \n";
std::cout<<" \n";
std::cout<<" \n";
std::cout<<" \n";
std::cout<<" \n";
/////////// ZADACHA2
double Xstart;
double Xend;
double step;
int i;
std::ofstream out ("x_4+arctg(x)", std::ofstream::app);
out<<"x f(x)\n";
std::cout<<"Функция2 значения функции х^4+arctg(x) на отрезке с заданным шагом с выводом в файл\n";
std::cout<<"Введите начало отрезка\n";
std::cin>>Xstart;
std::cout<<"Введите конец отрезка\n";
std::cin>>Xend;
std::cout<<"Введите шаг\n";
std::cin>>step;
std::cout<<"Результат смотрите в файле \n";
std::cout<<" \n";
std::cout<<" \n";
std::cout<<" \n";
std::cout<<" \n";
std::cout<<" \n";
std::cout<<" \n";
i = numberofsteps(Xstart, Xend, step);
int n=0;
do {
out<<Xstart<<'\t'<<function(Xstart)<<'\n';
Xstart=Xstart + step;
n=n+1;
} while (n<=i);
out.close();
////////// ZADACHA3
int N;
std::cout<<"Функция3 двойной факториал числа\n";
std::cout<<"Введите натуральное число\n";
std::cin>>N;
std::cout<<"Двойной факториал введенного числа"<<factorial(N)<<'\n';
return 0;
}
| true |
19644657e1e97bea7a43ce88e834197fbd2133c1 | C++ | jsshao/straights2 | /View.h | UTF-8 | 1,796 | 2.75 | 3 | [] | no_license | #ifndef VIEW_H
#define VIEW_H
#include <gtkmm/window.h>
#include <gtkmm/box.h>
#include <gtkmm/image.h>
#include <gtkmm/table.h>
#include <gtkmm/button.h>
#include <gtkmm/entry.h>
#include <gtkmm/frame.h>
#include <vector>
#include "DeckGUI.h"
#include "Controller.h"
#include "Model.h"
class View : public Gtk::Window, public Observer {
public:
// Constructor
View(Controller *c, Model *m);
// Desctructor
virtual ~View();
// Update the view by quering info from the model
virtual void update();
// Behaviour when start game is clicked
virtual void startClicked();
// Behaviour when end game is clicked
virtual void endClicked();
// Behaviour when card is clicked
virtual void cardClicked(int which);
// Behaviour when switch from human/computer button is clicked
virtual void switchClicked(int which);
protected:
// Controller and model from MVC design pattern
Controller *controller_;
Model *model_;
// Cache the 52 cards
Gtk::Image* cards[52];
// Cards in the hand
Gtk::Image* hand_cards[13];
// The Deck manager handles the images for all cards
DeckGUI card_manager;
// Graphics for the table of cards
Gtk::Frame tableFrame;
Gtk::Table table;
// Graphics for the player's info: points/discards
Gtk::Frame playerFrame[4];
Gtk::VBox player[4];
Gtk::Label points[4];
Gtk::Label discards[4];
Gtk::HBox players;
// Switch button from AI/Human
Gtk::Button switchButton[4];
// Set the seed, start game button and end game button
Gtk::HBox header;
Gtk::Button start_;
Gtk::Button end_;
Gtk::Entry seed_;
// Display the cards in the hand
Gtk::Frame handFrame_;
Gtk::HBox hand_;
Gtk::Button handButtons_[13];
// VBox to contain the entire layout in the window
Gtk::VBox layout;
};
#endif
| true |
bdc63cc68bb24ac9397c823ae4d7796bb9933d45 | C++ | smallkirby/bdm-nekomanju | /main/mains/main_bluetooth.ino | UTF-8 | 355 | 2.75 | 3 | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | permissive | void setup() {
//11520bpsでポートを開く
Serial.begin(115200);
}
void loop() {
//シリアルポートに到着してるデータのバイト数が0より大きい場合
if (Serial.available() > 0) {
int input = Serial.read();
//受信確認でログ吐かせてみた
Serial.println(input);
Serial.println("hello");
}
}
| true |
b6df675e5297acf609b13f792ee3b04703a39233 | C++ | manohar2000/DSA_450 | /Arrays/Medianof2Arr.cpp | UTF-8 | 1,861 | 3.546875 | 4 | [] | no_license | /*
Given two sorted arrays nums1 and nums2 of size m and n respectively,
return the median of the two sorted arrays.
Example 1:
Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
Example 2:
Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
*/
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2)
{
if(nums2.size()<nums1.size()) return findMedianSortedArrays(nums2,nums1);
int start = 0;
int end = nums1.size();
while(start<=end)
{
int i1 = (start+end)/2;
int i2 = ( nums1.size() + nums2.size() + 1)/2 - i1;
int min1;
if(i1==nums1.size()) min1 = INT_MAX;
else min1 = nums1[i1];
int max1;
if(i1==0) max1 = INT_MIN;
else max1 = nums1[i1-1];
int min2;
if(i2==nums2.size()) min2 = INT_MAX;
else min2 = nums2[i2];
int max2;
if(i2==0) max2 = INT_MIN;
else max2 = nums2[i2-1];
// cout<<min1<<" "<<max1<<" "<<min2<<" "<<max2<<endl;
if(max1<=min2 && max2<=min1)
{
if( (nums1.size()+nums2.size())%2==0)
{
return (((double)(max(max1,max2) + min(min1,min2)))/2);
}
return ( (double)(max(max1,max2)) );
}
else if(max1>min2) end = i1-1;
else start = i1+1;
}
return 1;
}
};
| true |
931e6896efa74c054db1ca1aeab2b391a08ee129 | C++ | DCSR/SA200 | /FeatherM0/Device.h | UTF-8 | 432 | 2.828125 | 3 | [] | no_license |
/*
* Device.h - Library for timed devices such as pumps, LEDs and food hoppers
* Created by David Roberts, Mar 6, 2019
*/
#ifndef Device_h
#define Device_h
#include "Arduino.h"
class Device {
public:
Device(int num);
void switchOn();
void switchOff();
void switchOnFor(long duration);
void update();
private:
int _pin;
long _time;
long _duration;
boolean _timerOn = false;
};
#endif
| true |
7e857de38ddc758af70ca1ec3f9b00879883a949 | C++ | mxm001/UNLaM | /Programacion Basica I/clase 8/clase8-3.cpp | UTF-8 | 259 | 2.875 | 3 | [] | no_license | #include<stdio.h>
#include<conio.h>
main()
{
int num,mayor;
while(num!=99)
{
printf("\nIngrese un numero: ");
scanf("%d",&num);
if((num>mayor)&&(num!=99))
{
mayor=num;
}
}
printf("\nEl mayor numero es: %d",mayor);
getch();
return(1);
}
| true |
804116218355a9d3f99945335814962d89dff132 | C++ | deadzora/Zorlock | /Zorlock/src/Zorlock/Editor/Assets.cpp | UTF-8 | 1,917 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | #include "ZLpch.h"
#include "Assets.h"
#include <rpc.h>
namespace Zorlock
{
void Asset::GetUUID()
{
#ifdef ZL_PLATFORM_WINDOWS
UUID uuid;
RPC_STATUS s = UuidCreate(&uuid);
HRESULT hr = HRESULT_FROM_WIN32(s);
if (SUCCEEDED(hr))
{
RPC_STATUS ss = UuidToStringA(&uuid, (RPC_CSTR*)&m_uuid);
HRESULT hrr = HRESULT_FROM_WIN32(ss);
if (SUCCEEDED(hrr))
{
}
}
#endif
}
void Asset::SetUUID(std::string u)
{
#ifdef ZL_PLATFORM_WINDOWS
UUID uuid;
RPC_STATUS s = UuidFromStringA((RPC_CSTR)u.c_str(), &uuid);
HRESULT hr = HRESULT_FROM_WIN32(s);
if (SUCCEEDED(hr))
{
}
#endif
}
bool Asset::Deserialize(const rapidjson::Value& obj)
{
Name(obj["name"].GetString());
FilePath(obj["filepath"].GetString());
AssetUUID(obj["uuid"].GetString());
AssetType(obj["type"].GetString());
return true;
}
bool Asset::Serialize(rapidjson::Writer<rapidjson::StringBuffer>* writer) const
{
writer->StartObject();
writer->String("name");
writer->String(_name.c_str());
writer->String("filepath");
writer->String(_filepath.c_str());
writer->String("uuid");
writer->String(m_uuid.c_str());
writer->String("type");
writer->String(m_asset_type.c_str());
writer->EndObject();
return true;
}
AssetLibrary::AssetLibrary()
{
}
AssetLibrary::~AssetLibrary()
{
}
bool AssetLibrary::Deserialize(const std::string& s)
{
rapidjson::Document doc;
if (!InitDocument(s, doc))
return false;
if (!doc.IsArray())
return false;
for (rapidjson::Value::ConstValueIterator itr = doc.Begin(); itr != doc.End(); ++itr)
{
Asset a;
a.Deserialize(*itr);
m_assets.push_back(a);
}
return true;
}
bool AssetLibrary::Serialize(rapidjson::Writer<rapidjson::StringBuffer>* writer) const
{
writer->StartArray();
for (size_t i = 0; i < m_assets.size(); i++)
{
m_assets[i].Serialize(writer);
}
writer->EndArray();
return true;
}
}
| true |
c63cffca9d3b024e3597fc74f01de80c630daffc | C++ | arnonzilca/steganos | /src/file_permissions_covert_channel.cpp | UTF-8 | 2,650 | 3.296875 | 3 | [] | no_license | #include <sys/stat.h>
#include <stdlib.h>
#include <fstream>
#include "file_permissions_covert_channel.h"
#include "message_exception.h"
using namespace std;
const char FilePermissionsCovertChannel::FILE_NAME[] = "/tmp/innocent_file";
const int FilePermissionsCovertChannel::SYNC_BIT_POS = 0;
const int FilePermissionsCovertChannel::DATA_BIT_POS = 1;
const bool FilePermissionsCovertChannel::SYNC_BIT_WRITE_STATE = false;
FilePermissionsCovertChannel::FilePermissionsCovertChannel() {
//creating the file
ofstream outfile(FILE_NAME);
outfile << "These are not the files you're looking for..." << endl;
outfile.close();
}
void FilePermissionsCovertChannel::writeBit(bool bit) {
bool syncBit = readPermissionsBit(SYNC_BIT_POS); // reading the sync bit.
while (syncBit != SYNC_BIT_WRITE_STATE) { // checking if the sync marks 'write'.
syncBit = readPermissionsBit(SYNC_BIT_POS); // reading the sync bit again.
}
writePermissionsBit(bit, DATA_BIT_POS); // writing the data bit.
writePermissionsBit(!SYNC_BIT_WRITE_STATE, SYNC_BIT_POS); // setting the sync bit to 'read'.
}
bool FilePermissionsCovertChannel::readBit() {
bool syncBit = readPermissionsBit(SYNC_BIT_POS); // reading the sync bit.
while (syncBit == SYNC_BIT_WRITE_STATE) { // checking if the sync marks 'read'.
syncBit = readPermissionsBit(SYNC_BIT_POS); // reading the sync bit again.
}
bool readDataBit = readPermissionsBit(DATA_BIT_POS); // reading the data bit.
writePermissionsBit(SYNC_BIT_WRITE_STATE, SYNC_BIT_POS); // setting the sync bit to 'write'.
return readDataBit;
}
bool FilePermissionsCovertChannel::readPermissionsBit(int pos) const {
struct stat fileStat;
if (stat(FILE_NAME, &fileStat) < 0) { // getting the file's stats.
throw MessageException("<FilePermissionsCovertChannel::readPermissionsBit> Error reading file stat.");
}
return (fileStat.st_mode >> pos) & 1; // returning the bit at pos from the file's permissions.
}
void FilePermissionsCovertChannel::writePermissionsBit(bool bit, int pos) const {
struct stat fileStat;
if (stat(FILE_NAME, &fileStat) < 0) { // getting the file's stats.
throw MessageException("<FilePermissionsCovertChannel::writePermissionsBit> Error reading file stat.");
}
mode_t mode = fileStat.st_mode; // reading the file's current mode.
if (bit == true) {
mode |= 1 << pos; // setting the bit at pos to true
}
else {
mode &= ~(1 << pos); // setting the bit at pos to false
}
if (chmod(FILE_NAME, mode) < 0) { // changing the file's mode.
throw MessageException("<FilePermissionsCovertChannel::writePermissionsBit> Error writing chmod.");
}
}
| true |
12484101096c3cb6041d09ae019f8744b8e90e06 | C++ | Ayush32/Cpp-Data-Structures | /Linked List/inser_middle_list.cpp | UTF-8 | 572 | 3.59375 | 4 | [] | no_license | /*
* Copyright (c) 2020
* All rights reserved.
*/
#include <iostream>
using namespace std;
class node
{
public:
int data;
node *next;
node(int d)
{
data = d;
next = NULL;
}
};
void print(node *head)
{
while (head != NULL)
{
cout << head->data << " ->";
head = head->next;
}
}
int main()
{
node *head = NULL;
insertAThead(head, 3);
insertAThead(head, 2);
insertAThead(head, 1);
insertAThead(head, 0);
print(head);
return 0;
} | true |
92cf6acaa052192aafbf39c5ef24366a13f99de9 | C++ | aprilvkuo/leetcode | /leetcode/cpp/src/1024.cpp | UTF-8 | 817 | 3.140625 | 3 | [] | no_license | //
// Created by April Kuo on 2020/10/24.
//
/*
* https://leetcode-cn.com/problems/video-stitching/
* 1024. 视频拼接
* 1. 动态规划
* 2. 贪心
*/
class Solution {
public:
int videoStitching(vector<vector<int>>& clips, int T) {
vector<int> left_to_right(T+1, 0);
for (auto &item: clips) {
if (item[0] < T) {
left_to_right[item[0]] = max(item[1], left_to_right[item[0]]);
}
}
int pre = 0;
int next = 0;
int step = 0;
for (int i = 0; i < T; i++) {
next = max(left_to_right[i], next);
if (i == next) {
return -1;
}
if (pre == i) {
pre = next;
step ++;
}
}
return step;
}
}; | true |
13f151050057117e2aade403bd9633763faf3d69 | C++ | d0ctr/infotecs-cpp-task | /program2/connectionhost.cpp | UTF-8 | 1,506 | 3.0625 | 3 | [] | no_license | #include "connectionhost.hpp"
ConnectionHost::~ConnectionHost()
{
unlink(server_socket_name.sun_path);
close(server_socket);
close(client_socket);
}
std::string ConnectionHost::readFromSocket()
{
read_stream = fdopen(client_socket, "r");
std::string new_line("");
char c;
while((c = fgetc(read_stream)) != '_')
{
new_line += c;
}
return new_line;
}
void ConnectionHost::readyHostConnection()
{
try
{
if((server_socket = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
{
throw std::invalid_argument("Server socket descriptor can not be generated.");
}
server_socket_name.sun_family = AF_UNIX;
strcpy(server_socket_name.sun_path, NAME);
server_socket_name_size = sizeof(server_socket_name.sun_family) + strlen(server_socket_name.sun_path);
unlink(NAME);
if(bind(server_socket, (const sockaddr *)&server_socket_name, server_socket_name_size) < 0)
{
throw std::invalid_argument("Cannot bind socket with name.");
}
if(listen(server_socket, 5) < 0)
{
throw std::invalid_argument("Failure on seting que for connections.");
}
if((client_socket = accept(server_socket, &client_socket_name, &client_socket_name_size)) < 0)
{
throw std::invalid_argument("Client socket descriptor can not be generated.");
}
if(readFromSocket() != "start")
{
throw std::invalid_argument("Wrong connection start.");
}
}
catch(const std::exception_ptr &e)
{
std::rethrow_exception(e);
}
}
| true |
e053df53fad5186ea42aea59ee8b4d9eb23a2ca6 | C++ | hexu1985/cpp_book_code | /cpp.adts.data/Chap14/Figure14.3/Employee.h | UTF-8 | 2,360 | 4.03125 | 4 | [] | no_license | /* Employee.h --------------------------------------------------------------
Header file for a class Employee that encapsulates the attributes common
to all employees.
Operations are: A constructor and an output operation.
-----------------------------------------------------------------------*/
#include <iostream>
#ifndef EMPLOYEE
#define EMPLOYEE
class Employee
{
public:
Employee(long id = 0, string last = "", string first = "",
char initial = ' ', int dept = 0);
/*-----------------------------------------------------------------------
Employee constructor.
Preconditions: None.
Postconditions: myIdNum is initialized to id (default 0), myLastName
to last (default empty string), myFirstName to first (default
empty string), myMiddleInitial to initial (default blank char),
and myDeptCode to dept (default 0).
----------------------------------------------------------------------*/
void display(ostream & out) const;
/*-----------------------------------------------------------------------
Output function member.
Precondition: ostream out is open.
Postcondition: A text representation of this Employee object has
been output to out.
------------------------------------------------------------------------*/
// ... Other employee operations ...
private:
long myIdNum; // Employee's id number
string myLastName, // " last name
myFirstName; // " first name
char myMiddleInitial; // " middle initial
int myDeptCode; // " department code
// ... other attributes common to all employees
};
//--- Definition of Employee's Constructor
inline Employee::Employee(long id, string last, string first,
char initial, int dept)
{
myIdNum = id;
myLastName = last;
myFirstName = first;
myMiddleInitial = initial;
myDeptCode = dept;
}
//--- Definition of Employee's display()
inline void Employee::display(ostream & out) const
{
out << myIdNum << ' ' << myLastName << ", "
<< myFirstName << ' ' << myMiddleInitial << " "
<< myDeptCode << endl;
}
//--- Definition of output operator <<
inline ostream & operator<<(ostream & out, const Employee & emp)
{
emp.display(out);
return out;
};
#endif
| true |
004e41311e1d89f2889003fc1cccfb1ee3048cbe | C++ | codedazzlers/DSA-Bootcamps | /Arya Chakraborty/Strings/concatenate.cpp | UTF-8 | 587 | 3.03125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int length(string s)
{
int i = 0;
while (s[i])
{
i++;
}
return i;
}
int main()
{
char s[100], s1[100];
cin.getline(s, 100);
cin.getline(s1, 100);
int length1 = length(s), length2 = length(s1), addLen = length1 + length2;
char s2[addLen];
for (int i = 0; i < length1; i++)
{
s2[i] = s[i];
}
for (int i = length1; i < length1 + length2; i++)
{
s2[i] = s1[i - length1];
}
for (int i = 0; i < addLen; i++)
{
cout << s2[i];
}
return 0;
}
| true |
a02a049046f5267c0c77d3f65e317543360252db | C++ | telishev/sneakPic | /src/editor/base_handle.cpp | UTF-8 | 2,407 | 2.578125 | 3 | [] | no_license | #include "editor/base_handle.h"
#include <QTransform>
#include "renderer/anchor_handle_renderer.h"
#include "path/geom_helpers.h"
base_handle::base_handle ()
{
m_handle_type = handle_type::SQUARE;
m_renderer.set_visible (true);
}
base_handle::~base_handle ()
{
}
int base_handle::distance_to_mouse (QPoint screen_pos, QTransform transform) const
{
QPoint center = geom::nearest_point (transform.map (get_handle_center ()));
QRect element_rect = get_element_rect (transform);
if (element_rect.contains (screen_pos))
return 0;
return geom::distance (center, screen_pos);
}
void base_handle::set_mouse_hovered (bool hovered)
{
m_renderer.set_highlighted (hovered);
}
bool base_handle::start_drag (QPointF /*local_pos*/, QTransform /*transform*/)
{
return false;
}
bool base_handle::drag (QPointF /*local_pos*/, QTransform /*transform*/, keyboard_modifier /*modifier*/)
{
return false;
}
bool base_handle::end_drag (QPointF /*local_pos*/, QTransform /*transform*/, keyboard_modifier /*modifier*/)
{
return false;
}
void base_handle::draw (SkCanvas &canvas, const renderer_state &state, const renderer_config *config) const
{
if (!is_visible ())
return;
m_renderer.set_pos (get_handle_center ());
m_renderer.set_node_type (get_handle_type ());
m_renderer.set_anchor_size (get_handle_size ());
m_renderer.set_rotation (handle_rotation ());
m_renderer.draw (canvas, state, config);
}
handle_type base_handle::get_handle_type () const
{
return m_handle_type;
}
QRect base_handle::get_element_rect (QTransform transform) const
{
int mouse_size_px = m_renderer.get_anchor_size_px ();
QPoint center = geom::nearest_point (transform.map (get_handle_center ()));
QRect rect (0, 0, mouse_size_px, mouse_size_px);
rect.moveCenter (center);
return rect;
}
void base_handle::set_selected (bool selected)
{
m_renderer.set_is_selected (selected);
}
void base_handle::set_highlighted (bool highlighted)
{
m_renderer.set_highlighted (highlighted);
}
void base_handle::set_color (QColor color)
{
m_renderer.set_color (color);
}
void base_handle::set_selected_color (QColor color)
{
m_renderer.set_selected_color (color);
}
void base_handle::set_highlighted_color (QColor color)
{
m_renderer.set_highlighted_color (color);
}
float base_handle::handle_rotation () const
{
return 0.0f;
}
int base_handle::get_handle_size () const
{
return 7;
}
| true |
5ef5fd506c758bf452e21236bec63cb183c8471d | C++ | Kapurichino/AvoidStar-Refactoring- | /setting.cpp | UTF-8 | 914 | 2.65625 | 3 | [] | no_license | #include "header.h"
int Setting::need = 0;
int Setting::count = 0;
int Setting::avoid = 0;
int Setting::fallenStar = 0;
int Setting::remain = 0;
int Setting::level = 0;
int Setting::speed = 0;
int Setting::require()
{
need = 20 + getLevel() * 20;
return need;
}
void Setting::starUp()
{
count = 5 + getLevel() * LEVEL_COUNT;
}
int Setting::starCount()
{
return count;
}
void Setting::setRemain()
{
remain = require() - avoid;
}
int Setting::getRemain()
{
return remain;
}
void Setting::setAvoid()
{
++avoid;
}
int Setting::getAvoid()
{
return avoid;
}
void Setting::setFallenStar()
{
++fallenStar;
}
int Setting::getFallenStar()
{
return fallenStar;
}
int Setting::getLevel()
{
return level;
}
void Setting::setLevel()
{
++level;
}
void Setting::clear()
{
avoid = 0;
}
void Setting::setSpeed()
{
speed = 150 - getLevel() * LEVEL_SPEED;
}
int Setting::getSpeed()
{
return speed;
}
| true |
4d478b36c91fced544a640e7d27a7395c3481be0 | C++ | Avijit7102/LeetCode-Problem-Solving | /maxAreaOfIsland.cpp | UTF-8 | 1,297 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
void countGrid(vector<vector<int>> &grid, int x, int y, int r, int c, int &count)
{
if(x < 0 || x >= r || y < 0 || y >= c || grid[x][y] != 1)
{
return;
}
grid[x][y] = 2;
count++;
countGrid(grid, x+1, y, r, c, count);
countGrid(grid, x-1, y, r, c, count);
countGrid(grid, x, y+1, r, c, count);
countGrid(grid, x, y-1, r, c, count);
}
int main()
{
vector<vector<int>> grid = {
{0,0,1,0,0,0,0,1,0,0,0,0,0},
{0,0,0,0,0,0,0,1,1,1,0,0,0},
{0,1,1,0,1,0,0,0,0,0,0,0,0},
{0,1,0,0,1,1,0,0,1,0,1,0,0},
{0,1,0,0,1,1,0,0,1,1,1,0,0},
{0,0,0,0,0,0,0,0,0,0,1,0,0},
{0,0,0,0,0,0,0,1,1,1,0,0,0},
{0,0,0,0,0,0,0,1,1,0,0,0,0}
};
int row = grid.size();
int col = grid[0].size();
int count = 0, maxCount = 0;
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
{
if(grid[i][j] == 1)
{
countGrid(grid, i, j, row, col, count);
maxCount = max(count, maxCount);
count = 0;
}
}
}
cout << maxCount << endl;
}
| true |
01cbf400990ed274c1f4e0a9bbfe1b9175627aa8 | C++ | kjnh10/pcw | /work/atcoder/abc/abc027/A/dump.hpp | UTF-8 | 1,186 | 3.359375 | 3 | [] | no_license | // http://www.creativ.xyz/dump-cpp-652
using namespace std;
#include <iostream>
#include <bits/stdc++.h>
// デバッグ用変数ダンプ関数
void dump_func() {
}
template <class Head, class... Tail>
void dump_func(Head&& head, Tail&&... tail)
{
DUMPOUT << head;
if (sizeof...(Tail) == 0) {
DUMPOUT << " ";
}
else {
DUMPOUT << ", ";
}
dump_func(std::move(tail)...);
}
// vector出力
template<typename T>
ostream& operator << (ostream& os, const vector<T>& vec) {
os << "{";
for (int i = 0; i<sz(vec); i++) {
os << vec[i] << (i + 1 == sz(vec) ? "" : ", ");
}
os << "}";
return os;
}
// array出力
template<typename T, size_t SIZE>
ostream& operator << (ostream& os, T (&array)[SIZE]) {
os << '{';
for (int i = 0; i<SIZE; i++) {
os << array[i] << (i + 1 == SIZE ? "" : ", ");
}
os << '}';
return os;
}
// map出力
template<typename T, typename U>
ostream& operator << (ostream& os, const map<T, U>& ma) {
os << '{';
int cnt = 0;
for (auto x: ma){
cnt ++;
os << x.first << ": " << x.second << (cnt==sz(ma) ? "" : ", ");
}
os << '}';
return os;
}
| true |
bb3a2a4dab391a82fa1447f66f8f76a0af68ac12 | C++ | Wycers/Codelib | /Lydsy/P1617 [Usaco2008 Mar]River Crossing渡河问题/P1617.cpp | UTF-8 | 594 | 2.78125 | 3 | [
"MIT"
] | permissive | #include <cstdio>
#include <cstring>
#include <algorithm>
const int N = 2500 + 10;
using namespace std;
int n,s[N];
void Readin()
{
int temp;
scanf("%d%d",&n,&s[0]);
for (int i=1;i<=n;++i)
{
scanf("%d",&temp);
s[i] = s[i - 1] + temp;
}
}
int f[N];//f[i] - the cost of carrying i cows;
void Dp()
{
f[1] = s[1] + s[0];
for (int i=2;i<=n;++i)
{
f[i] = 0x7fffffff;
for (int k=0;k<i;++k)
f[i] = min(f[i],f[k] + s[i - k] + s[0]);
}
printf("%d\n",f[n] - s[0]);
}
int main()
{
Readin();
Dp();
return 0;
}
| true |
e98d8d99be601349143ac98378bd63cc0ffeb937 | C++ | rdieno/lostmines | /LostMines/LostMines/Game/UI/TextInputUI.cpp | UTF-8 | 2,594 | 2.921875 | 3 | [] | no_license | #include "TextInputUI.h"
#include "../../Engine/Game.h"
#include "../../Engine/Texture/TextureManager.h"
#include "../../Engine/AssetManager/AssetManager.h"
TextInputUI::TextInputUI() {}
TextInputUI::TextInputUI(std::string id, UILabels type, std::string fontName, SDL_Rect position, SDL_Color color, std::string placeholder) : labelColor(color), labelPosition(position), labelInitialPosition(position), text(placeholder){
labelFont = Game::assetManager.getFont(fontName);
createTexture();
//super call
UI::setID(id);
UI::setType(type);
UI::setSrc(SDL_Rect());
//UI(id, labelTexture, position, SDL_Rect());
}
TextInputUI::TextInputUI(std::string id, UILabels type, TTF_Font* ttfFont, SDL_Rect position, SDL_Color color, std::string placeholder) : labelColor(color), labelPosition(position), labelInitialPosition(position), labelFont(ttfFont), text(placeholder) {
createTexture();
//super call
UI::setID(id);
UI::setType(type);
UI::setSrc(SDL_Rect());
//UI(id, labelTexture, position, SDL_Rect());
}
TextInputUI::~TextInputUI() {}
void TextInputUI::setColor(Uint8 r, Uint8 g, Uint8 b, Uint8 h) {
labelColor = { r, g, b, h };
createTexture();
}
void TextInputUI::setColor(SDL_Color color) {
labelColor = color;
createTexture();
}
std::string TextInputUI::getText() {
return text;
}
void TextInputUI::changeText(std::string newText) {
text = newText;
TTF_SizeText(labelFont, text.c_str(), &labelPosition.w, &labelPosition.h);
createTexture();
//resetPosition();
}
void TextInputUI::resetPosition() {
labelPosition.x = (labelInitialPosition.x + (labelInitialPosition.w /2)) - (labelPosition.w / 2);
labelPosition.y = (labelInitialPosition.y + (labelInitialPosition.h / 2)) - (labelPosition.h / 2);
}
void TextInputUI::setTextSize(std::string font, std::string text, int *w, int *h) {
TTF_SizeText(Game::assetManager.getFont(font), text.c_str(), w, h);
std::cout << "FONT TEXT SIZE: W->" << w << " H->" << h << std::endl;
}
void TextInputUI::createTexture() {
SDL_Surface* surf = TTF_RenderText_Blended(labelFont, text.c_str(), labelColor);
labelTexture = SDL_CreateTextureFromSurface(Game::renderer, surf);
SDL_FreeSurface(surf);
SDL_QueryTexture(labelTexture, nullptr, nullptr, &labelPosition.w, &labelPosition.h);
//super call
UI::setTexture(labelTexture);
UI::setDest(labelPosition);
}
void TextInputUI::enableTextInput() {
std::cout << "Enabled Text" << std::endl;
inputEnabled = true;
SDL_StartTextInput();
}
void TextInputUI::disableTextInput() {
std::cout << "Disabled Text" << std::endl;
inputEnabled = false;
SDL_StopTextInput();
} | true |
5350ccdd05cdcb9267c063a023fdecadb7fc8b50 | C++ | CAgAG/DataStructure_CPP | /String/SeqString.cpp | UTF-8 | 3,538 | 3.171875 | 3 | [
"Apache-2.0"
] | permissive |
#include "SeqString.h"
void InitString(SeqString &Str) {
clear(Str);
Str->length = 0;
}
int StrLength(SeqString Str) {
int length = 0;
for (length = 0; Str->ch[length] != '\0'; length++) {}
return length;
}
void StrConcat(SeqString &Str1, SeqString Str2) {
for (int i = 0; i < Str2->length; ++i) {
Str1->ch[Str1->length++] = Str2->ch[i];
}
Str1->ch[Str1->length] = '\0';
}
bool StrCompare(SeqString S1, SeqString S2) {
int min_length = S1->length;
if (min_length != S2->length) {
return false;
}
for (int i = 0; i < min_length; ++i) {
if (S1->ch[i] != S2->ch[i]) {
return false;
}
}
return true;
}
bool SubString(SeqString &Sub, SeqString Str, int pos, int len) {
if ((pos + len) > Str->length) {
return false;
}
for (int i = pos, j = 0; i < pos + len; ++i, ++j) {
Sub->ch[j] = Str->ch[i];
}
Sub->length = len;
Sub->ch[len] = '\0';
return true;
}
void print_string(SeqString Str) {
printf("\n");
for (int i = 0; i < Str->length; ++i) {
printf("%c", Str->ch[i]);
}
printf("\n");
}
void clear(SeqString &S) {
S->length = 0;
memset(S->ch, '\0', sizeof(S->ch));
}
int Index(SeqString S1, SeqString S2) {
SeqString sub = (SeqString) malloc(sizeof(SString));
int i = 0, n = StrLength(S1), m = StrLength(S2);
while (i <= n - m + 1) {
clear(sub);
SubString(sub, S2, i, m - i);
if (StrCompare(sub, S2)) ++i;
else return i;
}
return 0;
}
int SimplePart(SeqString S, SeqString T) {
int i = 1, j = 1;
while (i < S->length && j < T->length) {
if (S->ch[i] == T->ch[j]) {
++i, ++j;
} else {
i = i - j + 2;
j = 1;
}
}
if (j > T->length) return i - T->length;
return 0;
}
void prefix_table(SeqString T, int prefix[]) {
// 第1个字符已知为0, 忽略
int len = 0;
prefix[0] = len;
// 从第二个字符开始比较
int i = 1;
while (i < T->length) {
// 下一位如果与当前位相等
if (T->ch[i] == T->ch[len]) {
len++;
prefix[i] = len;
i++;
} else {
if (len > 0) {
// 斜左下角的prefix
len = prefix[len - 1];
} else {
// 无法再后退
prefix[i] = 0;
i++;
}
}
}
}
// 向前移动一位, 第一位填充为-1 --> 仅为了后面KMP算法的实现
void move_prefix_table(int prefix[], int length) {
for (int i = length - 1; i > 0; --i) {
prefix[i] = prefix[i - 1];
}
prefix[0] = -1;
}
void KMP_search(SeqString text, SeqString pattern) {
int p_len = pattern->length;
int t_len = text->length;
int *prefix = (int *) malloc(sizeof(int) * p_len);
prefix_table(pattern, prefix);
move_prefix_table(prefix, p_len);
// i --> text
// j --> pattern
int i = 0, j = 0;
while (i <= t_len){
if (j == p_len){
// 全匹配
printf("found pattern at %d\n", i - p_len);
// 继续往后匹配, 根据实际要求也可以直接退出
j = prefix[j];
}
if (text->ch[i] == pattern->ch[j]){
i++, j++;
} else {
j = prefix[j];
// 第一位都不匹配, 已经无法后退
if (j == -1){
i++, j++;
}
}
}
} | true |
1f1c7168f0d4b87fe3602e2ec1116f493304572b | C++ | MoriartyShan/PythonModuleWithCpp | /src/class.cpp | GB18030 | 2,982 | 2.859375 | 3 | [] | no_license | #include <string>
#include <Eigen/Dense>
#include <Python.h>
#include <structmember.h>
#include <iostream>
#include <sstream>
typedef struct _EigenUtil{
PyObject_HEAD;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> a;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> b;
} EigenUtil;
static PyMemberDef DataMembers[] = {
///ṹݳԱ˵ .
//ݹٷĵ˵
//ҪҪһԪȫΪNULLݽṹβ
//滹һMethod Ҳ
{ "EigenUtil", T_OBJECT, offsetof(EigenUtil, b), 0, "some usage of eigen matrix" },
{ NULL, NULL, NULL, 0, NULL }
};
static int EigneUtil_init(EigenUtil* Self, PyObject* pArgs) //췽.
{
int size = -1;
if (!PyArg_ParseTuple(pArgs, "i", &size)) {
return -1;
}
Self->a.resize(size, size);
Self->b.resize(size, size);
Self->a.setRandom();
Self->b.setRandom();
std::cout << __FILE__ << ":" << __LINE__ << ": a= \n" << Self->a << std::endl;
std::cout << __FILE__ << ":" << __LINE__ << ": b= \n" << Self->b << std::endl;
return 0;
}
static void EigneUtil_deconstruct(EigenUtil* Self) //.
{
std::cout << __FILE__ << ":" << __LINE__ << ":" << "release\n";
Py_TYPE(Self)->tp_free((PyObject*)Self);
return;
}
static PyObject *PyMatrix_str(PyObject *self) {
std::stringstream ss;
ss << "a = \n" << ((EigenUtil*)self)->a << "\nb = \n" << ((EigenUtil*)self)->b;
return Py_BuildValue("s", ss.str().c_str());
}
PyObject *PyMatrix_size(EigenUtil *self) {
return Py_BuildValue("i", self->a.rows());
}
static PyGetSetDef MatrixGetSet[] = {
{"size", (getter)PyMatrix_size, nullptr, nullptr},
{nullptr} };
static PyModuleDef module = {
PyModuleDef_HEAD_INIT,
"module_class",
"Python interface for Matrix calculation",
-1,
NULL, NULL, NULL, NULL, NULL
};
static PyTypeObject EigenMatrixType = { 0 };
PyMODINIT_FUNC PyInit_module_class(void) //ģⲿΪ--PyVcam
{
PyObject* pReturn = 0;
EigenMatrixType.ob_base = { PyObject_HEAD_INIT(nullptr) 0 };
EigenMatrixType.tp_name = "module_class.matrix";
EigenMatrixType.tp_basicsize = sizeof(EigenUtil);
EigenMatrixType.tp_dealloc = (destructor)EigneUtil_deconstruct;
EigenMatrixType.tp_str = PyMatrix_str;
EigenMatrixType.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
EigenMatrixType.tp_new = PyType_GenericNew; //newú.
EigenMatrixType.tp_doc = "test eigen usage";
EigenMatrixType.tp_init = (initproc)EigneUtil_init;
EigenMatrixType.tp_version_tag = 1;
if (PyType_Ready(&EigenMatrixType) < 0)
return NULL;
pReturn = PyModule_Create(&module);
if (pReturn == NULL)
return NULL;
Py_INCREF(&EigenMatrixType);
PyModule_AddObject(pReturn, "module_class", (PyObject*)&EigenMatrixType); //뵽ģDictionary.
return pReturn;
} | true |
2fd7c25208d91221b8cd3e294c35da648e6e223d | C++ | TonyChouZJU/c---primer | /ex926.cpp | UTF-8 | 870 | 3.234375 | 3 | [] | no_license | /*
*copy dynamic array to vector and list
*erase odd elements in the list and
*erase even elements in the vector
*by zhoudaxia
*see c++ primer(5th)
*/
#include <vector>
#include <list>
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;
int main()
{
int ia[]={0,1,2,3,4,5,6,7,8,13,21,55,89};
vector<int> vi(begin(ia),end(ia));
list<int> li(begin(ia),end(ia));
for_each(vi.begin(),vi.end(),[](const int &s){cout << s << " ";});
cout << endl;
vector<int>::iterator vii=vi.begin();
list<int>::iterator lii=li.begin();
while(vii != vi.end())
if(*vii%2==0)
vii = vi.erase(vii);
else
++vii;
for_each(vi.begin(),vi.end(),[](const int &s){cout << s << " ";});
cout <<endl;
while(lii != li.end())
if(*lii%2==0)
++lii;
else
lii = li.erase(lii);
for_each(li.begin(),li.end(),[](const int &s){cout << s << " ";});
}
| true |
6e18390f31ab4ed499a2d1a08d37757b350e10d9 | C++ | masonicgryphon7/AuroraEngine | /Vector3.h | UTF-8 | 414 | 2.734375 | 3 | [] | no_license | #pragma once
#include <string>
#include <DirectXMath.h>
class Vector3
{
public:
Vector3() = default;
Vector3(float x_in, float y_in, float z_in);
Vector3(DirectX::XMVECTOR in);
Vector3 operator+ (const Vector3& vec3) const;
bool operator!= (const Vector3& vec3) const;
bool operator== (const Vector3& vec3) const;
DirectX::XMVECTOR asXMVECTOR();
const std::string toString() const;
float x, y, z;
};
| true |
ab387a8626925ae951e3e5f750c3f5c2f137b379 | C++ | i2070p/R-nd | /Operations/Condition.h | UTF-8 | 1,025 | 2.921875 | 3 | [] | no_license | #pragma once
#include "SimpleOperation.h"
#include <stack>
#include "../Elements/LiteralElement.h"
#include "../StackAdapter.h"
#include "Expression.h"
#include <sstream>
using namespace std;
class Condition : public SimpleOperation {
public:
Condition(Operation * parent) : SimpleOperation(parent) {
}
void addExpression(Expression* exp) {
this->exps.push(exp);
}
void addSign(SignElement* sign) {
this->sign = sign;
}
protected:
StackAdapter<Expression*> exps;
SignElement * sign;
void generate(SpimCodeContainer * spimCode) {
Expression * left = exps.pop();
Expression * right = exps.pop();
left->startGenerate(spimCode);
right->startGenerate(spimCode);
stringstream line;
line << this->sign->getCommand() << " " << left->getValueLiteral()->toString() << ", " << right->getValueLiteral()->toString() << ", label" << spimCode->nextLabel();
spimCode->addOperation(line.str());
}
};
| true |
38d7b86792aff4ba3a0a55944f0bd2bec7d1d7ac | C++ | zhuxb/C-ATTL3 | /C-ATTL3/neural_network/ResidualNeuralNetwork.hpp | UTF-8 | 5,387 | 2.75 | 3 | [
"MIT"
] | permissive | /*
* ResidualNeuralNetwork.hpp
*
* Created on: 25 Jul 2018
* Author: Viktor Csomor
*/
#ifndef C_ATTL3_NEURAL_NETWORK_RESIDUALNEURALNETWORK_H_
#define C_ATTL3_NEURAL_NETWORK_RESIDUALNEURALNETWORK_H_
#include <cassert>
#include <utility>
#include "neural_network/CompositeNeuralNetwork.hpp"
namespace cattle {
/**
* A class template for ResNets. These networks take vectors of neural networks as their
* sub-modules.
*
* \see https://arxiv.org/abs/1512.03385
*/
template<typename Scalar, std::size_t Rank>
class ResidualNeuralNetwork :
public CompositeNeuralNetwork<Scalar,Rank,false,NeuralNetwork<Scalar,Rank,false>> {
typedef NeuralNetwork<Scalar,Rank,false> Base;
typedef NeuralNetPtr<Scalar,Rank,false> Module;
typedef ResidualNeuralNetwork<Scalar,Rank> Self;
public:
/**
* @param modules A vector of residual modules.
* @param foremost Whether the network is to function as a foremost network.
*/
inline ResidualNeuralNetwork(std::vector<Module>&& modules, bool foremost = true) :
modules(std::move(modules)),
foremost(foremost) {
assert(this->modules.size() > 0 && "modules must contain at least 1 element");
Base& first_module = *this->modules[0];
input_dims = first_module.get_input_dims();
output_dims = this->modules[this->modules.size() - 1]->get_output_dims();
first_module.set_foremost(foremost);
typename Base::Dims prev_dims = input_dims;
for (std::size_t i = 0; i < this->modules.size(); ++i) {
Base& module = *this->modules[i];
if (i != 0)
module.set_foremost(false);
assert(module.get_input_dims() == module.get_output_dims() &&
"residual module input-output dimension discrepancy");
assert(prev_dims == module.get_input_dims() && "incompatible module dimensions");
prev_dims = module.get_output_dims();
}
}
/**
* @param module A single residual module.
* @param foremost Whether the network is to function as a foremost network.
*/
inline ResidualNeuralNetwork(Module&& module, bool foremost = true) :
ResidualNeuralNetwork(create_vector(std::move(module), foremost)) { }
inline ResidualNeuralNetwork(const Self& network) :
modules(network.modules.size()),
foremost(network.foremost),
input_dims(network.input_dims),
output_dims(network.output_dims) {
for (std::size_t i = 0; i < modules.size(); ++i)
modules[i] = Module(network.modules[i]->clone());
}
inline ResidualNeuralNetwork(Self&& network) {
swap(*this, network);
}
~ResidualNeuralNetwork() = default;
inline Self& operator=(Self network) {
swap(*this, network);
return *this;
}
inline Base* clone() const {
return new ResidualNeuralNetwork(*this);
}
inline const typename Base::Dims& get_input_dims() const {
return input_dims;
}
inline const typename Base::Dims& get_output_dims() const {
return output_dims;
}
inline std::vector<const Layer<Scalar,Rank>*> get_layers() const {
std::vector<const Layer<Scalar,Rank>*> layer_ptrs;
populate_layer_vector<const Layer<Scalar,Rank>*>(layer_ptrs);
return layer_ptrs;
}
inline std::vector<Layer<Scalar,Rank>*> get_layers() {
std::vector<Layer<Scalar,Rank>*> layer_ptrs;
populate_layer_vector<Layer<Scalar,Rank>*>(layer_ptrs);
return layer_ptrs;
}
inline std::vector<Base*> get_modules() {
std::vector<Base*> modules;
for (std::size_t i = 0; i < this->modules.size(); ++i)
modules.push_back(this->modules[i].get());
return modules;
}
inline bool is_foremost() const {
return foremost;
}
inline void set_foremost(bool foremost) {
modules[0]->set_foremost(foremost);
this->foremost = foremost;
}
inline void empty_caches() {
for (std::size_t i = 0; i < modules.size(); ++i)
modules[i]->empty_caches();
}
inline typename Base::Data propagate(typename Base::Data input, bool training) {
assert(input_dims == (Dimensions<std::size_t,Base::DATA_RANK>(input.dimensions()).template demote<>()));
for (std::size_t i = 0; i < modules.size(); ++i)
input += modules[i]->propagate(input, training);
return input;
}
inline typename Base::Data backpropagate(typename Base::Data out_grad) {
assert(output_dims == (Dimensions<std::size_t,Base::DATA_RANK>(out_grad.dimensions()).template demote<>()));
for (int i = modules.size() - 1; i >= 0; --i) {
if (foremost && i == 0)
return modules[i]->backpropagate(std::move(out_grad));
else
out_grad += modules[i]->backpropagate(out_grad);
}
return out_grad;
}
inline friend void swap(Self& network1, Self& network2) {
using std::swap;
swap(network1.modules, network2.modules);
swap(network1.foremost, network2.foremost);
swap(network1.input_dims, network2.input_dims);
swap(network1.output_dims, network2.output_dims);
}
private:
inline static std::vector<Module> create_vector(Module&& module) {
std::vector<Module> vec(1);
vec[0] = std::move(module);
return vec;
}
template<typename _LayerPtr>
inline void populate_layer_vector(std::vector<_LayerPtr>& layer_ptrs) const {
for (std::size_t i = 0; i < modules.size(); ++i) {
std::vector<Layer<Scalar,Rank>*> internal_layer_ptrs = modules[i]->get_layers();
for (std::size_t j = 0; j < internal_layer_ptrs.size(); ++j)
layer_ptrs.push_back(internal_layer_ptrs[j]);
}
}
std::vector<Module> modules;
bool foremost;
typename Base::Dims input_dims, output_dims;
};
} /* namespace cattle */
#endif /* C_ATTL3_NEURAL_NETWORK_RESIDUALNEURALNETWORK_H_ */
| true |
41ba9b968c5ca1fa6a4e0b4f69bb82d2261b98b4 | C++ | faerytea/Warlocks | /Settings.h | UTF-8 | 1,008 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <map>
class Settings {
private:
std::map<std::string, std::string> settingsMap;
std::string fileName;
void save();
void checkFile();
public:
/**
* Construct settings store
* and load data from file (if exists)
* \param filename Path to file with settings
*/
Settings(std::string const &fileName);
/**
* Get setting value
* \param name Setting unique identifier
* \param def Default setting value
* \return Stored value for given name or default value
*/
std::string const &get(std::string const &name,
std::string const &def = "") const;
/**
* Set or replace setting value and save changes to file
* \param name Setting unique identifier
* \param value New setting value
*/
void set(std::string const &name,
std::string const &value);
/**
* Reset all settings
*/
void reset();
/**
* Reload all settings from file
*/
void reload();
}; | true |
67cbc3905b3dc3dbca34d4577ac08c9ad2ed70ef | C++ | UnluckyHeroes/Idarax | /SDL8_Handout/ModuleScene1.cpp | UTF-8 | 1,586 | 2.515625 | 3 | [
"MIT"
] | permissive | #include "Globals.h"
#include "Application.h"
#include "ModuleTextures.h"
#include "ModuleRender.h"
#include "ModulePlayer.h"
#include "ModuleCollision.h"
#include "ModuleParticles.h"
#include "ModuleEnemies.h"
#include "ModuleScene1.h"
// Reference at https://www.youtube.com/watch?v=OEhmUuehGOA
ModuleScene1::ModuleScene1()
{}
ModuleScene1::~ModuleScene1()
{}
// Load assets
bool ModuleScene1::Start()
{
LOG("Loading space scene");
background = App->textures->Load("Rickme/Graphics/Room1/Room1.png");
App->player->Enable();
App->particles->Enable();
App->collision->Enable();
App->enemies->Enable();
// Colliders ---
App->collision->AddCollider({70, 224, 340, 25}, COLLIDER_WALL); //Down Wall
App->collision->AddCollider({ 70, 19, 340, 25 }, COLLIDER_WALL); //Up Wall
App->collision->AddCollider({ 408, 43, 25, 185 }, COLLIDER_WALL); //Right Wall
App->collision->AddCollider({ 46, 43, 25, 185 }, COLLIDER_WALL); //Left Wall
// Enemies ---
App->enemies->AddEnemy(ENEMY_TYPES::ENEMY_RAPIER, 300, 200);
return true;
}
// UnLoad assets
bool ModuleScene1::CleanUp()
{
LOG("Unloading space scene");
App->textures->Unload(background);
App->enemies->Disable();
App->collision->Disable();
App->particles->Disable();
App->player->Disable();
return true;
}
// Update: draw background
update_status ModuleScene1::Update()
{
// Move camera forward -----------------------------
//App->render->camera.x += 1 * SCREEN_SIZE;
// Draw everything --------------------------------------
App->render->Blit(background, 0, 0, NULL);
return UPDATE_CONTINUE;
} | true |
053d613f6756249c8770de3122f0fa74ae7d6a7c | C++ | Zanzal/X-Studio2-Mirror | /Logic/MapIterator.hpp | UTF-8 | 1,863 | 3.390625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <iterator>
namespace Logic
{
namespace Utils
{
/// <summary>Forward only iterator for accessing the values in a map collection</summary>
template <typename OBJ, typename COLL, typename ITER>
class MapIterator : public std::iterator<std::forward_iterator_tag, OBJ>
{
// ------------------------ TYPES --------------------------
// --------------------- CONSTRUCTION ----------------------
public:
/// <summary>Create new iterator</summary>
/// <param name="c">The collection</param>
/// <param name="pos">The initial position</param>
MapIterator(const COLL& c, ITER pos) : Collection(&c), Position(pos)
{
}
// --------------------- PROPERTIES ------------------------
// ---------------------- ACCESSORS ------------------------
public:
OBJ& operator*() const { return Position->second; }
OBJ* operator->() const { return &Position->second; }
bool operator==(const MapIterator& r) const { return Collection==r.Collection && Position==r.Position; }
bool operator!=(const MapIterator& r) const { return Collection!=r.Collection || Position!=r.Position; }
// ----------------------- MUTATORS ------------------------
public:
MapIterator& operator++()
{
++Position;
return *this;
}
MapIterator operator++(int)
{
MapIterator tmp(*this);
operator++();
return tmp;
}
// -------------------- REPRESENTATION ---------------------
private:
const COLL* Collection;
ITER Position;
};
}
}
| true |
f33ae202ebd3dc215ba2ccdaf23552b263df36f2 | C++ | JavaZhangYin/coding | /general/const.cpp | UTF-8 | 984 | 3.90625 | 4 | [] | no_license | #include<iostream>
// const int const * const func(const int const * const &p) const;
// the function can be reduced to ==>>
// int const * const func(int const * const &p) const;
// from left to right,
// const 1: return value can not be changed.
// const 2: return pointer can not be changed.
// const 3: parameter can not be changed.
// const 4: pointer p can not be changed.
// const 5: does not make sense for non-member functions.
int main(){
// const value.
const int i = 100;
i = 200; // fails, i is const.
const_cast<int&> (i) = 20; // good, const is cast away.
// const pointer.
int x = 10;
int * const p = &i;
*p = 20; // ok, value that p is pointing to can be changed.
p++; // fail, pointer p is const.
static_cast<const int&> (x) = 20; // fail, x is const now.
// const pointer + const values.
int x1 = 10;
const int * const p = & x1;
*p = 20; // fail, value is const.
p++; // fail, pointer is also const.
}
| true |
ebfd0e734594fb011bade71d92a6957b8aa553cb | C++ | LordBones/EvoLisaBetter | /TestWin32/FastFunctions2.cpp | UTF-8 | 2,320 | 2.625 | 3 | [] | no_license | #include "stdafx.h"
#include "FastFunctions2.h"
FastFunctions2::FastFunctions2(void)
{
}
FastFunctions2::~FastFunctions2(void)
{
}
void FastFunctions2::FastRowApplyColor(unsigned char * canvas, int from, int to, int colorABRrem, int colorAGRrem, int colorARRrem, int colorRem)
{
//unsigned int * ptrColor = (unsigned int *)(canvas+from);
//int count = (to - from)>>2;
// while(count>=0)
// {
//
// unsigned int Color = ptrColor[count];
// unsigned int res = Color&0xff000000;
// res |= ApplyColor((Color>>16)&0xFF, colorARRrem, colorRem) << 16; // r
// unsigned int G = (Color>>8)&0xFF;
// res |= ApplyColor(G, colorAGRrem, colorRem)<<8;
// unsigned int B = Color&0xFF;
//
// res |= ((colorABRrem + colorRem * B)>> 16);// ApplyColor(B, colorABRrem, colorRem);
//
//
// ptrColor[count] = res; // (Color&0xff000000) | (R<<16) | (G << 8) | B;
//
// count--;
//
// }
/*
while(from <= to)
{
int index = from;
canvas[index] = (unsigned char)FastFunctions::ApplyColor(canvas[index], colorABRrem, colorRem);
canvas[index + 1] = (unsigned char)FastFunctions::ApplyColor(canvas[index + 1], colorAGRrem, colorRem);
canvas[index + 2] = (unsigned char)FastFunctions::ApplyColor(canvas[index + 2], colorARRrem, colorRem);
from += 4;
}*/
while(from <= to)
{
int index = from;
//((axrem + rem * colorChanel) >> 16)
unsigned int b = canvas[index];
unsigned int g = canvas[index+1];
unsigned int r = canvas[index+2];
b*=colorRem;
g*=colorRem;
r*=colorRem;
b+=colorABRrem;
g+=colorAGRrem;
r+=colorARRrem;
b>>=16;
g>>=16;
r>>=16;
canvas[index] = (unsigned char)b;
canvas[index+1] = (unsigned char)g;
canvas[index+2] = (unsigned char)r;
from += 4;
}
/* canvas = canvas + from;
while(from <= to)
{
*canvas = ApplyColor(*canvas, colorABRrem, colorRem);
canvas[1] = ApplyColor(canvas[1], colorAGRrem, colorRem);
canvas[2] = ApplyColor(canvas[2], colorARRrem, colorRem);
from += 4;
canvas +=4;
}*/
}
| true |
6a8af0d88727a334b90258aec72878c22c8c792f | C++ | redturtlepower/openapi-generator-integration | /server/qt/demo/logger.h | UTF-8 | 501 | 2.828125 | 3 | [] | no_license | #ifndef LOGGER_H
#define LOGGER_H
#include <QPlainTextEdit>
class Logger{
Logger() = default;
QPlainTextEdit *output_;
public:
Logger(const Logger &) = delete;
void operator=(const Logger &) = delete;
static Logger &getLogger(){
static Logger logger;
return logger;
}
void setOutput(QPlainTextEdit *t){
output_ = t;
}
void log(const QString &t){
Q_ASSERT(output_);
output_->appendPlainText(t);
}
};
#endif // LOGGER_H
| true |
33568e13c0c165e80880ec5c2725c49899a77103 | C++ | RGBRYANT24/AlgorithmPractice | /Tiantisai/5.cpp | UTF-8 | 562 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int num[30];
for(int i=0; i < 24; i ++)
{
cin >> num[i];
}
int time;
int count = 0;
while (cin >> time )
{
if(time >= 24 || time < 0)
{
break;
}
if (count)
{
cout << endl;
}
count++;
cout << num[time];
if(num[time] > 50)
{
cout << " Yes";
}
else
{
cout << " No";
}
}
return 0;
} | true |
0d6849367c09c797ab262de816b1d55f7c12a6ad | C++ | maximaximal/Spacegasm | /src/CTextureManager.cpp | UTF-8 | 1,755 | 2.90625 | 3 | [] | no_license | #include "CTextureManager.h"
#include <iostream>
#include <CTexture.h>
#include <CStringExt.h>
using namespace std;
CTextureManager::CTextureManager()
{
//ctor
}
CTextureManager::~CTextureManager()
{
//dtor
}
void CTextureManager::loadTexture(std::string filename, std::string textureID)
{
if(m_textures.count(textureID) > 0)
{
cout << "!! Texture named " << textureID << " is already loaded! Doing nothing...." << endl;
return;
}
else
{
shared_ptr<CTexture> texture(new CTexture());
std::thread texthread(&CTexture::load, texture.get(), filename);
m_textures.insert(pair<string, shared_ptr<CTexture> >(textureID, texture));
texture.reset();
}
}
sf::IntRect CTextureManager::getRect(std::string textureID, std::string rect, unsigned int Number)
{
if(m_textures.count(textureID) > 0)
{
return m_textures[textureID]->getRect(rect, Number);
}
}
void CTextureManager::addSprite(std::string textureID, sf::Sprite *sprite, std::string textureRect, unsigned int textureNumber)
{
if(m_textures.count(textureID) > 0)
{
m_textures[textureID]->addAfterloadSprite(sprite, textureRect, textureNumber);
}
else
{
cout << "!! There is no Texture named " << textureID << "!" << endl;
}
}
void CTextureManager::setRenderWindow(sf::RenderWindow *window)
{
m_window = window;
}
void CTextureManager::setWindowActive(bool active)
{
m_window->setActive(active);
}
sf::Texture& CTextureManager::getTexture(std::string textureID)
{
if(m_textures.count(textureID) > 0)
{
return m_textures[textureID]->get();
}
else
{
cout << "!! There is no Texture named " << textureID << "!" << endl;
}
}
| true |
a2ab807e13a8cd54c55e83199c4bd04c6f248d1e | C++ | fmilburn3/DigitalPot_MCP41010 | /DigiPot.cpp | UTF-8 | 980 | 2.734375 | 3 | [] | no_license | /*
DigiPot.cpp - Library for MCP41010 digital potentiometer.
Created by Frank Milburn, 17 June 2015
Released into the public domain.
*/
#include <Energia.h>
#include "DigiPot.h"
DigiPot::DigiPot(int digiPotPin)
{
_digiPotPin = digiPotPin;
pinMode(_digiPotPin, OUTPUT);
}
void DigiPot::setValue(byte potValue)
{
_potCommand = B00010001; // command to write to pot
_potValue = potValue; // pot value to be written
writeValue(_potCommand, _potValue);
}
void DigiPot::shutdown()
{
_potCommand = B00100001; // command to shutdown pot
_potValue = B00000000; // pot value doesn't matter
writeValue(_potCommand, _potValue);
}
void DigiPot::writeValue(byte _potCommand, byte _potValue)
{
digitalWrite(_digiPotPin, LOW); // SS pin low - select chip
SPI.transfer(_potCommand); // transfer command
SPI.transfer(_potValue); // transfer value
digitalWrite(_digiPotPin, HIGH); // SS pin high - de-select chip
}
| true |
dffa109f5c665b6847a199664354d8c816bdc18f | C++ | chasebroder/SWDevProj | /src/utils/args.h | UTF-8 | 3,295 | 3.046875 | 3 | [] | no_license | #pragma once
#include "object.h"
#include <stdio.h>
/**
* A class to parse and hold all of the command line arguments. This object will end up being exposed to
* the entire program.
* IMPORTANT: Need to call parse() to actually read in the commandline args. Otherwise it will be all defaults
*
* @authors: kierzenka.m@husky.neu.edu and broder.c@husky.neu.edu
*/
class Arguments : public Object
{
public:
char *appName;
size_t numNodes;
size_t index;
char *ip;
size_t port;
char *serverIp;
size_t serverPort;
size_t serverIndex;
bool usePseudoNet;
size_t blockSize;
Arguments()
{
appName = nullptr; //"trivial";
numNodes = 1;
index = 0;
ip = nullptr; //"127.0.0.1";
port = 8080;
serverIp = nullptr; //"127.0.0.1";
serverPort = 8080;
serverIndex = 0;
usePseudoNet = false;
blockSize = 1024;
}
~Arguments() {}
void parse(int argc, char **argv)
{
for (int i = 1; i < argc; i++)
{
char *arg = argv[i];
if (strcmp(arg, "-pseudo") == 0)
{
usePseudoNet = true;
continue;
}
if (i == (argc - 1))
{
usageError_(arg);
exit(-1);
}
if (strcmp(arg, "-app") == 0)
{
appName = argv[++i];
}
else if (strcmp(arg, "-num_nodes") == 0)
{
numNodes = tryParseSizeT_(argv[++i]);
}
else if (strcmp(arg, "-i") == 0)
{
index = tryParseSizeT_(argv[++i]);
}
else if (strcmp(arg, "-ip") == 0)
{
ip = argv[++i];
}
else if (strcmp(arg, "-port") == 0)
{
port = tryParseSizeT_(argv[++i]);
}
else if (strcmp(arg, "-serverIdx") == 0)
{
serverIndex = tryParseSizeT_(argv[++i]);
}
else if (strcmp(arg, "-serverIp") == 0)
{
serverIp = argv[++i];
}
else if (strcmp(arg, "-serverPort") == 0)
{
serverPort = tryParseSizeT_(argv[++i]);
}
else if (strcmp(arg, "-blockSize") == 0)
{
blockSize = tryParseSizeT_(argv[++i]);
}
else
{
usageError_(arg);
}
}
}
/** Try to get a numerical value from a string. Error if invalid */
size_t tryParseSizeT_(char *arg)
{
size_t val = 0;
if (sscanf(arg, "%zu", &val) != 1)
{
fprintf(stderr, "Could not parse %s into a size_t\n", arg);
exit(1);
}
//scan was successful: return the value
return val;
}
void usageError_(char *arg)
{
fprintf(stderr, "Usage Error for argument (%s). Expected: ./eau2 -app (appname) -num_nodes N -i (mynodenum) -pseudo -ip (myipaddr) -port N -serverIp (addr) -serverPort N\n", arg);
exit(-1);
}
};
extern Arguments args;
| true |
dc47a200afeb79ed39712c78675130eab6db5ee1 | C++ | jeanpimentel/fsm66 | /erro.cpp | ISO-8859-1 | 2,047 | 2.953125 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
#include <stdlib.h>
#include "lexico.h"
#include "erro.h"
int quantidade_erros = 0;
const char* erro_mensagem(int);
const char* tipo_erro(int);
void erro(int tipo, int erro, int linha) {
quantidade_erros++;
fprintf(stderr, "ERRO%s: %s na linha %d.\n", tipo_erro(tipo), erro_mensagem(erro), linha);
}
void erro(int tipo, int erro, int linha, char extra) {
quantidade_erros++;
fprintf(stderr, "ERRO%s: %s [%c] na linha %d.\n", tipo_erro(tipo), erro_mensagem(erro), extra, linha);
}
void erro(int tipo, int erro, int linha, char* extra) {
quantidade_erros++;
fprintf(stderr, "ERRO%s: %s [%s] na linha %d.\n", tipo_erro(tipo), erro_mensagem(erro), extra, linha);
}
void erro_sintatico_token_esperado(int linha, char* esperado, char* encontrado) {
quantidade_erros++;
fprintf(stderr, "ERRO SINTATICO: %s [%s] na linha %d. %s [%s]\n", "Token encontrado", encontrado, linha, "Token esperado", esperado);
}
const char* tipo_erro(int tipo) {
switch(tipo) {
case ERRO_TIPO_LEXICO: return " LEXICO"; break;
case ERRO_TIPO_SINTATICO: return " SINTATICO"; break;
default: return ""; break;
}
}
const char* erro_mensagem(int erro) {
switch(erro) {
case ERRO_CARACTER_INVALIDO: return "Caracter invlido"; break;
case ERRO_NUMERO_INVALIDO: return "Nmero invlido"; break;
case ERRO_FIM_ARQUIVO_LITERAL: return "Fim de arquivo inesperado durante literal"; break;
case ERRO_FIM_ARQUIVO_COMENTARIO: return "Fim de arquivo inesperado durante comentrio"; break;
case ERRO_TOKEN_INESPERADO: return "Token inesperado"; break;
case ERRO_TOKEN_ESPERADO: return "Token esperado"; break;
case ERRO_FIM_ARQUIVO_INESPERADO: return "Fim de arquivo inesperado"; break;
default: return ""; break;
}
}
void erro_incrementar() {
quantidade_erros++;
}
int erro_quantidade_erros() {
return quantidade_erros;
}
void erro_imprimir_erros() {}
| true |
7553497cfa5b35d6e6ebf6d0951a8cb9c1395492 | C++ | Kuailun/Leetcode | /_167_Two_Sum_II/_167_Two_Sum_II.cpp | UTF-8 | 1,492 | 3.328125 | 3 | [] | no_license |
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
vector<int> twoSum(vector<int>& nums, int target);
int main()
{
vector<int> input, output;
int target;
input.push_back(2);
input.push_back(7);
input.push_back(9);
input.push_back(11);
target = 13;
output = twoSum(input, target);
system("pause");
}
vector<int> twoSum(vector<int>& nums, int target)
{
vector<int> answer;
int left = 0;
int right = nums.size() - 1;
while (left < right)
{
if (nums[left] + nums[right] < target)
{
left++;
}
else if (nums[left] + nums[right] > target)
{
right--;
}
else
{
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] == nums[left] || nums[i] == nums[right])
{
answer.push_back(i);
}
if (answer.size() == 2)
{
return answer;
}
}
}
}
return answer;
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
| true |
4ce5c8305a64c1b0f4db78bb483d0111414bd89e | C++ | RajKamal2013/DSA | /C++Source/flags.cpp | UTF-8 | 12,616 | 3.171875 | 3 | [] | no_license | // Test the efficiency of various implementations for storing and
// manipulating 32 boolean values. Methods tested are arrays of ints,
// shorts, chars, and one-bit boolean values.
#include "book.h"
// 32 one-bit values using the C++ bit-flag operators
struct btype {
int f0 : 1;
int f1 : 1;
int f2 : 1;
int f3 : 1;
int f4 : 1;
int f5 : 1;
int f6 : 1;
int f7 : 1;
int f8 : 1;
int f9 : 1;
int f10 : 1;
int f11 : 1;
int f12 : 1;
int f13 : 1;
int f14 : 1;
int f15 : 1;
int f16 : 1;
int f17 : 1;
int f18 : 1;
int f19 : 1;
int f20 : 1;
int f21 : 1;
int f22 : 1;
int f23 : 1;
int f24 : 1;
int f25 : 1;
int f26 : 1;
int f27 : 1;
int f28 : 1;
int f29 : 1;
int f30 : 1;
int f31 : 1;
};
// An array of characters
struct cstruct {
char pos[32];
};
// An array of shorts
struct sstruct {
short pos[32];
};
// An array of longs (which is the same as an int on a 32-bit machine)
struct lstruct {
long pos[32];
};
// Now, lets see how long it takes to use these implementations
int main(int argc, char** argv)
{
struct cstruct cs; // chars
struct sstruct ss; // shorts
struct lstruct ls; // longs
struct btype b; // bits
char csa[32];
short ssa[32];
long lsa[32];
long count;
long i;
// For timing, we can vary the number of iterations run
Assert(argc == 2, "Usage: flags <number_of_iterations>");
count = atol(argv[1]);
cs.pos[0] = true;
ss.pos[0] = true;
ls.pos[0] = true;
csa[0] = true;
ssa[0] = true;
lsa[0] = true;
b.f0 = true;
// For each interation, we are going to test the time to read and write
// the values by doing a copy from one array position to another.
// To cut down on the overhead of the outer loop, we do 120 assignements
// within the loop body.
Settime();
for (i=0; i<count; i++) {
csa[1] = csa[0];
csa[2] = csa[1];
csa[3] = csa[2];
csa[4] = csa[3];
csa[5] = csa[4];
csa[6] = csa[5];
csa[7] = csa[6];
csa[8] = csa[7];
csa[9] = csa[8];
csa[10] = csa[9];
csa[11] = csa[10];
csa[12] = csa[11];
csa[13] = csa[12];
csa[14] = csa[13];
csa[15] = csa[14];
csa[16] = csa[15];
csa[17] = csa[16];
csa[18] = csa[17];
csa[19] = csa[18];
csa[20] = csa[19];
csa[21] = csa[20];
csa[22] = csa[21];
csa[23] = csa[22];
csa[24] = csa[23];
csa[25] = csa[24];
csa[26] = csa[25];
csa[27] = csa[26];
csa[28] = csa[27];
csa[29] = csa[28];
csa[30] = csa[29];
csa[1] = csa[0];
csa[2] = csa[1];
csa[3] = csa[2];
csa[4] = csa[3];
csa[5] = csa[4];
csa[6] = csa[5];
csa[7] = csa[6];
csa[8] = csa[7];
csa[9] = csa[8];
csa[10] = csa[9];
csa[11] = csa[10];
csa[12] = csa[11];
csa[13] = csa[12];
csa[14] = csa[13];
csa[15] = csa[14];
csa[16] = csa[15];
csa[17] = csa[16];
csa[18] = csa[17];
csa[19] = csa[18];
csa[20] = csa[19];
csa[21] = csa[20];
csa[22] = csa[21];
csa[23] = csa[22];
csa[24] = csa[23];
csa[25] = csa[24];
csa[26] = csa[25];
csa[27] = csa[26];
csa[28] = csa[27];
csa[29] = csa[28];
csa[30] = csa[29];
csa[1] = csa[0];
csa[2] = csa[1];
csa[3] = csa[2];
csa[4] = csa[3];
csa[5] = csa[4];
csa[6] = csa[5];
csa[7] = csa[6];
csa[8] = csa[7];
csa[9] = csa[8];
csa[10] = csa[9];
csa[11] = csa[10];
csa[12] = csa[11];
csa[13] = csa[12];
csa[14] = csa[13];
csa[15] = csa[14];
csa[16] = csa[15];
csa[17] = csa[16];
csa[18] = csa[17];
csa[19] = csa[18];
csa[20] = csa[19];
csa[21] = csa[20];
csa[22] = csa[21];
csa[23] = csa[22];
csa[24] = csa[23];
csa[25] = csa[24];
csa[26] = csa[25];
csa[27] = csa[26];
csa[28] = csa[27];
csa[29] = csa[28];
csa[30] = csa[29];
csa[1] = csa[0];
csa[2] = csa[1];
csa[3] = csa[2];
csa[4] = csa[3];
csa[5] = csa[4];
csa[6] = csa[5];
csa[7] = csa[6];
csa[8] = csa[7];
csa[9] = csa[8];
csa[10] = csa[9];
csa[11] = csa[10];
csa[12] = csa[11];
csa[13] = csa[12];
csa[14] = csa[13];
csa[15] = csa[14];
csa[16] = csa[15];
csa[17] = csa[16];
csa[18] = csa[17];
csa[19] = csa[18];
csa[20] = csa[19];
csa[21] = csa[20];
csa[22] = csa[21];
csa[23] = csa[22];
csa[24] = csa[23];
csa[25] = csa[24];
csa[26] = csa[25];
csa[27] = csa[26];
csa[28] = csa[27];
csa[29] = csa[28];
csa[30] = csa[29];
}
cout << "Time for characters (120 assigns): " << count
<< " iterations: " << Gettime() << " seconds\n";
Settime();
for (i=0; i<count; i++) {
ssa[1] = ssa[0];
ssa[2] = ssa[1];
ssa[3] = ssa[2];
ssa[4] = ssa[3];
ssa[5] = ssa[4];
ssa[6] = ssa[5];
ssa[7] = ssa[6];
ssa[8] = ssa[7];
ssa[9] = ssa[8];
ssa[10] = ssa[9];
ssa[11] = ssa[10];
ssa[12] = ssa[11];
ssa[13] = ssa[12];
ssa[14] = ssa[13];
ssa[15] = ssa[14];
ssa[16] = ssa[15];
ssa[17] = ssa[16];
ssa[18] = ssa[17];
ssa[19] = ssa[18];
ssa[20] = ssa[19];
ssa[21] = ssa[20];
ssa[22] = ssa[21];
ssa[23] = ssa[22];
ssa[24] = ssa[23];
ssa[25] = ssa[24];
ssa[26] = ssa[25];
ssa[27] = ssa[26];
ssa[28] = ssa[27];
ssa[29] = ssa[28];
ssa[30] = ssa[29];
ssa[1] = ssa[0];
ssa[2] = ssa[1];
ssa[3] = ssa[2];
ssa[4] = ssa[3];
ssa[5] = ssa[4];
ssa[6] = ssa[5];
ssa[7] = ssa[6];
ssa[8] = ssa[7];
ssa[9] = ssa[8];
ssa[10] = ssa[9];
ssa[11] = ssa[10];
ssa[12] = ssa[11];
ssa[13] = ssa[12];
ssa[14] = ssa[13];
ssa[15] = ssa[14];
ssa[16] = ssa[15];
ssa[17] = ssa[16];
ssa[18] = ssa[17];
ssa[19] = ssa[18];
ssa[20] = ssa[19];
ssa[21] = ssa[20];
ssa[22] = ssa[21];
ssa[23] = ssa[22];
ssa[24] = ssa[23];
ssa[25] = ssa[24];
ssa[26] = ssa[25];
ssa[27] = ssa[26];
ssa[28] = ssa[27];
ssa[29] = ssa[28];
ssa[30] = ssa[29];
ssa[1] = ssa[0];
ssa[2] = ssa[1];
ssa[3] = ssa[2];
ssa[4] = ssa[3];
ssa[5] = ssa[4];
ssa[6] = ssa[5];
ssa[7] = ssa[6];
ssa[8] = ssa[7];
ssa[9] = ssa[8];
ssa[10] = ssa[9];
ssa[11] = ssa[10];
ssa[12] = ssa[11];
ssa[13] = ssa[12];
ssa[14] = ssa[13];
ssa[15] = ssa[14];
ssa[16] = ssa[15];
ssa[17] = ssa[16];
ssa[18] = ssa[17];
ssa[19] = ssa[18];
ssa[20] = ssa[19];
ssa[21] = ssa[20];
ssa[22] = ssa[21];
ssa[23] = ssa[22];
ssa[24] = ssa[23];
ssa[25] = ssa[24];
ssa[26] = ssa[25];
ssa[27] = ssa[26];
ssa[28] = ssa[27];
ssa[29] = ssa[28];
ssa[30] = ssa[29];
ssa[1] = ssa[0];
ssa[2] = ssa[1];
ssa[3] = ssa[2];
ssa[4] = ssa[3];
ssa[5] = ssa[4];
ssa[6] = ssa[5];
ssa[7] = ssa[6];
ssa[8] = ssa[7];
ssa[9] = ssa[8];
ssa[10] = ssa[9];
ssa[11] = ssa[10];
ssa[12] = ssa[11];
ssa[13] = ssa[12];
ssa[14] = ssa[13];
ssa[15] = ssa[14];
ssa[16] = ssa[15];
ssa[17] = ssa[16];
ssa[18] = ssa[17];
ssa[19] = ssa[18];
ssa[20] = ssa[19];
ssa[21] = ssa[20];
ssa[22] = ssa[21];
ssa[23] = ssa[22];
ssa[24] = ssa[23];
ssa[25] = ssa[24];
ssa[26] = ssa[25];
ssa[27] = ssa[26];
ssa[28] = ssa[27];
ssa[29] = ssa[28];
ssa[30] = ssa[29];
}
cout << "Time for shorts (120 assigns): " << count
<< " iterations: " << Gettime() << " seconds\n";
Settime();
for (i=0; i<count; i++) {
lsa[1] = lsa[0];
lsa[2] = lsa[1];
lsa[3] = lsa[2];
lsa[4] = lsa[3];
lsa[5] = lsa[4];
lsa[6] = lsa[5];
lsa[7] = lsa[6];
lsa[8] = lsa[7];
lsa[9] = lsa[8];
lsa[10] = lsa[9];
lsa[11] = lsa[10];
lsa[12] = lsa[11];
lsa[13] = lsa[12];
lsa[14] = lsa[13];
lsa[15] = lsa[14];
lsa[16] = lsa[15];
lsa[17] = lsa[16];
lsa[18] = lsa[17];
lsa[19] = lsa[18];
lsa[20] = lsa[19];
lsa[21] = lsa[20];
lsa[22] = lsa[21];
lsa[23] = lsa[22];
lsa[24] = lsa[23];
lsa[25] = lsa[24];
lsa[26] = lsa[25];
lsa[27] = lsa[26];
lsa[28] = lsa[27];
lsa[29] = lsa[28];
lsa[30] = lsa[29];
lsa[1] = lsa[0];
lsa[2] = lsa[1];
lsa[3] = lsa[2];
lsa[4] = lsa[3];
lsa[5] = lsa[4];
lsa[6] = lsa[5];
lsa[7] = lsa[6];
lsa[8] = lsa[7];
lsa[9] = lsa[8];
lsa[10] = lsa[9];
lsa[11] = lsa[10];
lsa[12] = lsa[11];
lsa[13] = lsa[12];
lsa[14] = lsa[13];
lsa[15] = lsa[14];
lsa[16] = lsa[15];
lsa[17] = lsa[16];
lsa[18] = lsa[17];
lsa[19] = lsa[18];
lsa[20] = lsa[19];
lsa[21] = lsa[20];
lsa[22] = lsa[21];
lsa[23] = lsa[22];
lsa[24] = lsa[23];
lsa[25] = lsa[24];
lsa[26] = lsa[25];
lsa[27] = lsa[26];
lsa[28] = lsa[27];
lsa[29] = lsa[28];
lsa[30] = lsa[29];
lsa[1] = lsa[0];
lsa[2] = lsa[1];
lsa[3] = lsa[2];
lsa[4] = lsa[3];
lsa[5] = lsa[4];
lsa[6] = lsa[5];
lsa[7] = lsa[6];
lsa[8] = lsa[7];
lsa[9] = lsa[8];
lsa[10] = lsa[9];
lsa[11] = lsa[10];
lsa[12] = lsa[11];
lsa[13] = lsa[12];
lsa[14] = lsa[13];
lsa[15] = lsa[14];
lsa[16] = lsa[15];
lsa[17] = lsa[16];
lsa[18] = lsa[17];
lsa[19] = lsa[18];
lsa[20] = lsa[19];
lsa[21] = lsa[20];
lsa[22] = lsa[21];
lsa[23] = lsa[22];
lsa[24] = lsa[23];
lsa[25] = lsa[24];
lsa[26] = lsa[25];
lsa[27] = lsa[26];
lsa[28] = lsa[27];
lsa[29] = lsa[28];
lsa[30] = lsa[29];
lsa[1] = lsa[0];
lsa[2] = lsa[1];
lsa[3] = lsa[2];
lsa[4] = lsa[3];
lsa[5] = lsa[4];
lsa[6] = lsa[5];
lsa[7] = lsa[6];
lsa[8] = lsa[7];
lsa[9] = lsa[8];
lsa[10] = lsa[9];
lsa[11] = lsa[10];
lsa[12] = lsa[11];
lsa[13] = lsa[12];
lsa[14] = lsa[13];
lsa[15] = lsa[14];
lsa[16] = lsa[15];
lsa[17] = lsa[16];
lsa[18] = lsa[17];
lsa[19] = lsa[18];
lsa[20] = lsa[19];
lsa[21] = lsa[20];
lsa[22] = lsa[21];
lsa[23] = lsa[22];
lsa[24] = lsa[23];
lsa[25] = lsa[24];
lsa[26] = lsa[25];
lsa[27] = lsa[26];
lsa[28] = lsa[27];
lsa[29] = lsa[28];
lsa[30] = lsa[29];
}
cout << "Time for longs (120 assigns): " << count
<< " iterations: " << Gettime() << " seconds\n";
Settime();
for (i=0; i<count; i++) {
b.f1 = b.f0;
b.f2 = b.f1;
b.f3 = b.f2;
b.f4 = b.f3;
b.f5 = b.f4;
b.f6 = b.f5;
b.f7 = b.f6;
b.f8 = b.f7;
b.f9 = b.f8;
b.f10 = b.f9;
b.f11 = b.f10;
b.f12 = b.f11;
b.f13 = b.f12;
b.f14 = b.f13;
b.f15 = b.f14;
b.f16 = b.f15;
b.f17 = b.f16;
b.f18 = b.f17;
b.f19 = b.f18;
b.f20 = b.f19;
b.f21 = b.f20;
b.f22 = b.f21;
b.f23 = b.f22;
b.f24 = b.f23;
b.f25 = b.f24;
b.f26 = b.f25;
b.f27 = b.f26;
b.f28 = b.f27;
b.f29 = b.f28;
b.f30 = b.f29;
b.f1 = b.f0;
b.f2 = b.f1;
b.f3 = b.f2;
b.f4 = b.f3;
b.f5 = b.f4;
b.f6 = b.f5;
b.f7 = b.f6;
b.f8 = b.f7;
b.f9 = b.f8;
b.f10 = b.f9;
b.f11 = b.f10;
b.f12 = b.f11;
b.f13 = b.f12;
b.f14 = b.f13;
b.f15 = b.f14;
b.f16 = b.f15;
b.f17 = b.f16;
b.f18 = b.f17;
b.f19 = b.f18;
b.f20 = b.f19;
b.f21 = b.f20;
b.f22 = b.f21;
b.f23 = b.f22;
b.f24 = b.f23;
b.f25 = b.f24;
b.f26 = b.f25;
b.f27 = b.f26;
b.f28 = b.f27;
b.f29 = b.f28;
b.f30 = b.f29;
b.f1 = b.f0;
b.f2 = b.f1;
b.f3 = b.f2;
b.f4 = b.f3;
b.f5 = b.f4;
b.f6 = b.f5;
b.f7 = b.f6;
b.f8 = b.f7;
b.f9 = b.f8;
b.f10 = b.f9;
b.f11 = b.f10;
b.f12 = b.f11;
b.f13 = b.f12;
b.f14 = b.f13;
b.f15 = b.f14;
b.f16 = b.f15;
b.f17 = b.f16;
b.f18 = b.f17;
b.f19 = b.f18;
b.f20 = b.f19;
b.f21 = b.f20;
b.f22 = b.f21;
b.f23 = b.f22;
b.f24 = b.f23;
b.f25 = b.f24;
b.f26 = b.f25;
b.f27 = b.f26;
b.f28 = b.f27;
b.f29 = b.f28;
b.f30 = b.f29;
b.f1 = b.f0;
b.f2 = b.f1;
b.f3 = b.f2;
b.f4 = b.f3;
b.f5 = b.f4;
b.f6 = b.f5;
b.f7 = b.f6;
b.f8 = b.f7;
b.f9 = b.f8;
b.f10 = b.f9;
b.f11 = b.f10;
b.f12 = b.f11;
b.f13 = b.f12;
b.f14 = b.f13;
b.f15 = b.f14;
b.f16 = b.f15;
b.f17 = b.f16;
b.f18 = b.f17;
b.f19 = b.f18;
b.f20 = b.f19;
b.f21 = b.f20;
b.f22 = b.f21;
b.f23 = b.f22;
b.f24 = b.f23;
b.f25 = b.f24;
b.f26 = b.f25;
b.f27 = b.f26;
b.f28 = b.f27;
b.f29 = b.f28;
b.f30 = b.f29;
}
cout << "Time for bitfields (120 assigns): " << count
<< " iterations: " << Gettime() << " seconds\n";
return 0;
}
| true |
0fe8e53234e011c5762f1a74c343f6cfd797f25a | C++ | KyleWilliford/Blackjack | /Blackjack/Blackjack/Game.cpp | UTF-8 | 18,024 | 3.140625 | 3 | [] | no_license | /*
Kyle Williford
Blackjack [WIP]
*/
#include <stdlib.h>
#include <iostream>
#include "Game.h"
#include "math.h"
bool Game::playAgain = false;
/*
@execRound
Controls a round of blackjack, dealer AI calls, card display calls, and player menu display, and input parse calls
*/
const void Game::execRound()
{
bool round_over = initRound();
int turn_counter = 1;
while(round_over == false){
std::cout << "\n!---TURN " << turn_counter << " START---!\n";
do{
//Present and process user menu choices
gameChoice();
//Check that changing an Ace's values has not put the player over 21; auto-correct if necessary
revertAces();
round_over = checkWinConditions(false, false);
if(round_over && !splitHand){
std::cout << "\n!---END OF TURN " << turn_counter << "---!\n";
gameOver();
}
++current_hand;
}while(current_hand < player.getNumberOfHands());
current_hand = 0;
if(!round_over){ //If the player didn't win outright or bust
dealerAI(); //Dealer's turn
}
//Check that all conditions (i.e. all hands are set to stand) are right to end the game
bool all_hands_stand = true;
for(int i = 0; i < player.getNumberOfHands(); ++i){
if(player.getHandStandStatus(i) == false){
all_hands_stand = false;
break;
}
}
if(!dealerStands){
all_hands_stand = false;
}else if(dealerBusted){
for(; current_hand < player.getNumberOfHands(); ++current_hand){ //set all hands to stand
setPlayerStands(true);
}
all_hands_stand = true;
}
if(round_over && all_hands_stand){
std::cout << "\n!---END OF TURN " << turn_counter << "---!\n";
gameOver();
}
++turn_counter;
}
}
/*
@purseNotEmpty
Returns true iff the player has money left to bet.
*/
const bool Game::isPurseEmpty() const
{
if(player.getPurse() <= 0){
return true;
}
return false;
}
/*
@displayChips
Display the bet amount for each of the player's hands of cards
*/
const void Game::displayChips() const
{
std::cout << "\nRemaining wallet: " << player.getPurse();
if(player.getNumberOfHands() == 1){
std::cout << "\nBet amount: " << player.getBet();
}else{
for(int i = 0; i < player.getNumberOfHands(); ++i){
std::cout << "\nBet amount for hand # " << (i + 1) << ": " << player.getBet();
}
}
if(insurance_amount != 0){
std::cout << "\nInsurance amount: " << insurance_amount;
}
}
/*
@initRound
Iinitialize a new round of cards using the current deck of cards.
*/
const bool Game::initRound()
{
//Draw two cards for the player and dealer
placeBet();
for(int i = 0; i < 2; ++i){
player.hit(current_hand, deck);
dealer.hit(0, deck);
}
//Display round #
std::cout << "\n\n!---ROUND " << round_counter << " START---!\n";
//Check if cards drawn form a blackjack (21 = Ace + face card or ten card)
bool blackjack = false;
int playerAceCount = player.checkForAces(current_hand);
int dealerAceCount = dealer.checkForAces(0);
if (dealer.displayCardVal(0, 0) == ACE || (playerAceCount == 1 && player.getHandTotal(current_hand) == 11)){ //insurance prompt
displayCards(true);
placeInsurance();
player.updatePurse(-1 * insurance_amount);
}
if(playerAceCount == 1 && dealerAceCount == 1 && player.getHandTotal(current_hand) == 11 && dealer.getHandTotal(0) == 11){
blackjack = checkWinConditions(true, true);
if(insurance_amount > 0){
std::cout << "\nYour insurance paid off.\n";
player.updatePurse(insurance_amount * 2);
insurance_amount = 0;
}
}
else if(playerAceCount == 1 && player.getHandTotal(current_hand) == 11){
blackjack = checkWinConditions(true, false);
}
else if(dealerAceCount == 1 && dealer.getHandTotal(0) == 11){
blackjack = checkWinConditions(false, true);
if(insurance_amount > 0){
std::cout << "Your insurance paid off.";
player.updatePurse(insurance_amount * 2);
insurance_amount = 0;
}
}
if(blackjack){
return gameOver();
}
return false;
}
/*
@placeInsurance
Prompt for the user to buy insurance
*/
const void Game::placeInsurance()
{
int tmp = 0;
bool valid = false; //Input validation flag
do{
std::cout << "\nThe dealer has an Ace upcard or you have a blackjack. You can buy insurance up to one half of your bet this round." <<
"\nIf the dealer has a blackjack, you will win twice your insurance amount." <<
"\nYou lose your insurance if the dealer does not have a blackjack." <<
"\nEnter insurance amount (0 to cancel): ";
std::string s;
std::cin >> s;
tmp = atoi(s.c_str());
if(tmp > player.getBet() / 2 || tmp < 0){
std::cout << "\n\nInvalid input.\n";
valid = false;
}
else{
valid = true;
}
}while(!valid); //Prompt for input again if not valid
Game::insurance_amount = tmp; //Assign valid insurance bet to member var
}
/*
@placeBet
Calls Player::placeBet, asking the user to ante up from their Wallet
*/
const void Game::placeBet()
{
std::cout << "Betting wallet: " << player.getPurse();
player.placeBet();
system("cls");
std::cout << "Bet amount: " << player.getBet();
}
/*
@displayCards
Display the cards in each player's hand.
Dealer's second card is hidden until the dealer stands (or the end of the round).
*/
const void Game::displayCards(const bool displayDealerHand) const
{
//Display wallet
displayChips();
//Display card names
std::cout << "\n\nYOUR CARDS\n";
int local_hand_counter = 0;
do{
if(player.getNumberOfHands() != 1){
std::cout << "\nHAND #" << local_hand_counter + 1 << ":\n";
}
for(int i = 0; i < player.getHandSize(local_hand_counter); ++i){
std::cout << "Card " << (i+1) << ": " << player.displayCardName(local_hand_counter, i) << std::endl;
}
++local_hand_counter;
}while(local_hand_counter < player.getNumberOfHands());
if(displayDealerHand){
bool player_stands_all = true;
for(int i = 0; i < player.getNumberOfHands(); ++i){
if(player.getHandStandStatus(i) == false){
player_stands_all = false;
break;
}
}
std::cout << "\n\nDEALER'S CARDS\n";
int tmp = 1;
for(int i = 0; i < dealer.getHandSize(0); ++i){
if(i == 1 && ((!player_stands_all) || (!dealerStands))){ //Hide second drawn card
std::cout << "\nHole Card: face down (hidden).";
}
else{
std::cout << "\nUpcard " << (tmp) << ": " << dealer.displayCardName(0, i);
++tmp;
}
}
}
std::cout << "\n";
}
/*
@flipAces
Allow the player to change the value of ace cards.
*/
const void Game::flipAces()
{
do{
displayCards(false); //Don't display the dealer's hand
std::cout << "\nYou have one or more ace cards whose value can be modified (to 1 or 11).\n" <<
"Enter the card number for an ace that you would like to flip (or -1 to cancel): ";
std::string s;
std::cin >> s;
int choice = atoi(s.c_str());
if(choice == -1){
break;
}
else if(choice <= 0 || choice > player.getHandSize(current_hand)){
std::cout << "\nInvalid input.\n";
continue;
}
else if(choice >= 1 && choice <= player.getHandSize(current_hand)){
int index = choice - 1;
player.changeAce(current_hand, player.displayCardVal(current_hand, index), index);
}
}while(true);
}
/*
@flipAllAces
Flip the value of all of the @parameter player's ace cards.
Can be used for the dealer or player.
Used when a player has a blackjack (Ace + 10 value card on first two card draws).
*/
const void Game::flipAllAces(Player &player)
{
for(int i = 0; i < player.getHandSize(current_hand); ++i){
player.changeAce(current_hand, player.displayCardVal(current_hand, i), i);
}
}
/*
@revertAces
Revert ACE (11) cards to ACE (1) if the player's current hand is over 21. You wouldn't want to stand on two ACE (11) cards, now would you?
*/
const void Game::revertAces()
{
if(player.getHandTotal(current_hand) > 21 && checkNumAces() != 0){
for(int i = 0; i < player.getHandSize(current_hand); ++i){
if(player.displayCardVal(current_hand, i) == VERSA_ACE){
player.changeAce(current_hand, player.displayCardVal(current_hand, i), i);
if(!doubledDown){ //If doubled down, do not allow the user to draw more cards
setPlayerStands(false);
}
displayCards(false);
std::cout << "\n\nWARNING: Your current hand is greater than 21, but at least one ace card with a value of 11 was detected.\n" <<
"Your ace card with value of 11 has been reverted to 1.\n" <<
"You can also hit again even if you chose to stand with a hand greater than 21.";
if(player.getHandTotal(current_hand) < 21){
break; //Break only if the player's hand has been reduced under 21
}
}
}
}
}
/*
@checkForAcess
Check for the existence of aces within a player's hand.
*/
const int Game::checkNumAces() const
{
return player.checkForAces(current_hand);
}
/*
@gameChoice
Parse input from execRound for user game interactions.
*/
const void Game::gameChoice()
{
if(!getPlayerStands()){
bool valid = false;
do{
displayCards(true);
bool double_valid = false, split_valid = false, ace_valid = false;
//Display menu
std::cout << "\nMake a choice for hand #" << current_hand + 1 << ".\n";
std::cout << "1. Hit\n";
std::cout << "2. Stand\n";
if(player.getHandSize(current_hand) == 2 && player.getNumberOfHands() == 1 && (player.getBet() * 2 <= player.getPurse())){ //Check that the player can afford to double down, and is eligible to do so this round
std::cout << "3. Double Down\n";
double_valid = true;
}
if(player.getHandSize(current_hand) == 2 && ((player.displayCardName(current_hand, 0) == player.displayCardName(current_hand, 1)) || ((player.displayCardVal(current_hand, 0) == 1 || player.displayCardVal(current_hand, 0) == 11) && (player.displayCardVal(current_hand, 1) == 1 || player.displayCardVal(current_hand, 1) == 11)))){
if(player.getBet() <= player.getPurse()){
std::cout << "4. Split Hand\n";
split_valid = true;
}
}
if(checkNumAces() != 0){
std::cout << "5. Change Ace Values\n";
ace_valid = true;
}
//Parse user input
std::cout << "\nMake your choice: ";
std::string input;
std::cin >> input;
int choice = atoi(input.c_str());
if((choice == 3 && !double_valid)
|| (choice == 4 && !split_valid)
|| (choice == 5 && !ace_valid)){ //Prevent access to unlisted choices in specific conditions
std::cout << "\nInvalid Input.";
valid = false;
continue;
}
switch(choice){
case 1: //HIT
system("cls");
player.hit(current_hand, deck);
std::cout << "You drew a " << player.displayCardName(current_hand, player.getHandSize(current_hand) - 1) << ".\n";
if(player.getHandTotal(current_hand) == 21){ //Force player to stand on 21
setPlayerStands(true);
}
valid = true;
break;
case 2: //STAND
system("cls");
std::cout << "You Stand.\n";
setPlayerStands(true);
valid = true;
break;
case 3: //DOUBLE DOWN
system("cls");
doubledDown = true;
player.doubleBet(); //Double the bet
player.hit(current_hand, deck); //Draw a single card
std::cout << "You doubled down, and drew a " << player.displayCardName(current_hand, player.getHandSize(current_hand) - 1) << ". You are now standing on this hand.\n";
setPlayerStands(true); //Prevent drawing more cards
valid = true;
break;
case 4: //SPLIT HAND
system("cls");
splitHand = true;
std::cout << "You split your hand!\n" <<
"You draw a new card for each hand.\n" <<
"You will now play on each hand until you stand, win, lose, or push on all of your hands of cards." <<
"\nYour bet is also increased to cover each hand.\n";
player.addSplitHand(current_hand, deck);
valid = false; //Allow the user to hit/stand on hand 1 before proceeding
break;
case 5: //FLIP ACES
flipAces();
valid = false; //Don't immediately proceed to checkWinConditions with the new ace values
break;
default:
std::cout << "\nInvalid Input.\n\n";
valid = false;
break;
}
}while(!valid);
}
}
/*
@dealerAI
Process the dealer's turn.
The dealer will decide to hit or stand based on the value of its hand.
Stand on 17.
*/
const void Game::dealerAI()
{
if(!dealerStands){
//Determine dealer's move
int dealerTotal = dealer.getHandTotal(0);
if(dealerTotal < 17){
dealer.hit(0, deck);
std::cout << "\nDealer draws a(n) " << dealer.displayCardName(0, dealer.getHandSize(0) - 1) << ".\n";
}
else if(dealerTotal >= 17){
std::cout << "\nDealer stands.\n";
dealerStands = true;
}
}
if(dealer.getHandTotal(0) > 21){
dealerBusted = true;
}
}
/*
@displayEndOfRound
Displays relevant game data for the end of the round.
Round #
Cards (with hidden card revealed)
Player hand total
Dealer hand total
*/
const void Game::displayEndOfRound()
{
int playerHand = player.getHandTotal(current_hand);
int dealerHand = dealer.getHandTotal(0);
setPlayerStands(true);
dealerStands = true;
displayCards(true);
std::cout << "\nYour hand total: " << playerHand << std::endl;
std::cout << "Dealer hand total: " << dealerHand << std::endl;
}
/*
@checkWinConditions
Checks the player's and dealer's hands against all win, lose, and tie conditions.
p_blackjack and d_blackjack are values representing whether or not a blackjack was achieved on the first two card draws of the round.
*/
const bool Game::checkWinConditions(const bool p_blackjack, const bool d_blackjack)
{
if(p_blackjack && d_blackjack){
flipAllAces(player);
flipAllAces(dealer);
}
else if(p_blackjack && !d_blackjack){
flipAllAces(player);
}
else if(!p_blackjack && d_blackjack){
flipAllAces(dealer);
}
//Check for blackjack on first two card draws
if(p_blackjack && d_blackjack){ //Player and dealer both have blackjack.
displayEndOfRound();
std::cout << "You and the dealer both drew blackjack. Push." << std::endl;
player.updatePurse(player.getBet());
return true;
}
else if(!p_blackjack && d_blackjack){ //Dealer has blackjack
displayEndOfRound();
std::cout << "Dealer got a Blackjack! You lost." << std::endl;
return true;
}
else if(p_blackjack && !d_blackjack){ //Player has blackjack
displayEndOfRound();
std::cout << "You got a Blackjack! Payout = 3:2" << std::endl;
int scale = (int) ceil(player.getBet() + (1.5 * player.getBet()));
player.updatePurse(scale);
return true;
}
/*
Other win and lose conditions
*/
if(player.getHandTotal(current_hand) > 21 && dealer.getHandTotal(0) > 21){ //Player and dealer hands > 21
displayEndOfRound();
std::cout << "You and the dealer both bust for hand #" << current_hand + 1 << ". Push." << std::endl;
player.updatePurse(player.getBet());
return true;
}
else if(player.getHandTotal(current_hand) > 21){ //Player hand > 21
displayEndOfRound();
std::cout << "You bust hand #" << current_hand + 1 << "." << std::endl;
return true;
}
else if(dealer.getHandTotal(0) > 21){ //Dealer hand > 21
displayEndOfRound();
std::cout << "Dealer bust. You won hand #" << current_hand + 1 << "!" << std::endl;
player.updatePurse(player.getBet() * 2);
Game::dealerBusted = true;
return true;
}
else if(player.getHandTotal(current_hand) == 21 && dealer.getHandTotal(0) == 21){ //Player and dealer hands = 21
displayEndOfRound();
std::cout << "You and the dealer both have 21 for hand #" << current_hand + 1 << ". Push." << std::endl;
player.updatePurse(player.getBet());
return true;
}
else if(getPlayerStands() && dealerStands){ //Final check for win, lose, tie after player and dealer have finished moving (both players "stand")
if(player.getHandTotal(current_hand) == dealer.getHandTotal(0)){ //Tie
displayEndOfRound();
std::cout << "You and the dealer have the same card values for hand #" << current_hand + 1 << ". Push." << std::endl;
player.updatePurse(player.getBet());
return true;
}
else if(player.getHandTotal(current_hand) < dealer.getHandTotal(0)){ //Player loses
displayEndOfRound();
std::cout << "You lost hand #" << current_hand + 1 << "!" << std::endl;
return true;
}
else if(player.getHandTotal(current_hand) > dealer.getHandTotal(0)){ //Player wins
displayEndOfRound();
std::cout << "You won hand #" << current_hand + 1 <<"!" << std::endl;
player.updatePurse(player.getBet() * 2);
return true;
}
}
return false; //The round is not over - no condition satisfied
}
/*
@gameOver
Prompt for a user response to continue playing.
Reset a round of blackjack, or exit.
*/
const bool Game::gameOver()
{
if(insurance_amount != 0){
std::cout << "\nYou lost your insurance bet.\n";
}
std::cout << "\n!---END OF ROUND " << round_counter << "---!\n";
std::cout << "\nYour current purse: " << player.getPurse() << std::endl;
bool valid = false;
do{
std::cout << "\nPlay Again? Selecting 'No' will exit the program. (Y/N): ";
std::string input;
std::cin >> input;
if(input.size() > 1){
valid = false;
std::cout << "\nInvalid Input.\n";
continue;
}
switch(input[0]){
case 'y':
valid = true;
playAgain = true;
cleanupRound();
valid = true;
break;
case 'Y':
valid = true;
playAgain = true;
cleanupRound();
valid = true;
break;
case 'n':
std::cout << "\nNow exiting.\n\n";
exit(0);
case 'N':
std::cout << "\nNow exiting.\n\n";
exit(0);
default:
valid = false;
std::cout << "\nInvalid Input.\n";
break;
}
}while(!valid);
system("cls");
return valid;
}
/*
@cleanupRound
Clean the player & dealer hands in anticipation of a new round.
*/
const void Game::cleanupRound()
{
dealerStands = false, dealerBusted = false, doubledDown = false, splitHand = false;
player.resetAllHands();
dealer.resetHand(0);
++round_counter;
insurance_amount = 0;
}
/*
@setPlayerStands
Set the player's currently in use hand of cards to the value of @param stand (i.e. the hand is finalized)
*/
const void Game::setPlayerStands(const bool stand)
{
player.setHandStandStatus(current_hand, stand);
}
/*
@getPlayerStands
Get the "Stand" status of the player's currently in use hand of cards
*/
const bool Game::getPlayerStands() const
{
return player.getHandStandStatus(current_hand);
} | true |
f09ddd5c88aac5c5febc27179b510abe9622fe0e | C++ | LeverImmy/Codes | /比赛/2019暑假中山纪念中学模拟测/2019.08.07【NOIP提高组】模拟 B 组/T2 排序/未命名1.cpp | GB18030 | 4,906 | 2.734375 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
#include <cctype>
#include <algorithm>
#define ll long long
#define il inline
#define rgi register int
using namespace std;
const int N = 100000 + 10;
int n;
int a[N], rev[N];
int Less[N], Greater[N];
struct Seg_Tree
{
int lc, rc;
int val, add;
} t[N << 2], L[N << 2], G[N << 2];
il int read()
{
rgi x = 0, f = 0, ch;
while(!isdigit(ch = getchar())) f |= ch == '-';
while(isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
return f ? -x : x;
}
void Update(int p)
{
t[p].val = t[p << 1].val + t[p << 1 | 1].val;
}
void Update_Less(int p)
{
L[p].val = L[p << 1].val + L[p << 1 | 1].val;
}
void Update_Greater(int p)
{
G[p].val = G[p << 1].val + G[p << 1 | 1].val;
}
void Build(int p, int l, int r)
{
t[p].lc = l, t[p].rc = r;
if(l == r)
{
t[p].val = 0;
return;
}
int mid = l + r >> 1;
Build(p << 1, l, mid);
Build(p << 1 | 1, mid + 1, r);
Update(p);
}
void Build_Less(int p, int l, int r)
{
L[p].lc = l, L[p].rc = r;
if(l == r)
{
L[p].val = Less[l];
return;
}
int mid = l + r >> 1;
Build_Less(p << 1, l, mid);
Build_Less(p << 1 | 1, mid + 1, r);
Update_Less(p);
}
void Build_Greater(int p, int l, int r)
{
G[p].lc = l, G[p].rc = r;
if(l == r)
{
G[p].val = Greater[l];
return;
}
int mid = l + r >> 1;
Build_Greater(p << 1, l, mid);
Build_Greater(p << 1 | 1, mid + 1, r);
Update_Greater(p);
}
void Spread(int p)
{
if(t[p].add != 0)
{
t[p << 1].add += t[p].add;
t[p << 1 | 1].add += t[p].add;
t[p << 1].val += t[p].add * (t[p << 1].rc - t[p << 1].lc + 1);
t[p << 1 | 1].val += t[p].add * (t[p << 1 | 1].rc - t[p << 1 | 1].lc + 1);
t[p].add = 0;
}
}
void Spread_Less(int p)
{
if(L[p].add != 0)
{
L[p << 1].add += L[p].add;
L[p << 1 | 1].add += L[p].add;
L[p << 1].val += L[p].add * (L[p << 1].rc - L[p << 1].lc + 1);
L[p << 1 | 1].val += L[p].add * (L[p << 1 | 1].rc - L[p << 1 | 1].lc + 1);
L[p].add = 0;
}
}
void Spread_Greater(int p)
{
if(G[p].add != 0)
{
G[p << 1].add += G[p].add;
G[p << 1 | 1].add += G[p].add;
G[p << 1].val += G[p].add * (G[p << 1].rc - G[p << 1].lc + 1);
G[p << 1 | 1].val += G[p].add * (G[p << 1 | 1].rc - G[p << 1 | 1].lc + 1);
G[p].add = 0;
}
}
void Add(int p, int l, int r, int val)
{
if(l <= t[p].lc && t[p].rc <= r)
{
t[p].add += val;
t[p].val += val * (t[p].rc - t[p].lc + 1);
return;
}
Spread(p);
int mid = t[p].lc + t[p].rc >> 1;
if(l <= mid)
Add(p << 1, l, r, val);
if(mid < r)
Add(p << 1 | 1, l, r, val);
Update(p);
}
void Add_Less(int p, int l, int r, int val)
{
if(l <= L[p].lc && L[p].rc <= r)
{
L[p].add += val;
L[p].val += val * (L[p].rc - L[p].lc + 1);
return;
}
Spread_Less(p);
int mid = L[p].lc + L[p].rc >> 1;
if(l <= mid)
Add_Less(p << 1, l, r, val);
if(mid < r)
Add_Less(p << 1 | 1, l, r, val);
Update_Less(p);
}
void Add_Greater(int p, int l, int r, int val)
{
if(l <= G[p].lc && G[p].rc <= r)
{
G[p].add += val;
G[p].val += val * (G[p].rc - G[p].lc + 1);
return;
}
Spread_Greater(p);
int mid = G[p].lc + G[p].rc >> 1;
if(l <= mid)
Add_Greater(p << 1, l, r, val);
if(mid < r)
Add_Greater(p << 1 | 1, l, r, val);
Update_Greater(p);
}
int Query(int p, int l, int r)
{
if(l <= t[p].lc && t[p].rc <= r)
return t[p].val;
Spread(p);
int mid = t[p].lc + t[p].rc >> 1;
int res = 0;
if(l <= mid)
res += Query(p << 1, l, r);
if(mid < r)
res += Query(p << 1 | 1, l, r);
return res;
}
int Query_Less(int p, int l, int r)
{
if(l <= L[p].lc && L[p].rc <= r)
return L[p].val;
Spread_Less(p);
int mid = L[p].lc + L[p].rc >> 1;
int res = 0;
if(l <= mid)
res += Query_Less(p << 1, l, r);
if(mid < r)
res += Query_Less(p << 1 | 1, l, r);
return res;
}
int Query_Greater(int p, int l, int r)
{
if(l <= G[p].lc && G[p].rc <= r)
return G[p].val;
Spread_Greater(p);
int mid = G[p].lc + G[p].rc >> 1;
int res = 0;
if(l <= mid)
res += Query_Greater(p << 1, l, r);
if(mid < r)
res += Query_Greater(p << 1 | 1, l, r);
return res;
}
int main()
{
n = read();
Build(1, 1, n);
for(rgi i = 1; i <= n; ++i)
{
a[i] = read();
rev[a[i]] = i;
}
for(rgi i = n; i >= 1; --i)
{
Less[i] = Query(1, 1, a[i] - 1);
Add(1, a[i], a[i], 1);
}
Build_Less(1, 1, n);//Less:Сĸ
/*
for(rgi i = 1; i <= n; ++i)
printf("%d ", Less[i]);
puts("");*/
Build(1, 1, n);
for(rgi i = 1; i <= n; ++i)
{
Greater[i] = Query(1, a[i] + 1, n);
Add(1, a[i], a[i], 1);
}
Build_Greater(1, 1, n);//Greater:ǰĸ
/*
for(rgi i = 1; i <= n; ++i)
printf("%d ", Greater[i]);
puts("");*/
for(rgi i = 1; i <= n; ++i)
{
if(i & 1)
{
int pos = i + 1 >> 1;
printf("%d\n", Query_Greater(1, rev[pos], rev[pos]));
Add_Less(1, 1, rev[pos] - 1, -1);
}
else
{
int pos = n - (i >> 1) + 1;
printf("%d\n", Query_Less(1, rev[pos], rev[pos]));
Add_Greater(1, rev[pos] + 1, n, -1);
}
}
return 0;
}
| true |
6b9cbb8119bf5635d572eafad57b2bd5b20fa843 | C++ | minorleaguegrayonassociates/GrayonSlam | /app/src/utils/parser.cpp | UTF-8 | 2,957 | 3.4375 | 3 | [] | no_license | #include <fstream>
#include <sstream>
#include <iostream>
#include "parser.hpp"
#include "exceptions.hpp"
std::vector<std::vector<std::string>> loadData(const std::string& path)
{
// Initializing - vector will hold all lines of data within the document
std::vector<std::vector<std::string>> allRows;
std::ifstream infile(path);
if(path.substr(path.size()-4) != ".csv"){throw BadFileFormat(QString::fromUtf8("Wrong File type\n"), QString::fromStdString(path));}
// Checks if file is open if not throw error
if (!infile.is_open()){throw BadFile(QFile(QString::fromStdString(path)));}
std::string line;
while (!infile.eof())
{
std::getline(infile, line);
if (line.empty() || line.front() == '#' || line.front() == ' '){continue;}
std::vector<std::string> columns;
// used for seperating words
std::stringstream row(line);
std::string word;
while (getline(row, word, ',')) //Extract until a comma
{
if(word.front() == '\"')
{
word.erase(0, 1); //Erase quotation mark
std::string extra;
bool finish = false;
do
{
std::getline(row, extra, ','); //Extra until a comma
if(extra.back() == '\"')
{
extra.erase(extra.size() - 1, 1); //Remove quotation mark at the end
finish = true;
}
word += ',' + extra;
} while(!finish);
}
columns.push_back(word);
}
if(!columns.empty()){allRows.push_back(columns);}
}
infile.close();
if (allRows.empty())
{
throw BadFileFormat(QString::fromUtf8("Empty file!\n"), QString::fromStdString(path));
}
return allRows;
}
void saveData(const std::string& path, const std::vector<std::vector<std::string>>& allRows)
{
// Creating a ofstream object that opens outfile with the given path
std::ofstream outfile(path);
// Check if path file extension matches expected file extension
if(path.substr(path.size()-4) != ".csv"){throw BadFileFormat(QString::fromUtf8("Wrong File type\n"), QString::fromStdString(path));}
// If file doesn't open throw BadFile error
if (!outfile.is_open()){throw BadFile(QFile(QString::fromStdString(path)));}
for(std::vector<std::string> columns: allRows)
{
/* Output first column before entering loop, first column doesn't need a comma preceding it, erase first column */
outfile << columns.front();
columns.erase(columns.begin());
for(const std::string& column: columns)
{
/* Output each column with a comma preceding it */
outfile << "," << column;
}
// Add a new line
outfile << std::endl;
}
// Close outfile
outfile.close();
}
| true |
b5fef0d50bb64cd5702d17c9abcf44ad25d78030 | C++ | emprice/cyvtk | /unstructuredGrid.cc | UTF-8 | 3,699 | 2.609375 | 3 | [
"MIT"
] | permissive | #include <unstructuredGrid.hh>
#include <vtkPoints.h>
#include <vtkCellData.h>
#include <vtkPointData.h>
#include <vtkDoubleArray.h>
#include <vtkXMLUnstructuredGridWriter.h>
#include <string>
#include <sstream>
UnstructuredGrid::UnstructuredGrid(double *x, double *y, double *z, size_t N)
{
// initialize a new grid object
grid = vtkUnstructuredGrid::New();
// allocate memory for all points
vtkPoints *points = vtkPoints::New();
points->SetNumberOfPoints(N);
// loop needs to be in fortran order (first index varies fastest, last
// index varies slowest) for vtk to be happy
for (size_t idx = 0; idx < N; ++idx)
{
points->SetPoint(idx, x[idx], y[idx], z[idx]);
}
// attach the points to the grid
grid->SetPoints(points);
// clean up memory
points->Delete();
}
UnstructuredGrid::~UnstructuredGrid()
{
// clean up memory
grid->Delete();
}
void UnstructuredGrid::addScalarCellData(const char *name, const double *data)
{
vtkDoubleArray *xyz = vtkDoubleArray::New();
xyz->SetName(name);
xyz->SetNumberOfComponents(1);
size_t numCells = grid->GetNumberOfCells();
xyz->SetNumberOfTuples(numCells);
for (size_t idx = 0; idx < numCells; ++idx)
xyz->SetTuple1(idx, data[idx]);
grid->GetCellData()->AddArray(xyz);
xyz->Delete();
}
void UnstructuredGrid::addVectorCellData(const char *name, const double *dataX,
const double *dataY, const double *dataZ)
{
vtkDoubleArray *xyz = vtkDoubleArray::New();
xyz->SetName(name);
xyz->SetNumberOfComponents(3);
size_t numCells = grid->GetNumberOfCells();
xyz->SetNumberOfTuples(numCells);
for (size_t idx = 0; idx < numCells; ++idx)
xyz->SetTuple3(idx, dataX[idx], dataY[idx], dataZ[idx]);
grid->GetCellData()->AddArray(xyz);
xyz->Delete();
}
void UnstructuredGrid::addScalarPointData(const char *name, const double *data)
{
vtkDoubleArray *xyz = vtkDoubleArray::New();
xyz->SetName(name);
xyz->SetNumberOfComponents(1);
size_t numPoints = grid->GetNumberOfPoints();
xyz->SetNumberOfTuples(numPoints);
for (size_t idx = 0; idx < numPoints; ++idx)
xyz->SetTuple1(idx, data[idx]);
grid->GetPointData()->AddArray(xyz);
xyz->Delete();
}
void UnstructuredGrid::addVectorPointData(const char *name, const double *dataX,
const double *dataY, const double *dataZ)
{
vtkDoubleArray *xyz = vtkDoubleArray::New();
xyz->SetName(name);
xyz->SetNumberOfComponents(3);
size_t numPoints = grid->GetNumberOfPoints();
xyz->SetNumberOfTuples(numPoints);
for (size_t idx = 0; idx < numPoints; ++idx)
xyz->SetTuple3(idx, dataX[idx], dataY[idx], dataZ[idx]);
grid->GetPointData()->AddArray(xyz);
xyz->Delete();
}
void UnstructuredGrid::addScalarFieldData(const char *name, const double data)
{
vtkDoubleArray *f = vtkDoubleArray::New();
f->SetName(name);
f->SetNumberOfTuples(1);
f->SetTuple1(0, data);
grid->GetFieldData()->AddArray(f);
f->Delete();
}
void UnstructuredGrid::writeToFile(const char *prefix)
{
// create a new writer
vtkXMLUnstructuredGridWriter *writer = vtkXMLUnstructuredGridWriter::New();
// construct the filename from the given prefix and default extension
std::ostringstream oss;
oss << std::string(prefix) << "." << writer->GetDefaultFileExtension();
writer->SetFileName(oss.str().c_str());
// attach the grid to the writer
#if VTK_MAJOR_VERSION <= 5
writer->SetInput(grid);
#else
writer->SetInputData(grid);
#endif
// write the file and clean up
writer->Write();
writer->Delete();
}
// vim: set syntax=cpp.doxygen:
| true |
0b7f706032b3963010ee7a45b9b517922ea42c1e | C++ | MarcGroef/CSVM | /SvmCodeMarco/PYTHON_OPT_CLASSIFICATION_SVM/SVM/utils.cpp | UTF-8 | 2,346 | 3.453125 | 3 | [] | no_license | /* input: line
output: array of words, function returns amount of words
ALLOCATES MEMORY NEEDS malloc.h
The amount of words in the line should not exceed MAX_WORDS
*/
#include <cstdlib>
#include <math.h>
#include <limits.h>
#include <stdio.h>
#include "utils.h"
#define MAX_WORDS 10000
using namespace std;
/* extract all words from a line */
word_list line_to_words(char *line) {
int i, j;
int read;
int word_length[MAX_WORDS];
word_list words;
/* initialization */
for (i=0; i<MAX_WORDS; i++)
word_length[i] = 0;
i=0;
words.number_of_words = 0;
/* first pass: calculate the amount of words and the word length
needed to allocate memory */
while (line[i] != '\n') {
read = 0;
while (((line[i] == ' ') || (line[i] == '\t') || (line[i] == ','))
&& (line[i] != '\n')) /* ignore blanks and tabs */
i++;
while ((line[i] != ' ') && (line[i] != '\t') && (line[i] != ',')
&& (line[i] != '\n')) { /* calculate word length */
word_length[words.number_of_words]++;
i++;
read = 1; /* needed in order to ignore blanks at the end of a line */
}
if (read == 1) {
words.number_of_words++;
}
}
/* memory allocation */
if (NULL == (words.word
= (char **) calloc(words.number_of_words, sizeof(char*)))) {
printf("line_to_words: Could not allocate memory...\n");
//exit(1);
}
for (i=0; i<words.number_of_words; i++)
if (NULL == (words.word[i]
= (char *) calloc(word_length[i]+1, sizeof(char)))) {
printf("line_to_words: Could not allocate memory...\n");
//exit(1);
}
/* reinitialization */
i=0;
words.number_of_words = 0;
/* second pass: extract the words */
while (line[i] != '\n') {
read = 0;
while (((line[i] == ' ') || (line[i] == '\t') || (line[i] == ','))
&& (line[i] != '\n')) /* ignore blanks and tabs */
i++;
j = 0;
while ((line[i] != ' ') && (line[i] != '\t') && (line[i] != ',')
&& (line[i] != '\n')) { /* extract word */
words.word[words.number_of_words][j] = line[i];
i++;
j++;
read = 1; /* needed in order to ignore blanks at the end of a line */
}
if (read == 1) {
words.word[words.number_of_words][j] = '\0';
words.number_of_words++;
}
}
return(words);
} /* line_to_words */
| true |
2b559bb58e89452f358f35c7f2e0a0a15ef4525a | C++ | yazici/MinecraftD3D | /Coursework/DirectSound.cpp | UTF-8 | 2,944 | 2.59375 | 3 | [] | no_license | #include "DirectSound.h"
DirectSound::DirectSound()
{
m_directSound = 0;
m_listenerBuffer = 0;
m_listener = 0;
}
DirectSound::DirectSound(const DirectSound& other)
{
}
DirectSound::~DirectSound()
{
}
bool DirectSound::initialise(HWND hwnd)
{
HRESULT result;
DSBUFFERDESC bufferDesc;
WAVEFORMATEX waveFormat;
//==========================
// initialise DirectAudioClip
//==========================
// initialise the direct sound interface pointer for the default sound device.
result = DirectSoundCreate8(NULL, &m_directSound, NULL);
if (FAILED(result))
{
return false;
}
// set the cooperative level to priority so the format of the primary sound buffer can be modified.
result = m_directSound->SetCooperativeLevel(hwnd, DSSCL_PRIORITY);
if (FAILED(result))
{
return false;
}
//=============================
// create Listener Description
//=============================
// setup the primary buffer description.
bufferDesc.dwSize = sizeof(DSBUFFERDESC);
bufferDesc.dwFlags = DSBCAPS_PRIMARYBUFFER | DSBCAPS_CTRLVOLUME | DSBCAPS_CTRL3D;
bufferDesc.dwBufferBytes = 0;
bufferDesc.dwReserved = 0;
bufferDesc.lpwfxFormat = NULL;
bufferDesc.guid3DAlgorithm = GUID_NULL;
// get control of the primary sound buffer on the default sound device.
result = m_directSound->CreateSoundBuffer(&bufferDesc, &m_listenerBuffer, NULL);
if (FAILED(result))
{
return false;
}
// setup the format of the primary sound bufffer.
// In this case it is a .WAV file recorded at 44,100 samples per second in 16-bit stereo (cd audio format).
waveFormat.wFormatTag = WAVE_FORMAT_PCM;
waveFormat.nSamplesPerSec = 44100;
waveFormat.wBitsPerSample = 16;
waveFormat.nChannels = 2;
waveFormat.nBlockAlign = (waveFormat.wBitsPerSample / 8) * waveFormat.nChannels;
waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
waveFormat.cbSize = 0;
// set the primary buffer to be the wave format specified.
result = m_listenerBuffer->SetFormat(&waveFormat);
if (FAILED(result))
{
return false;
}
// Obtain a listener interface.
result = m_listenerBuffer->QueryInterface(IID_IDirectSound3DListener8, (LPVOID*)&m_listener);
if (FAILED(result))
{
return false;
}
// set the position of the listener
setListenerPosition(D3DXVECTOR3(0.0f, 0.0f, 0.0f));
return true;
}
void DirectSound::terminate()
{
// Release the listener interface.
if (m_listener)
{
m_listener->Release();
m_listener = 0;
}
// Release the primary sound buffer pointer.
if (m_listenerBuffer)
{
m_listenerBuffer->Release();
m_listenerBuffer = 0;
}
// Release the direct sound interface pointer.
if (m_directSound)
{
m_directSound->Release();
m_directSound = 0;
}
return;
}
void DirectSound::setListenerPosition(D3DXVECTOR3 Position)
{
m_listener->SetPosition(Position.x, Position.y, Position.z, DS3D_IMMEDIATE);
}
IDirectSound8* DirectSound::getDirectSound()
{
return m_directSound;
} | true |
74400dc501e3366df1b67e54f4740873d68d13d2 | C++ | emaha/SFML2 | /SFML2/Game.cpp | WINDOWS-1251 | 4,556 | 2.640625 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <SFML/Graphics.hpp>
#include <SFML/Network.hpp>
#include "Game.h"
#include "Constants.h"
#include "ObjectManager.h"
#include "NetworkClient.h"
Game::Game() : running(true)
{
networkClient = new NetworkClient();
}
Game::~Game()
{
window.close();
}
void Game::createWindow()
{
if (window.isOpen())
window.close();
window.create(sf::VideoMode(APP_WIDTH, APP_HEIGHT), APP_TITLE, sf::Style::Default);
window.setKeyRepeatEnabled(true);
//window.setFramerateLimit(APP_FPS);
}
void Game::run()
{
createWindow();
Clock clock;
networkClient->doConnect();
while (window.isOpen())
{
float time = clock.getElapsedTime().asMilliseconds();
if (time >= 1000 / 60)
{
clock.restart();
window.clear();
//time /= 1000.0f;
checkEvents(window, time);
update(time);
draw(window);
window.display();
}
}
}
void Game::update(float time)
{
level.update(time);
networkClient->update(time);
ObjectManager::getInstance()->update(time);
hud.update(time);
Player::getInstance()->Update(time, Mouse::getPosition(window));
}
void Game::draw(RenderTarget &target)
{
level.draw(window);
ObjectManager::getInstance()->draw(window);
Player::getInstance()->Draw(window);
hud.draw(window);
}
void Game::checkEvents(RenderWindow &window, float time) const
{
Event event;
while (window.pollEvent(event))
{
switch (event.type)
{
case Event::Closed:
{
window.close();
networkClient->socket->disconnect();
break;
}
case Event::KeyPressed:
{
if (Keyboard::isKeyPressed(Keyboard::Num1))
{
if (Player::getInstance()->isSkillAvailable(0))
{
Packet packet;
packet << Action::UseSkill << Player::getInstance()->id << Skill::ShieldWall;
networkClient->sendPacket(packet);
cout << "Skill 1 used" << endl;
}
}
if (Keyboard::isKeyPressed(Keyboard::Num2))
{
if (Player::getInstance()->isSkillAvailable(1))
{
Packet packet;
packet << Action::UseSkill << Player::getInstance()->id << Skill::Cure;
networkClient->sendPacket(packet);
cout << "Skill 2 used" << endl;
}
}
break;
}
case Event::KeyReleased:
{
break;
}
default:
break;
}
}
if (Player::getInstance()->isAlive())
{
if (Mouse::isButtonPressed(Mouse::Left))
{
if (Player::getInstance()->isFire())
{
Vector2i mousePos = Mouse::getPosition(window);
// ))))
mousePos.y += rand() % 20 - 10;
mousePos.x += rand() % 20 - 10;
//
Vector2f vector = Vector2f(mousePos) - Player::getInstance()->position + Player::getInstance()->viewportOffset;
float lenght = sqrt(vector.x * vector.x + vector.y * vector.y);
Vector2f normVelocity(vector.x / lenght, vector.y / lenght);
//ObjectManager::getInstance()->addBullet(Player::getInstance()->id, Player::getInstance()->position, normVelocity);
Packet packet;
packet << Action::Shot << Player::getInstance()->id << Player::getInstance()->position.x
<< Player::getInstance()->position.y << normVelocity.x << normVelocity.y;
networkClient->sendPacket(packet);
}
}
if (Keyboard::isKeyPressed(Keyboard::W)) { Player::getInstance()->position.y -= Player::getInstance()->speed * time; }
if (Keyboard::isKeyPressed(Keyboard::S)) { Player::getInstance()->position.y += Player::getInstance()->speed * time; }
if (Keyboard::isKeyPressed(Keyboard::A)) { Player::getInstance()->position.x -= Player::getInstance()->speed * time; }
if (Keyboard::isKeyPressed(Keyboard::D)) { Player::getInstance()->position.x += Player::getInstance()->speed * time; }
/* //
if (Keyboard::isKeyPressed(Keyboard::A)) { Player::getInstance()->direction.x -= 0.1f * time; }
if (Keyboard::isKeyPressed(Keyboard::D)) { Player::getInstance()->direction.x += 0.1f * time; }
if (Keyboard::isKeyPressed(Keyboard::W))
{
Vector2f forwardVector(sin(Player::getInstance()->direction.x * DEG2RAD), -cos(Player::getInstance()->direction.x * DEG2RAD));
Player::getInstance()->position += forwardVector * 0.2f * time;
}
if (Keyboard::isKeyPressed(Keyboard::S))
{
Vector2f forwardVector(sin(Player::getInstance()->direction.x * DEG2RAD), -cos(Player::getInstance()->direction.x * DEG2RAD));
Player::getInstance()->position -= forwardVector * 0.2f * time;
}
*/
}
else
{
if (Keyboard::isKeyPressed(Keyboard::Space)){}
}
}
| true |
622c7ee27368074544a2c2fdc1ab702e0c487e78 | C++ | incarnadined/reg_parse_v2 | /src/FastLeaf.cpp | UTF-8 | 845 | 2.953125 | 3 | [] | no_license | #include "FastLeaf.h"
FastLeaf::FastLeaf(std::ifstream* fs, unsigned int offset)
{
Helper::Read(fs, 0x1000 + offset, sizeof(int), &m_size);
Helper::Read(fs, 0x1000 + offset + 0x4, sizeof(short), &m_signature);
Helper::Read(fs, 0x1000 + offset + 0x6, sizeof(short), &m_entries_count);
// if the signature is not 'lf' (26732) something has gone wrong
if (m_signature != 26732)
{
throw;
}
// read the pointers (4 bytes) and name hints (first 4 chars of name) for each key
pointers = new unsigned int[m_entries_count];
hints = new unsigned int[m_entries_count];
for (int i = 0; i < m_entries_count; i++)
{
Helper::Read(fs, 0x1000 + offset + 0x8 + (i * 8), sizeof(int), &pointers[i]);
Helper::Read(fs, 0x1000 + offset + 0xC + (i * 8), sizeof(int), &hints[i]);
}
}
FastLeaf::~FastLeaf()
{
delete[] pointers;
delete[] hints;
}
| true |
610d38f5b5d301b6873c4c5207686833fc96bca9 | C++ | vadim-cherepanov/monkeyrooms | /main.cpp | UTF-8 | 1,902 | 2.890625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
#include "monkeyrooms.h"
#include "timer.h"
using namespace std;
vector<MonkeyRooms> vpMonkeyRooms;
void printMonkeyRoomsStatistics(const MonkeyRooms &monkeyRooms, const string& sAdditionalInfo = "") {
uint32_t iChecksNumber = monkeyRooms.getChecksNumber();
cout << "Rooms # " << monkeyRooms.getRoomsNumber()
<< " Days # " << (iChecksNumber == -1u ? "+oo" : to_string(iChecksNumber))
<< " Solutions # " << monkeyRooms.getSolutionsNumber()
<< "\t" << sAdditionalInfo
<< endl;
}
uint32_t askNumber(const string &sMessage) {
uint32_t iAnswer;
cout << sMessage;
cin >> iAnswer;
return iAnswer;
}
bool askNY(const string &sMessage) {
string sAnswer;
cout << sMessage;
cin >> sAnswer;
return (sAnswer == "y" || sAnswer == "Y");
}
int main() {
uint32_t iChecksNumber = askNumber("Maximum number of room checks per day: ");
if (!iChecksNumber) return 0;
bool bAnyMoves = iChecksNumber > 1u && !askNY("Require all checked rooms to be different? ");
bool bCircular = askNY("Circular? ");
uint32_t iMax = 1u;
Timer timer;
while (true) {
double dStart = timer.getSeconds();
vpMonkeyRooms.emplace_back(MonkeyRooms(iMax, bCircular, iChecksNumber, bAnyMoves));
double dSpan = timer.getSeconds() - dStart;
printMonkeyRoomsStatistics(vpMonkeyRooms[iMax - 1], "| " + timer.secondsToString(dSpan) + " sec ");
if (dSpan > 3.3) break;
++iMax;
}
cout << "Total time: " << timer.getSecondsString() << " sec" << endl;
//*
while (true) {
uint32_t n = askNumber("Show all solutions for Rooms # ");
if (--n >= iMax) break;
MonkeyRooms &monkeyRooms = vpMonkeyRooms.at(n);
printMonkeyRoomsStatistics(monkeyRooms);
monkeyRooms.printAllSolutions();
}
/**/
return 0;
}
| true |
879c8b26368c9ed8a9a3ad9791ea6706e56225ae | C++ | NimeshJohari02/CppProjects | /constructor(explicit call).cpp | UTF-8 | 338 | 3.109375 | 3 | [] | no_license | #include<iostream>
using namespace std;
class test
{
int a,b;
public:
test(int c,int d);
void showdata()
{
cout<<a<<endl<<b<<endl;
}
};
test::test(int c=12,int d=69)
{
a=c;
b=d;
}
int main()
{
test o1(69,699);
o1.showdata();
test o2=test(90,99);
o2.showdata();
test o3;
o3.showdata();
return 0;
}
| true |
abed1893affe1d92971dd6478e8c5daa4fecd677 | C++ | Chainsawkitten/Deathcap | /src/Video/Geometry/Geometry2D.hpp | UTF-8 | 2,022 | 2.59375 | 3 | [
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-public-domain"
] | permissive | #pragma once
#include <GL/glew.h>
#include <glm/glm.hpp>
namespace Video {
namespace Geometry {
/// Interface for renderable 2D geometry.
class Geometry2D {
public:
/// A vertex point.
struct Vertex {
/// Position.
glm::vec2 position;
/// %Texture coordinate.
glm::vec2 textureCoordinate;
};
/// Destructor
virtual ~Geometry2D();
/// Get all the vertices.
/**
* @return Array of vertices
*/
virtual Vertex* GetVertices() const = 0;
/// Get the number of vertices.
/**
* @return The number of vertices
*/
virtual unsigned int GetVertexCount() const = 0;
/// Get all the vertex indices.
/**
* @return Array of vertex indices
*/
virtual unsigned int* GetIndices() const = 0;
/// Get the number of indicies.
/**
* @return The number of vertex indices.
*/
virtual unsigned int GetIndexCount() const = 0;
/// Get the vertex array.
/**
* @return The vertex array
*/
GLuint GetVertexArray() const;
protected:
/// Generate vertex and index buffers.
void GenerateBuffers();
/// Generate vertex array.
void GenerateVertexArray();
private:
GLuint vertexBuffer;
GLuint indexBuffer;
GLuint vertexArray;
};
}
}
| true |
55f85f97014cc23e6511de80ae8befd512a412ac | C++ | turesnake/leetPractice | /src/_leetcode/leet_322.cpp | UTF-8 | 2,814 | 3.0625 | 3 | [
"MIT"
] | permissive | /*
* ====================== leet_322.cpp ==========================
* -- tpr --
* CREATE -- 2020.06.16
* MODIFY --
* ----------------------------------------------------------
* 322. 零钱兑换
*/
#include "innLeet.h"
namespace leet_322 {//~
// 可以是 dp,类似 背包问题
// 也可以是 回溯
// 回溯解法 这个方案 目测会超时 .....
class S{
bool isFind {false};
int minNum {INT_MAX};
std::vector<int> *coinsp {nullptr};
int Nc {};
// idx 当前能使用的 最大值
// leftNum 还需要分配的值
// deep 分配次数
void work( int idx, int leftNum, int deep ){
deep++;
for( int i=idx; i<Nc; i++ ){// 从大到小
int curCoin = coinsp->at(i);
if( curCoin == leftNum ){
if( !isFind ){ isFind=true; }
minNum = std::min(minNum, deep);
return;
}else if( curCoin > leftNum ){
continue;
}else{// <
work( i, leftNum-curCoin, deep );
}
}
}
public:
int coinChange( std::vector<int>& coins, int amount ){
if( amount==0 ){
return coins.empty() ? -1 : 0;
}else{
if( coins.empty() ){ return -1; }
}
std::sort( coins.begin(), coins.end(), std::greater<int>{} );
coinsp = &coins;
Nc = static_cast<int>(coins.size());
work( 0, amount, 0 );
return isFind ? minNum : -1;
}
};
// dp 10%, 11%
// 背包dp 的本质是 一维的!!!
class S2{
public:
int coinChange( std::vector<int>& coins, int amount) {
if( amount==0 ){
return coins.empty() ? -1 : 0;
}else{
if( coins.empty() ){ return -1; }
}
std::vector<int> dp ( amount+1, 0);// 到达本格,消耗的最少硬币数
// dp[0]=0;
for( int n=1; n<=amount; n++ ){
int mmin = INT_MAX;
bool isFind = false;
for( int i : coins ){// each coin
if( i<=0 ){ continue; }
int iOff = n-i;
if( iOff<0 ){ continue; }
if( dp[iOff]==-1 ){ continue; }
if( !isFind ){ isFind=true; }
mmin = std::min( mmin, dp.at(iOff) );
}
dp[n] = isFind ? (mmin+1) : -1;
}
//cout<<"dp:"<<endl; for( int i : dp ){ cout<<i<<", "; }cout<<endl;
return dp[amount];
}
};
//=========================================================//
void main_(){
std::vector<int> v { 0 };
cout<<S2{}.coinChange( v, 11 )<<endl;
debug::log( "\n~~~~ leet: 322 :end ~~~~\n" );
}
}//~
| true |
26b9c6ec185c8b407c42a9208f730d3c2301aacf | C++ | vaish-agarwal/c- | /lab5_q9.cpp | UTF-8 | 228 | 3.015625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
//declare the variables
int a,b;
//print the odd numbers less than 100 using while loop
a =0;
while(a<50){
b = ((2*a)+1);
a++;
cout<<b<<endl;
}
return 0;
}
| true |
a01721441b5bfe821faa29fc9a8eb1d112796146 | C++ | shumin215/misc | /algorithm/dijkstra/src/main.cpp | UTF-8 | 6,490 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <queue>
#define NUM_VERTEX 8+1
#define MAX_W 9999999
using namespace std;
class Dijkstra
{
public:
Dijkstra(): visited(false), w(0), prev(0) {}
bool visited;
int w;
int prev;
};
int graph[NUM_VERTEX][NUM_VERTEX];
int dtable[NUM_VERTEX];
priority_queue<pair<int, int>> pq;
void initDtable(void)
{
for (int i=0; i<NUM_VERTEX; i++) {
dtable[i] = MAX_W;
}
}
void updateDtable(int v)
{
for (int i=1; i<NUM_VERTEX; i++) {
if (graph[v][i] > 0) {
if (dtable[i] > dtable[v] + graph[v][i]) {
dtable[i] = dtable[v] + graph[v][i];
pq.push(make_pair(dtable[i], i));
}
}
}
}
void showDtable(void)
{
for (int i=1; i<NUM_VERTEX; i++) {
printf("%d: %d\n", i, dtable[i]);
}
}
void doDijkstra(int v)
{
pq.push({0, v});
dtable[v] = 0;
while(!pq.empty()) {
int dist = pq.top().first;
int next_v = pq.top().second;
pq.pop();
if (dtable[next_v] < dist)
continue;
updateDtable(next_v);
}
showDtable();
}
void addEdge(int src, int dst, int w, bool bidirection)
{
graph[src][dst] = w;
if (bidirection) {
graph[dst][src] = w;
}
}
int main()
{
addEdge(1, 2, 3, false);
addEdge(1, 4, 2, false);
addEdge(2, 5, 9, false);
addEdge(2, 6, 4, false);
addEdge(3, 1, 7, false);
addEdge(3, 4, 9, false);
addEdge(4, 3, 25, false);
addEdge(4, 7, 18, false);
addEdge(5, 3, 10, false);
addEdge(5, 8, 4, false);
addEdge(6, 5, 8, false);
addEdge(6, 7, 10, false);
addEdge(7, 5, 7, false);
addEdge(7, 6, 5, false);
addEdge(7, 8, 3, false);
addEdge(7, 3, 2, false);
addEdge(8, 4, 3, false);
initDtable();
doDijkstra(1);
return 0;
}
#ifdef ARRAY
#include <iostream>
#define NUM_VERTEX 8+1
#define MAX_W 9999999
using namespace std;
class Dijkstra
{
public:
Dijkstra(): visited(false), w(0), prev(0) {}
bool visited;
int w;
int prev;
};
int graph[NUM_VERTEX][NUM_VERTEX];
Dijkstra dtable[NUM_VERTEX];
void initDtable(void)
{
for (int i=0; i<NUM_VERTEX; i++) {
dtable[i].visited = false;
dtable[i].w = MAX_W;
dtable[i].prev = -1;
}
}
void updateDtable(int v)
{
for (int i=1; i<NUM_VERTEX; i++) {
if (graph[v][i] > 0) {
if (!dtable[i].visited && (dtable[i].w > dtable[v].w + graph[v][i])) {
dtable[i].w = dtable[v].w + graph[v][i];
dtable[i].prev = v;
}
}
}
}
int findDijkstraNextV(void)
{
int smallest_w = MAX_W;
int smallest_v = -1;
for (int i=1; i<=NUM_VERTEX; i++) {
if (!dtable[i].visited && dtable[i].w < smallest_w) {
smallest_w = dtable[i].w;
smallest_v = i;
}
}
return smallest_v;
}
void showDtable(void)
{
for (int i=1; i<NUM_VERTEX; i++) {
printf("%d: %d %d %d\n", i, dtable[i].visited, dtable[i].w, dtable[i].prev);
}
}
void doDijkstra(int v)
{
int next_v = -1;
dtable[v].w = 0;
while((next_v = findDijkstraNextV()) != -1) {
dtable[next_v].visited = true;
updateDtable(next_v);
}
showDtable();
}
void addEdge(int src, int dst, int w, bool bidirection)
{
graph[src][dst] = w;
if (bidirection) {
graph[dst][src] = w;
}
}
int main()
{
addEdge(1, 2, 3, false);
addEdge(1, 4, 2, false);
addEdge(2, 5, 9, false);
addEdge(2, 6, 4, false);
addEdge(3, 1, 7, false);
addEdge(3, 4, 9, false);
addEdge(4, 3, 25, false);
addEdge(4, 7, 18, false);
addEdge(5, 3, 10, false);
addEdge(5, 8, 4, false);
addEdge(6, 5, 8, false);
addEdge(6, 7, 10, false);
addEdge(7, 5, 7, false);
addEdge(7, 6, 5, false);
addEdge(7, 8, 3, false);
addEdge(7, 3, 2, false);
addEdge(8, 4, 3, false);
initDtable();
doDijkstra(1);
return 0;
}
#endif
#ifdef LINKED_LIST
#include <iostream>
#define NUM_VERTEX 8+1
#define MAX_W 9999999
using namespace std;
class Node
{
public:
Node(int _v, int _w, Node *_next): v(_v), w(_w), next(_next) {}
int v;
int w;
Node *next;
};
class Dijkstra
{
public:
Dijkstra(): visited(false), w(0), prev(0) {}
bool visited;
int w;
int prev;
};
Node *graph[NUM_VERTEX];
Dijkstra dtable[NUM_VERTEX];
void initDtable(void)
{
for (int i=0; i<NUM_VERTEX; i++) {
dtable[i].visited = false;
dtable[i].w = MAX_W;
dtable[i].prev = -1;
}
}
void updateDtable(int v)
{
Node *cur = graph[v];
while(cur != nullptr) {
if (!dtable[cur->v].visited && (dtable[cur->v].w > dtable[v].w + cur->w)) {
dtable[cur->v].w = dtable[v].w + cur->w;
dtable[cur->v].prev = v;
}
cur = cur->next;
}
}
int findDijkstraNextV(void)
{
int smallest_w = MAX_W;
int smallest_v = -1;
for (int i=1; i<=NUM_VERTEX; i++) {
if (!dtable[i].visited && dtable[i].w < smallest_w) {
smallest_w = dtable[i].w;
smallest_v = i;
}
}
return smallest_v;
}
void showDtable(void)
{
for (int i=1; i<NUM_VERTEX; i++) {
printf("%d: %d %d %d\n", i, dtable[i].visited, dtable[i].w, dtable[i].prev);
}
}
void doDijkstra(int v)
{
int next_v = -1;
dtable[v].w = 0;
while((next_v = findDijkstraNextV()) != -1) {
dtable[next_v].visited = true;
updateDtable(next_v);
}
showDtable();
}
void addEdge(int src, int dst, int w, bool bidirection)
{
Node *new_node = new Node(dst, w, nullptr);
Node *cur = graph[src];
if (cur == nullptr) {
graph[src] = new_node;
} else {
while(cur->next != nullptr) {
cur = cur->next;
}
cur->next = new_node;
}
if (bidirection) {
addEdge(dst, src, w, false);
}
}
int main()
{
addEdge(1, 2, 3, false);
addEdge(1, 4, 2, false);
addEdge(2, 5, 9, false);
addEdge(2, 6, 4, false);
addEdge(3, 1, 7, false);
addEdge(3, 4, 9, false);
addEdge(4, 3, 25, false);
addEdge(4, 7, 18, false);
addEdge(5, 3, 10, false);
addEdge(5, 8, 4, false);
addEdge(6, 5, 8, false);
addEdge(6, 7, 10, false);
addEdge(7, 5, 7, false);
addEdge(7, 6, 5, false);
addEdge(7, 8, 3, false);
addEdge(7, 3, 2, false);
addEdge(8, 4, 3, false);
initDtable();
doDijkstra(1);
return 0;
}
#endif
| true |
83634fb6e47aa33c68a60f1a5a098c49b71d3234 | C++ | ZacharyJ97/File-Reader-Mapper | /Student Class/Student.cpp | UTF-8 | 1,396 | 3.40625 | 3 | [] | no_license | #include "stdafx.h"
#include "Student.h"
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <vector>
using namespace std;
//Default Student
Student::Student()
{
name = "Unknown";
stu_major = "Undecided";
stu_id = 11111111;
stu_year = "0";
}
//Overloaded/4-parameter student
Student::Student(std::string new_name, int new_id, std::string new_major, string new_year) : name(new_name), stu_major(new_major), stu_id(new_id), stu_year(new_year) {}
//Set methods for each private variable
void Student::setStudentName(const std::string &input_name)
{
name = input_name;
}
//Setter function
void Student::setStudentMajor(const std::string &input_major)
{
stu_major = input_major;
}
//Set student ID
void Student::setStudentID(int input_id)
{
stu_id = input_id;
}
//Setter function
void Student::setStudentYear(const std::string &input_year)
{
stu_year = input_year;
}
//Display formmating for the student class
string Student::display()
{
std::ostringstream stu_display;
stu_display << std::left << std::setw(20) << Student::getStudentID() << std::left << std::setw(25) << Student::getStudentName() << std::left << std::setw(20) << Student::getStudentMajor() << std::right << std::setw(5) << Student::getStudentYear() << std::endl;
string result_display = stu_display.str();
return result_display;
}
Student::~Student()
{
}
| true |
9a9673720cb9f1cd0ebc5270c6ccb94eb8358159 | C++ | dustin-thewind/cpp_sandbox | /grad/grad/grad-main.cpp | UTF-8 | 895 | 2.96875 | 3 | [] | no_license | #include "grad.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(){
string n;
double tut;
int nc;
double fees;
cout << "Enter the undergraduate students name: ";
cin >> n;
cout << "Now enter the number of classes they'll be taking: ";
cin >> nc;
cout << "Now enter the cost per course: ";
cin >> tut;
Undergraduate u1;
u1.nameset(n);
u1.setnumclasses(nc);
u1.tuitionset(tut);
u1.studentprint();
cout << "Enter the graduate students name: ";
cin >> n;
cout << "Now enter the number of classes they'll be taking: ";
cin >> nc;
cout << "Now enter the cost per course: ";
cin >> tut;
cout << "Finally, enter the student body fees: ";
cin >> fees;
Graduate g1;
g1.nameset(n);
g1.setnumclasses(nc);
g1.setfees(fees);
g1.tuitionset(tut);
g1.gettuition();
g1.studentprint();
return 0;
} | true |
460ae5c7b4ce58044ea08268d03f76a41c2b76ce | C++ | ananyapati/LiftOffC-Solutions | /week3_Q3.cpp | UTF-8 | 360 | 3.203125 | 3 | [] | no_license | #include<stdio.h>
int fun(int a,int b);
int main()
{
int n1,n2,LCM,HCF;
printf("\nEnter two numbers:");
scanf("%d %d",&n1,&n2);
HCF=fun(n1,n2);
LCM=(n1*n2)/HCF;
printf("\nGCD of the numbers is:%d",HCF);
printf("\nLCM of the numbers is:%d",LCM);
return 0;
}
int fun(int a,int b)
{
if(b==0)
return a;
else
return fun(b,a%b);
}
| true |
37b5a4f939133c06ad31f3e8d4be6b2485855064 | C++ | kverty/homeworks | /semester1/3 homework/5/sortedlist.cpp | UTF-8 | 2,016 | 3.859375 | 4 | [] | no_license | #include "sortedlist.h"
#include <iostream>
#include <cstdlib>
using namespace std;
void createList(SortedList &l)
{
ListElement *guard = new ListElement;
guard->next = nullptr;
guard->value = 0;
l.head = guard;
}
void printElement(ListElement *element)
{
if (element != nullptr)
{
cout << element->value << " ";
printElement(element->next);
}
}
void printList(SortedList &l)
{
if (l.head->next != nullptr)
{
cout << "Sorted list : " << endl;
printElement(l.head->next);
cout << endl;
}
else
{
cout << "List is empty!" << endl;
}
}
void addValue(int value, ListElement *rightPlace)
{
ListElement *newElement = new ListElement;
newElement->value = value;
newElement->next = rightPlace->next;
rightPlace->next = newElement;
}
void addValue(SortedList &l, int value)
{
ListElement *currentElement = l.head;
if (currentElement != nullptr)
{
while ((currentElement->next != nullptr) && (currentElement->next->value < value))
{
currentElement = currentElement->next;
}
}
addValue(value, currentElement);
}
void deleteAll(ListElement *element)
{
if (element != nullptr)
{
deleteAll(element->next);
delete element;
}
}
void deleteList(SortedList &l)
{
deleteAll(l.head);
l.head = nullptr;
}
void clearList(SortedList &l)
{
deleteAll(l.head->next);
l.head->next = nullptr;
}
bool removeValue(SortedList &l, int value)
{
ListElement *currentElement = l.head;
bool valueWasFound = false;
while (currentElement->next != nullptr)
{
if (currentElement->next->value == value)
{
valueWasFound = true;
ListElement *element = currentElement->next->next;
delete currentElement->next;
currentElement->next = element;
continue;
}
currentElement = currentElement->next;
}
return valueWasFound;
}
| true |