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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
0bbcb7c7cd0f2aeee5124423e555c5653d91159d | C++ | nitesh-147/Programming-Problem-Solution | /codeforces/ipay.cpp | UTF-8 | 1,824 | 3.625 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
struct node
{
int val;
node *nxt;
};
void print(node *n)
{
if(n == NULL) return;
printf("%d ", n->val);
print(n->nxt);
return;
}
void insert(node* pre, int v)
{
if((pre -> nxt) == NULL)
{
node *new_data = NULL;
new_data = (struct node*)malloc(sizeof(struct node));
new_data ->val = v;
new_data -> nxt = pre -> nxt;
pre -> nxt = new_data;
}
else
{
insert(pre->nxt, v);
}
return;
}
void deleteNode(node **head, int key)
{
node *temp = *head, *prev;
if(temp != NULL && temp -> val == key)
{
*head = temp->nxt;
free(temp);
return;
}
while(temp != NULL && temp -> val != key)
{
prev = temp;
temp = temp->nxt;
}
if(temp == NULL) return;
prev -> nxt = temp -> nxt;
free(temp);
return;
}
void insertFront(node **pre, int v)
{
node *tmp = NULL;
tmp = (struct node*)malloc(sizeof(struct node));
tmp ->val = v;
tmp -> nxt = (*pre);
(*pre) = tmp;
return;
}
int main()
{
node *fst = NULL;
node *snd = NULL;
node *third = NULL;
fst = (struct node*)malloc(sizeof (struct node));
snd = (struct node*)malloc(sizeof (struct node));
third = (struct node*)malloc(sizeof (struct node));
fst->val = 1;
fst -> nxt = NULL;
printf("here\n");
// snd->val = 2;
// snd -> nxt = third;
//
// third->val = 3;
// third -> nxt = NULL;
insert(fst, 12);
insert(fst, 13);
insert(fst, 14);
print(fst);
deleteNode(&fst, 13);
printf("\n");
print(fst);
printf("\n");
insertFront(&fst, 20);
print(fst);
printf("\n");
deleteNode(&fst, 20);
print(fst);
printf("\n");
return 0;
}
| true |
afb1b19a60f0f0c1da54580a3e7ccbb30d63dc6c | C++ | wepng/ECNU-Online-Judge | /2948.cpp | UTF-8 | 1,742 | 3.078125 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
#include <cstdlib>
#include <vector>
using namespace std;
int getNum(char c)
{
switch(c)
{
case 'A':
case 'B':
case 'C':return 2;
case 'D':
case 'E':
case 'F':return 3;
case 'G':
case 'H':
case 'I':return 4;
case 'J':
case 'K':
case 'L':return 5;
case 'M':
case 'N':
case 'O':return 6;
case 'P':
case 'Q':
case 'R':
case 'S':return 7;
case 'T':
case 'U':
case 'V':return 8;
case 'W':
case 'X':
case 'Y':
case 'Z':return 9;
}
return -1;
}
struct In
{
char num[10];
}s[110];
int cmp(const void *a , const void *b)
{
return strcmp( (*(In *)a).num , (*(In *)b).num );
}
int main()
{
int n;
char tmp[100];
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%s",tmp);
int len=strlen(tmp);
int index=0;
for(int j=0;j<len;j++)
{
if('0'<=tmp[j]&&tmp[j]<='9')
s[i].num[index++]=tmp[j];
else if('A'<=tmp[j]&&tmp[j]<='Z')
{s[i].num[index++]=getNum(tmp[j])+'0';}
}
s[i].num[index++]='\0';
}
qsort(s,n,sizeof(s[0]),cmp);
for(int i=0;i<n;i++)
{
//printf("%s\n",s[i].num);
int con=1,t=i;
for(int j=i+1;j<n;j++)
{
if(strcmp(s[i].num,s[j].num)==0)
{
con++;
i=j;
}
else
{
break;
}
}
printf("%c%c%c%c-%c%c%c%c %d\n",s[t].num[0],s[t].num[1],s[t].num[2],s[t].num[3],s[t].num[4],s[t].num[5],s[t].num[6],s[t].num[7],con);
}
return 0;
}//Parsed in 0.141 seconds
| true |
3faeeee3b75836521469c1c153b33a5f9f0f270f | C++ | ojaster/first_project | /cpp_xcode/FIrst_Project/FIrst_Project/2darray.cpp | UTF-8 | 1,226 | 2.953125 | 3 | [] | no_license | ////
//// 2darray.cpp
//// FIrst_Project
////
//// Created by Данил on 24.08.18.
//// Copyright © 2018 Daniil. All rights reserved.
////
//
//#include <iostream>
//#include <stdlib.h>
//using namespace std;
//int main(){
// int **a;//для выделения памяти под двумерный массив нам требуется "указатель на указатель"
// int n=-1;
// int m=-1;
//
// do{// этот цикл выполнится 1 раз в любом случае
// cout<<"n and m:";
// cin>>n;
// cin>>m;
// } while(n<1 || m<1);
//
//
// a = new int*[n];//выделение памяти для n строк
// for(int i=0; i<n; i++){
// a[i]= new int[m];// для каждой строки выделяем нужное количество элементов
// }
//
// for(int i=0 ;i<n; i++){
// for(int j=0 ;j<m; j++){
// a[i][j]=rand()%200;
// cout<<a[i][j]<<"\t";
//
// }
// cout<<endl;
// }
//
//
// //важно правильно очистить память
//
// for(int i=0; i<n;i++){
// delete a[i];
// }
// delete a;
//}
| true |
cee4137bddbd49f005e7fe8e99fabfff3a266221 | C++ | benesle/SpillmotorArkitektur2019 | /Sound/soundsource.cpp | UTF-8 | 4,057 | 2.765625 | 3 | [] | no_license |
#include "soundsource.h"
#include "wavefilehandler.h"
#include <sstream>
#include <iostream>
SoundSource::SoundSource(std::string name, bool loop, float gain) :
mName(name),
mSource(0),
mBuffer(0),
mPosition(0.0f, 0.0f, 0.0f),
mVelocity(0.0f, 0.0f, 0.0f)
{
alGetError();
alGenBuffers(1, &mBuffer);
checkError("alGenBuffers");
alGenSources(1, &mSource);
checkError("alGenSources");
alSourcef(mSource, AL_PITCH, 1.0f);
alSourcef(mSource, AL_GAIN, gain);
ALfloat temp[3] = {mPosition.x, mPosition.y, mPosition.z};
alSourcefv(mSource, AL_POSITION, temp);
ALfloat temp2[3] = {mVelocity.x, mVelocity.y, mVelocity.z};
alSourcefv(mSource, AL_VELOCITY, temp2);
alSourcei(mSource, AL_LOOPING, loop);
}
SoundSource::~SoundSource()
{
std::cout << "Destroying SoundSource " + mName;
stop();
alGetError();
alSourcei(mSource, AL_BUFFER, 0);
checkError("alSourcei");
alDeleteSources(1, &mSource);
checkError("alDeleteSources");
alDeleteBuffers(1, &mBuffer);
checkError("alDeleteBuffers");
}
bool SoundSource::loadWave(std::string filePath)
{
std::cout << "Loading wave file!\n";
ALuint frequency{};
ALenum format{};
wave_t* waveData = new wave_t();
if (!WaveFileHandler::loadWave(filePath, waveData))
{
std::cout << "Error loading wave file!\n";
return false; // error loading wave file data
}
frequency = waveData->sampleRate;
switch (waveData->bitsPerSample)
{
case 8:
switch (waveData->channels)
{
case 1: format = AL_FORMAT_MONO8;
std::cout << "Format: 8bit Mono\n";
break;
case 2: format = AL_FORMAT_STEREO8;
std::cout << "Format: 8bit Stereo\n";
break;
default: break;
}
break;
case 16:
switch (waveData->channels)
{
case 1: format = AL_FORMAT_MONO16;
std::cout << "Format: 16bit Mono\n";
break;
case 2: format = AL_FORMAT_STEREO16;
std::cout << "Format: 16bit Stereo\n";
break;
default: break;
}
break;
default: break;
}
if (waveData->buffer == NULL)
{
std::cout << "NO WAVE DATA!\n";
}
std::ostringstream i2s;
i2s << waveData->dataSize;
std::cout << "DataSize: " << i2s.str() << " bytes\n";
alGetError();
alBufferData(mBuffer, format, waveData->buffer, waveData->dataSize, frequency);
checkError("alBufferData");
alSourcei(mSource, AL_BUFFER, mBuffer);
checkError("alSourcei (loadWave)");
std::cout << "Loading complete!\n";
if (waveData->buffer) delete waveData->buffer;
if (waveData) delete waveData;
return true;
}
void SoundSource::play()
{
alSourcePlay(mSource);
}
void SoundSource::pause()
{
alSourcePause(mSource);
}
void SoundSource::stop()
{
alSourceStop(mSource);
}
void SoundSource::setPosition(gsl::Vector3D newPos)
{
mPosition = newPos;
ALfloat temp[3] = {mPosition.x, mPosition.y, mPosition.z};
alSourcefv(mSource, AL_POSITION, temp);
}
void SoundSource::setVelocity(gsl::Vector3D newVel)
{
mVelocity = newVel;
ALfloat temp[3] = {mVelocity.x, mVelocity.y, mVelocity.z};
alSourcefv(mSource, AL_VELOCITY, temp);
}
bool SoundSource::checkError(std::string name)
{
switch (alGetError())
{
case AL_NO_ERROR:
break;
case AL_INVALID_NAME:
std::cout << "OpenAL Error: "+name+": Invalid name!\n";
return false;
case AL_INVALID_ENUM:
std::cout << "OpenAL Error: "+name+": Invalid enum!\n";
return false;
case AL_INVALID_VALUE:
std::cout << "OpenAL Error: "+name+": Invalid value!\n";
return false;
case AL_INVALID_OPERATION:
std::cout << "OpenAL Error: "+name+": Invalid operation!\n";
return false;
case AL_OUT_OF_MEMORY:
std::cout << "OpenAL Error: "+name+": Out of memory!\n";
return false;
default: break;
}
return true;
}
| true |
b017e7420f9162f7db9809339d2e5ad58fdfdc85 | C++ | dashutaOk/lab__2 | /Sequence.h | UTF-8 | 866 | 3.359375 | 3 | [] | no_license | #pragma once
#ifndef SEQUENCE_H
#define SEQUENCE_H
template <class T> class Sequence {
public:
//Decomposition
virtual T GetFirst() = 0;//get el on first index
virtual T GetLast() = 0;//get el on last index
virtual T Get(int index) = 0;//get index of Node
virtual Sequence<T>* GetSubsequence(int startIndex, int endIndex) = 0;//get list of el
virtual int GetLength() = 0;// Length
//Operations
virtual void Append(T item) = 0; //add el at end
virtual void Prepend(T item) = 0; //add el at head
virtual void Set(T item, int index) = 0; // add el at index (replace)
virtual void InsertAt(T item, int index) = 0; //add el at index
virtual Sequence <T>* Concat(Sequence <T> *list) = 0; //concat two sequence
//operators
virtual T operator[] (int index) = 0;
};
#endif //SEQUENCE_H
| true |
5a989cd8d90671c29761617364b45a8f73a27aa1 | C++ | zVoxty/AppVox | /Server/Server/Source.cpp | UTF-8 | 473 | 2.890625 | 3 | [] | no_license | #include "Server.h"
int main()
{
bool serverCrash = false;
Server MyServer(1111, true); //Create server on port 100
for (int i = 0; i < 100; i++) //Up to 100 times...
{
MyServer.ListenForNewConnection(); //Accept new connection (if someones trying to connect)
}
serverCrash = true;
if (serverCrash == true) {
system("CLS");
std::cout << "Crash! Server is restarting in 5 seconds ! " << std::endl;
Sleep(5000);
main();
}
system("pause");
return 0;
} | true |
3d19f1cb912b1dd9e6b58aa6637dec228240ddb5 | C++ | raghumag/cpp-practice | /task_scheduler.cpp | UTF-8 | 740 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
int mp[120]={0};
int ma=0,c=0;
for(int i=0;i<tasks.size();i++)
{
mp[tasks[i]]++;
if(mp[tasks[i]]>ma)
{
ma=mp[tasks[i]];
c=1;
}
else if(mp[tasks[i]]==ma)
c++;
}
int ans=0;
ans=c+(ma-1)*(n+1);
int z=tasks.size();
ans=max(ans,z);
return ans;
}
};
int main()
{
Solution sol;
vector<char> vec{'A','A','A','A','A','B','B', 'A', 'C', 'C', 'C', 'C', 'D', 'D', 'E', 'E', 'E', 'E', 'E', 'E', 'B','B', 'B', 'B', 'C', 'C', 'D', 'D', 'D', 'D', 'F', 'F', 'F', 'F', 'F', 'F'};
int ans = sol.leastInterval(vec, 5);
cout<<"ans:"<<ans<<endl;
}
| true |
0162374009bc64e36721f7509593971b647be442 | C++ | jpvarbed/practiceproblems | /sortVector.cpp | UTF-8 | 464 | 3.265625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void print(const vector<auto> &v)
{
for (auto const& e : v)
{
cout << e << "\t";
}
cout << endl;
}
int main() {
vector<int> a{ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
vector<int> b{ 20, 18, 16, 14, 12, 10, 8, 6, 4, 2};
vector<int> c{ 19, 17, 15, 13, 11, 9, 7, 5, 3, 1};
sort(a.begin(), a.end());
sort(b.begin(), b.end());
sort(c.begin(), c.end());
print(a);
return 0;
} | true |
9439bf7bbbafcf3fff9255a49f21f3dd284ccb45 | C++ | InnocentK/Compact-QuadTrees | /back-ups_p3/2_QTNode.cpp | UTF-8 | 9,685 | 2.90625 | 3 | [
"MIT"
] | permissive | /*****************************************
** File: QTNode.cpp
** Project: CMSC 341 Project 3 - QuadTrees, Spring 2018
** Author: Innocent Kironji
** Date: 04/10/18
** Section: 03
** E-mail: wambugu1@umbc.edu
**
** This file contains the implementation of
** This class is
***********************************************/
#include "QTNode.h"
#include <iostream>
//#define QT_NUM_KIDS 4
// QTNode Constructor
QTNode::QTNode(){
unsigned int zero = 0;
unsigned int default_dim = 1;
m_child = new QTNode* [QT_NUM_KIDS];
// Initialize all pointers to NULL
for (int i = 0; i < QT_NUM_KIDS; i++)
m_child[i] = NULL;
m_point = Point(zero,zero);
m_bounds = BBox(m_point,default_dim);
m_bL = m_point;
m_data = 0;
m_num_children = 0;
}
// Overloaded Constructor
// default value of 0 for data
// For creating a new leaf node
QTNode::QTNode(const Point &pt, int data){
unsigned int default_dim = 1;
m_child = new QTNode* [QT_NUM_KIDS];
// Initialize all pointers to NULL
for (int i = 0; i < QT_NUM_KIDS; i++)
m_child[i] = NULL;
m_point = pt;
m_bounds = BBox(m_point,default_dim);
m_bL = m_point;
m_data = data;
m_num_children = 0;
}
// 2nd Overloaded Constructor
// default value of 0 for data
// For creating a new internal node
QTNode::QTNode(BBox bounds, int data){
unsigned int zero = 0;
m_child = new QTNode* [QT_NUM_KIDS];
// Initialize all pointers to NULL
for (int i = 0; i < QT_NUM_KIDS; i++)
m_child[i] = NULL;
m_point = Point(zero,zero);
m_bounds = bounds;
m_bL = m_bounds.m_bL;
m_data = data;
m_num_children = 0;
}
// Destructor
QTNode::~QTNode(){
if (m_child != NULL){
// Loops through children deleting those that exist
for (int i = 0; i < QT_NUM_KIDS; i++){
// Checks if child exists
if (m_child[i] != NULL)
delete m_child[i];
}
delete [] m_child;
m_child = NULL;
}
}
// adds a new point
// returns whether or not that point was successfully added
// Assumes the point is already initilised
// Unitialized points are handeled by QTree::add() or through recusrive
// calls of add
bool QTNode::add(const Point &pt, int data){
bool added = false;
QTNode* new_child = new QTNode(pt, data);
// Checks for dupilcates
if (m_point == pt){
m_data = data;
delete new_child;
new_child = NULL;
return added;
}
int quad = getQuad(pt);
// Adding to an empty node
if (m_child[quad] == NULL){
m_child[quad] = new_child;
m_num_children++;
added = true;
return added;
}
// Quadrant adding to is occupied
// Node is a leaf so it's data must be moved down
if (m_child[quad]->m_num_children < 1){
// Creating a new internal node to hold both points
QTNode* new_leaf = m_child[quad];
m_child[quad] = new QTNode(new_leaf->m_bounds);
m_child[quad]->m_bounds.resize(new_leaf->m_bL, pt);
// Updating memebers
m_child[quad]->m_child[0] = new_leaf;
m_child[quad]->m_num_children++;
m_child[quad]->m_child[4] = new_child;;
m_child[quad]->m_num_children++;
added = true;
return added;
}
// Recursively add into quadrant
// This is in case the point is lower in the quadrant
//if( m_child[quad].m_bounds->inBounds(pt) ){
added = m_child[quad]->add(pt, data);
// Cleaning up unsued memory
delete new_child;
new_child = NULL;
return added;
}
// removes a point
// returns whether or not that point was sucessfully removed
bool QTNode::remove(const Point &pt, bool &empty){
bool removed = false;
return 9999;
}
// finds a point
// returns whether or not the point was found
bool QTNode::find(const Point &pt, int &data){
bool found = false;
// Point looking for is the root
if (m_point == pt) {
found = true;
data = m_data;
}
// Point is not the root and root has no children
else if (m_num_children < 1)
found = false;
// Point is likely within the bounds of the root
else if (m_bounds.inBounds(pt)){
// Loops thorugh children looking for point within non-null children
for (int i = 0; i < QT_NUM_KIDS; i++){
if(m_child[i] != NULL)
found = m_child[i]->find(pt, data);
}
}
// If not within the bounds of the root the point does not exist
return found;
}
//
int QTNode::findPoints(const BBox ®ion, std::vector<Point> &found){
return 9999;
}
// Debugging function
void QTNode::dump(){
// Interior Nodes have default data of 0
if (m_data == 0)
std::cout << "[QTNode bounds=" << m_bounds << " is INTERNAL:" << m_point << m_data << std::endl;
else{
std::cout << "[QTNode bounds=" << m_bounds << " is LEAF: pt=" << m_point
<< ", data=" << m_data << "]" << std::endl;
return;
}
// Loop is recursive
for (int i = 0; i < QT_NUM_KIDS; i++){
// Tells what child is bring printed
switch(i){
case 0:
std::cout << "Botom-Left child:" << std::endl;
break;
case 1:
std::cout << "Botom-Right child:" << std::endl;
break;
case 2:
std::cout << "Top-Left child:" << std::endl;
break;
default:
std::cout << "Top-Right child:" << std::endl;
}
// Recursively prints children
if (m_child[i] != NULL)
m_child[i]->dump();
else
std::cout << "[NULL]" << std::endl;
}
std::cout << "]" << std::endl;
}
// Iterator and it's necessary methods
// Default constructor
QTNode::iterator::iterator(){
m_pos = 0;
}
// Overloaded constructor
// pos has a default value of 0
QTNode::iterator::iterator(QTNode* node, int pos){
m_pos = pos;
parent = node;
child = parent->m_child[m_pos];
}
// Checks if two iterators are equal
bool QTNode::iterator::operator==(const QTNode::iterator &other){
return child == other.child;
}
// Checks inequality from iterators
bool QTNode::iterator::operator!=(const QTNode::iterator &other){
return child != other.child;
}
// Prefix: e.g. "++it"
QTNode::iterator& QTNode::iterator::operator++(){
child = parent->m_child[++m_pos];
return *this;
}
// Postfix: "it++"
QTNode::iterator QTNode::iterator::operator++(int dummy){
QTNode::iterator temp(parent);
operator++();
//temp++;
return *temp;
}
// Derefernces an iterator
// Because iterator is applied on parent QTNode the dereference returns the child
// since the children are the ones being manipulated and iterated through
QTNode*& QTNode::iterator::operator*(){
return parent->m_child[m_pos];
}
// Returns iterator pointing to the first child
QTNode::iterator QTNode::begin(){
return iterator(this);
}
// Returns iterator pointing to the last child
QTNode::iterator QTNode::end(){
return iterator(this,3);
}
// Additional Functions to help with QTNode operations
// Adjusts the bounding boxes of two QTNodes to keep them independent
void QTNode::rescale(QTNode* other){
// When the points overlap then no rescale occurs
if( sameX(other) && sameY(other) )
return;
// Rescaling is only based on the y coordinate
else if( sameY(other) ){
if( largerX(other) ){
other->m_bounds.resize(other->m_point,Point(m_point.m_x - 1, m_point.m_y));
}
else{
m_bounds.resize(m_point,Point(other->m_point.m_x - 1, other->m_point.m_y));
}
}
// Rescaling is only based on the x coordinate
else if( sameX(other) ){
if( largerY(other) ){
other->m_bounds.resize(other->m_point,Point(m_point.m_x, m_point.m_y - 1));
}
else{
m_bounds.resize(m_point,Point(other->m_point.m_x, other->m_point.m_y - 1));
}
}
// X is definitively larger
else if( largerX(other) && largerY(other) ){
other->m_bounds.resize(other->m_point,Point(m_point.m_x - 1, m_point.m_y - 1));
}
// Current QTNode has both a smaller x and a smaller y
else{
m_bounds.resize(m_point,Point(other->m_point.m_x - 1, other->m_point.m_y - 1));
}
return;
}
// Calculates which quadrant a point should reside in current QTNode
int QTNode::getQuad(const Point &pt){
Point mid = getMid();
enum {BL, BR, TL, TR, OVERLAP};/*
const int BL = 0;
const int BR = 1;
const int TL = 2;
const int TR = 3;
const int OVERLAP = -1;*/
// Top-Right
if( (mid.m_x <= pt.m_x) && (mid.m_y <= pt.m_y) )
return TR;
// Top-Left
else if( (mid.m_x > pt.m_x) && (mid.m_y <= pt.m_y) )
return TL;
// Bottom-Right
else if( (mid.m_x <= pt.m_x) && (mid.m_y > pt.m_y) )
return BR;
// Bottom-Left
else if ( (mid.m_x > pt.m_x) && (mid.m_x > pt.m_x) )
return BL;
// Only called when both points have the same X and Y
return OVERLAP;
}
// Calculates the center of a bounds
// Returns the center as a point
Point QTNode::getMid(){
unsigned int mid_x = m_bL.m_x + (m_bounds.m_dim/2);
unsigned int mid_y = m_bL.m_y + (m_bounds.m_dim/2);
Point mid(mid_x, mid_y);
return mid;
}
// Calculates the maximum point a bounds can have
Point QTNode::getMax(){
unsigned int max_x = m_bL.m_x + m_bounds.m_dim;
unsigned int max_y = m_bL.m_y + m_bounds.m_dim;
Point max(max_x, max_y);
return max;
}
// Helper functions to compare coordinates of the QTNodes
bool QTNode::largerX(QTNode* other){
return m_bL.m_x > other->m_bL.m_x;
}
bool QTNode::largerY(QTNode* other){
return m_bL.m_y > other->m_bL.m_y;
}
bool QTNode::smallerX(QTNode* other){
return m_bL.m_x < other->m_bL.m_x;
}
bool QTNode::smallerY(QTNode* other){
return m_bL.m_y > other->m_bL.m_y;
}
bool QTNode::sameX(QTNode* other){
return m_bL.m_x == other->m_bL.m_x;
}
bool QTNode::sameY(QTNode* other){
return m_bL.m_y > other->m_bL.m_y;
}
| true |
55ca511ef7498a428edc448d62b2606e2c040dfa | C++ | Marukyu/RankCheck | /src/Client/GUI3/Rendering/Primitives/Outline.cpp | UTF-8 | 521 | 2.84375 | 3 | [
"MIT"
] | permissive | #include <Client/GUI3/Rendering/Primitives/Outline.hpp>
namespace gui3
{
namespace primitives
{
Outline::Outline(sf::FloatRect rect, float thickness, sf::Color color, int sides) :
myRect(rect),
myThickness(thickness),
myColor(color),
mySides(sides)
{
}
const sf::FloatRect& Outline::getRect() const
{
return myRect;
}
float Outline::getThickness() const
{
return myThickness;
}
sf::Color Outline::getColor() const
{
return myColor;
}
bool Outline::testSide(Sides side) const
{
return mySides & side;
}
}
}
| true |
078256c4f79b164338d0f3bcb8886c9293f72ed6 | C++ | Seongil-Shin/Algorithm | /백준/solutions/7579 app/7579 app.cpp | UTF-8 | 819 | 2.640625 | 3 | [] | no_license | #include <iostream>
#define MAX_N 100
#define MAX_MEMORY 10000000
using namespace std;
int numOfApp, a[MAX_N], c[MAX_N], m, maxValue;
int DP[105][10020];
int getMin();
int max(int a, int b) {
return a > b ? a : b;
}
int main() {
cin >> numOfApp >> m;
for (int i = 0; i < numOfApp; i++)
cin >> a[i];
for (int i = 0; i < numOfApp; i++) {
cin >> c[i];
maxValue += c[i];
}
cout << getMin();
}
int getMin(){
for (int i = 1; i <= numOfApp; i++) {
for (int j = 1; j <= maxValue; j++) {
if (c[i-1] > j)
DP[i][j] = DP[i - 1][j];
else
DP[i][j] = max(a[i-1] + DP[i - 1][j - c[i-1]], DP[i - 1][j]);
}
}
int minValue = 2000000000;
for (int i = 0; i <= numOfApp; i++) {
for (int j = 0; j <= maxValue; j++) {
if (DP[i][j] >= m && minValue > j)
minValue = j;
}
}
return minValue;
} | true |
44682e45048dea68a2be85572df593c950adc80a | C++ | BykadorovR/Engikit2D | /src/Graphic/TextureAtlas.cpp | UTF-8 | 4,010 | 2.59375 | 3 | [] | no_license | #include <algorithm>
#include <cassert>
#include "TextureAtlas.h"
TextureAtlas::TextureAtlas(GLenum fourCC, std::tuple<float, float> size) {
_size = size;
_fourCC = fourCC;
_bitDepth = 1;
if (_fourCC == GL_RGBA)
_bitDepth = 4;
glGenTextures(1, &_textureObjectId);
assert(_textureObjectId != 0);
_data.resize(std::get<0>(_size) * std::get<1>(_size) * _bitDepth);
}
bool TextureAtlas::initialize() {
glBindTexture(GL_TEXTURE_2D, _textureObjectId);
// Set texture options
glTexImage2D(GL_TEXTURE_2D, 0, _fourCC, std::get<0>(_size), std::get<1>(_size), 0, _fourCC, GL_UNSIGNED_BYTE, &_data[0]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
return false;
}
bool TextureAtlas::addTexture(std::shared_ptr<TextureRaw> texture, std::tuple<float, float> position) {
auto textureSize = texture->getRealImageSize();
auto textureData = texture->getData();
for (int y = 0; y < std::get<1>(textureSize); y++)
for (int x = 0; x < std::get<0>(textureSize) * _bitDepth; x++) {
int coordXIntoResult = std::get<0>(position) * _bitDepth + x;
int coordYIntoResult = std::get<1>(position) + y;
assert(coordXIntoResult < std::get<0>(_size) * _bitDepth);
assert(coordYIntoResult < std::get<1>(_size));
int coordIntoResult = coordXIntoResult + std::get<0>(_size) * _bitDepth * coordYIntoResult;
int coordIntoSource = x + std::get<0>(textureSize) * _bitDepth * y;
assert(coordIntoResult < std::get<0>(_size) * std::get<1>(_size) * _bitDepth);
assert(coordIntoSource < std::get<0>(textureSize) * std::get<1>(textureSize) * _bitDepth);
_data[coordIntoResult] = textureData[coordIntoSource];
}
_textures.push_back({texture, position});
texture->setTextureID(_textureCounter++);
return false;
}
bool TextureAtlas::addTextureFont(std::shared_ptr<TextureRaw> texture, std::tuple<float, float> position) {
auto textureSize = texture->getRealImageSize();
auto textureData = texture->getData();
for (int y = 0; y < std::get<1>(textureSize); y++)
for (int x = 0; x < std::get<0>(textureSize); x++) {
int coordXIntoResult = std::get<0>(position) * _bitDepth + x * _bitDepth;
int coordYIntoResult = std::get<1>(position) + y;
assert(coordXIntoResult < std::get<0>(_size) * _bitDepth);
assert(coordYIntoResult < std::get<1>(_size));
int coordIntoResult = coordXIntoResult + std::get<0>(_size) * _bitDepth * coordYIntoResult;
int coordIntoSource = x + std::get<0>(textureSize) * y;
assert(coordIntoResult < std::get<0>(_size) * std::get<1>(_size) * _bitDepth);
assert(coordIntoSource < std::get<0>(textureSize) * std::get<1>(textureSize));
for (int k = 0; k < 3; k++)
_data[coordIntoResult + k] = 255;
_data[coordIntoResult + _bitDepth - 1] = textureData[coordIntoSource];
}
_textures.push_back({ texture, position });
texture->setTextureID(_textureCounter++);
return false;
}
int TextureAtlas::getAtlasID() {
return _textureObjectId;
}
bool TextureAtlas::setAtlasID(int atlasID) {
_atlasID = atlasID;
return false;
}
std::tuple<std::shared_ptr<TextureRaw>, std::tuple<float, float> > TextureAtlas::getTexture(int textureID) {
auto textureIterator = std::find_if(_textures.begin(), _textures.end(), [textureID](std::tuple< std::shared_ptr<TextureRaw>, std::tuple<float, float> > texture) {return std::get<0>(texture)->getTextureID() == textureID; });
return *textureIterator;
}
bool TextureAtlas::containTexture(int textureID) {
auto textureIterator = std::find_if(_textures.begin(), _textures.end(), [textureID](std::tuple< std::shared_ptr<TextureRaw>, std::tuple<float, float> > texture) {return std::get<0>(texture)->getTextureID() == textureID; });
if (textureIterator != _textures.end())
return true;
return false;
}
GLuint TextureAtlas::getTextureObject() {
return _textureObjectId;
}
std::tuple<float, float> TextureAtlas::getSize() {
return _size;
} | true |
3da63ca38db377fff01666156d00159e29846802 | C++ | OMCS/CS264 | /include/node.h | UTF-8 | 716 | 2.796875 | 3 | [] | no_license | #pragma once
#include "grid.h"
class Node
{
private:
static int nodeCount;
int nodeId;
Node* parentNode;
Grid gridState;
int pathCost;
int xPos;
int yPos;
Direction moveDir;
public:
Node(Grid gridState, Node* parentNode, int pathCost, int xPos, int yPos, Direction moveDir); // Standard constructor
~Node(); // Destructor
int getNodeId() const;
Node* getParentNode();
Grid getGrid();
int getPathCost() const;
int getXPos() const;
int getYPos() const;
Direction getMoveDir();
std::string getMoveDirString();
bool isGoalState(int xPos, int yPos);
};
| true |
cf71b6803366eecc1a841d90fdc6abb67298c8e1 | C++ | a-kashirin-official/spbspu-labs-2018 | /zhigalin.dmitry/common/triangle.hpp | UTF-8 | 578 | 2.65625 | 3 | [] | no_license | #ifndef A1_TRIANGLE_HPP
#define A1_TRIANGLE_HPP
#include "shape.hpp"
namespace zhigalin
{
class Triangle:
public Shape
{
public:
Triangle(const point_t & point_a, const point_t & point_b, const point_t & point_c);
double getArea() const override;
rectangle_t getFrameRect() const override;
void move(const point_t & pos) override;
void move(const double dx, const double dy) override;
void scale(const double coeff) override;
private:
point_t point_a_, point_b_, point_c_;
};
} //zhigalin
#endif //A1_TRIANGLE_HPP
| true |
3dca48a3a3164f0cd50c8184a53488c65bf454f2 | C++ | Beisenbek/kbtu-2018-fall-lecture-samples | /pp1/Saturday/week11/76946_2.cpp | UTF-8 | 554 | 3.21875 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
using namespace std;
bool f(pair<int, int> l, pair<int, int> r){
if(l.first > r.first) return false;
if(l.first == r.first &&
l.second > r.second) return false;
return true;
}
int main(){
int n;
cin >> n;
pair<int, int> p[n];
int x, y;
for(int i = 0; i < n; ++i){
cin >> x >> y;
p[i] = make_pair(x, y);
}
sort(p, p + n, f);
for(int i = 0; i < n; ++i){
cout << p[i].first << " " << p[i].second << endl;
}
return 0;
} | true |
f89f63f911c71245b80d0aa1fd9a79d051bcbd14 | C++ | playday3008/otc | /OTC/cpp/runtime/RuntimeHandler.cpp | UTF-8 | 4,275 | 2.765625 | 3 | [
"CC0-1.0"
] | permissive | #include "../../headers/runtime/RuntimeHandler.h"
void RuntimeHandler::ExtractSegment () {
//Allocate memory for segment, and set pointer.
PanicUtils::SetImportant (&Segment::UnsafeAllocatedPointer, reinterpret_cast<DWORD> (VirtualAlloc (NULL, SegmentHeader::Datacase::ALLOCATION, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE)));
//Small check for not nullable pointer. (In 99% of situations this is not necessary. But who knows what is on the player side. :d)
//This is also unlikely, but if the player is not guilty of this, it will be useful for debugging.
PanicUtils::RequireNonNull (PanicUtils::Layers::INIT, reinterpret_cast<DWORD> (memcpy (reinterpret_cast<PVOID> (Segment::GetSafeAllocationPointer()), SegmentData, SegmentHeader::Datacase::SIZE)), "Allocated memory pointer is null");
}
void RuntimeHandler::ReconstructHotPoints () {
//------RELOCATIONS
//Iterate relocations in vector.
//(Why don't use SafeAllocationPointer? Because it's slow!)
for (const auto& relocation : m_Segment.GetHeader().GetRelocations ()) {
//Subtract value with old base address in segment from memory.
*reinterpret_cast<DWORD*> (Segment::UnsafeAllocatedPointer + relocation) -= SegmentHeader::Datacase::RUNTIME;
//Add new base address in segment to relocations.
*reinterpret_cast<DWORD*> (Segment::UnsafeAllocatedPointer + relocation) += Segment::UnsafeAllocatedPointer;
}
//------RELOCATIONS
//------IMPORTS
//Iterate value in imports map.
for (const auto& importsMap : m_Segment.GetHeader().GetImports ()) {
//Get info about import from value at map.
for (const auto& importInfo : importsMap.second) {
//Get function pointer from module. (Support only function with name)
DWORD functionPointer = Utils::GetFunction (importsMap.first, importInfo.function);
//Check non-nullptr at function and module. (Why don't use RequireNonNull? Because it's slow!)
if (!functionPointer) {
//Just error. Message, value, etc.
std::ostringstream message;
message << "Can`t find module or function. " << "Module: " << importsMap.first << " <|> " << "Function: " << importInfo.function;
PanicUtils::Release (PanicUtils::Layers::INIT, message.str().c_str());
}
//Just iterate all offset. (Locations where function call in segment)
for (const auto& parsedOffset : importInfo.offsetsMap) {
//More about ImportType: SegmentHeader.h
switch (parsedOffset.first) {
case SegmentHeader::ImportType::INTERNAL:
//Patch functions (and in them) that call import.
*reinterpret_cast<DWORD*> (Segment::UnsafeAllocatedPointer + parsedOffset.second) = functionPointer - (Segment::UnsafeAllocatedPointer + parsedOffset.second + 0x4);
break;
case SegmentHeader::ImportType::PUBLIC:
//Patch global variables.
*reinterpret_cast<DWORD*> (Segment::UnsafeAllocatedPointer + parsedOffset.second) = functionPointer;
break;
default:
//Just error. Message, value, etc.
std::ostringstream message;
message << "Can't find offset type. Offset: " << parsedOffset.second << " <-> " << "Function: " << importInfo.function;
PanicUtils::Release (PanicUtils::Layers::ROUTINE, message.str().c_str());
break;
}
}
}
}
//------IMPORTS
}
void RuntimeHandler::InvokeOEP () {
//Set function address for call.
SegmentHeader::DLLMAIN_CALLBACK DllMain = reinterpret_cast <SegmentHeader::DLLMAIN_CALLBACK> (Segment::GetSafeAllocationPointer() + SegmentHeader::Datacase::OEP);
//Check for non-null OEP address.
PanicUtils::RequireNonNull (PanicUtils::Layers::INIT, reinterpret_cast<DWORD> (DllMain), "OEP value is null");
//Call "OEP" func with arguments.
DllMain (reinterpret_cast<HMODULE> (Segment::GetSafeAllocationPointer()), DLL_PROCESS_ATTACH, NULL);
} | true |
6458714708f0073994d3d9f492425eb80ca28aae | C++ | tmcclain-taptech/Ovaldi-Win10 | /ovaldi-code-r1804-trunk/src/ArrayGuard.h | UTF-8 | 3,963 | 3.015625 | 3 | [] | no_license | //
//
//****************************************************************************************//
// Copyright (c) 2002-2014, The MITRE Corporation
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this list
// of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
// * Neither the name of The MITRE Corporation nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
// OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//****************************************************************************************//
#ifndef ARRAYGUARD_H
#define ARRAYGUARD_H
#include <Noncopyable.h>
/**
* Makes exception-safe use of new'd arrays more convenient. Instances
* of this class own an array, and will delete[] the array (but not its
* contents!) when it goes out of scope, so you don't have to remember to free
* it. It also contains some convenience methods similar to auto_ptr, for
* managing ownership, and convenience methods for access. This class does not
* implement ownership transfer semantics, and is noncopyable.
*/
template <typename T>
class ArrayGuard : private Noncopyable {
public:
/**
* Initializes the guard to protect the given array.
*/
explicit ArrayGuard(T *arr = NULL) : arr(arr) {
}
/**
* If the guard protects an array, frees it.
*/
~ArrayGuard() {
if (arr)
delete[] arr;
}
/**
* Changes the guard to protect the given array instead of
* the current array (if any). If an array is already protected,
* it is first freed.
*/
void reset(T *newArr = NULL) {
if (newArr != arr) {
if (arr)
delete[] arr;
arr = newArr;
}
}
/**
* Returns the protected array. The array will no longer be
* protected by this guard.
*/
T *release() {
T *tmp = arr;
arr = NULL;
return tmp;
}
/**
* Returns the protected array. Don't free this yourself.
*/
T *get() {
return arr;
}
/**
* Returns the protected array. Don't free this yourself.
*/
const T *get() const {
return arr;
}
/**
* Allows use of the guard like an array: returns a ref to the
* i'th element. This is not bounds-checked! It also does not
* verify that the guard is in fact protecting an array at all!
* You are responsible for making sure the access is safe.
*/
T& operator[](size_t idx) {
return arr[idx];
}
/**
* Allows use of the guard like an array: returns a ref to the
* i'th element. This is not bounds-checked! It also does not
* verify that the guard is in fact protecting an array at all!
* You are responsible for making sure the access is safe.
*/
const T& operator[](size_t idx) const {
return arr[idx];
}
private:
/** The protected array */
T *arr;
};
#endif
| true |
6751eddc1acdd4462a2edfff37b1d53227d38e68 | C++ | uriqishtepi/uvaonlinejudge | /gattaca_11512.cpp | UTF-8 | 4,520 | 3.25 | 3 | [] | no_license | /* the goal of this problem is to find the longest repeating substring
* so one way to do it is to sort all the substrings, keep track of
* the longest one and then count how many times it shows up
* (obviously two or more).
* Since we are sorting the array, that takes nlogn (where n is the strlen).
*
* It could possibly be achieved with order N, by using two pointers,
* the second one moving ahead of the first finding char same value,
* then record length of how long is the same substring (like strcmp).
* Then you set the first ptr to the second, and continue from
* begginning. Problem with this is that it will find the longest substring
* but not how many times it shows up, so one needs to do another go
* through the string to then find how many times it shows up.
* This second part can be done by building a FSM of the longest repeated
* substring that we found.
*
*/
#include<stdio.h>
#include<math.h>
#include<iostream>
#include<sstream>
#include<algorithm>
#include<functional>
#include<vector>
#include<bitset>
#include<set>
#include<map>
#include <iomanip>
#include <string.h>
#include <assert.h>
#define forl(i,init, max) for(int i = init; i < max; i++)
#define vi std::vector<int>
#define mtsi std::multiset<int, std::greater<int> >
#define si std::set<int>
#define ss std::set<std::string>
#define mi std::map<int, int>
#define msi std::map<std::string, int>
#define INF 1<<30;
//#define DEBUG true
#ifdef DEBUG
#define out printf
#else
#define out
#endif
int g_maxLen;
const char * g_maxPtr;
struct comparator {
public:
comparator(const char* s, size_t n) : m_str(s), m_n(n)
{
out("CONSTRUCTOR\n");
g_maxLen = 0;
g_maxPtr = NULL;
}
bool operator()(const char * pa, const char * pb) {
const char * spa = pa;
const char * spb = pb;
int len = 0;
while(*pa && *pb && *pa == *pb && len < m_n) {
pa++;
pb++;
len++;
}
if(len > g_maxLen || (len == g_maxLen && strncmp(spa, g_maxPtr,len)<0))
{
out(" inc maxlen %d (<= len %d), ", g_maxLen, len);
g_maxLen = len;
g_maxPtr = spa;
}
out("maxlen=%d, cmp %c %c, determined by '%.*s' and '%.*s'\n",
g_maxLen, *spa, *spb, len+1, spa, len+1, spb);
return (*pa < *pb);
}
const char * m_str;
int m_n;
//private: comparator(const comparator & c);
};
void find_smallest_repeating(char * str)
{
char * maxPtr = NULL;
size_t maxLen = 0;
maxPtr = str + 1;
maxLen = 3;
size_t N = strnlen(str, 1000);
//sort strs
std::vector<const char*>v(N);
forl(i, 0, N) v[i]=str+i;
comparator cmp(str, N);
std::sort(v.begin(), v.end(), cmp);
for(std::vector<const char *>::iterator it = v.begin(); it != v.end(); ++it)
{
out(" %c (%d)", **it, *it);
}
out("\n");
if(g_maxLen < 1) {
printf("No repetitions found!\n");
return;
}
//The comparator will give us the longest repeated substring, smaller
//than any other substring with the same length of repeititon
//Now we just need to find how many times such string repeats
out("maxlen = %d\n", g_maxLen);
std::vector<const char*>::iterator it = std::find(v.begin(), v.end(), g_maxPtr);
assert(it != v.end());
out("Found g_maxPtr: %.*s (%d) \n", g_maxLen, *it, *it);
std::vector<const char*>::iterator sit = it;
int freq = 0; //compute freq of the maxPtr
//the while loop counts *it as well
while(it != v.end() && strncmp(g_maxPtr, *it, g_maxLen) == 0) {
out("next *it: %.*s\n", g_maxLen, *it);
freq++;
it++;
}
//we dont know where in the range of same reps g_maxPtr fell
//so count backwards too, until reaching begin or a different substring
//v.begin will almost always be '\n', except for last line in file
while(v.begin() <= --sit && strncmp(g_maxPtr, *sit, g_maxLen) == 0) {
out("next *it: %.*s\n", g_maxLen, *sit);
freq++;
}
printf("%.*s %d\n", g_maxLen, g_maxPtr, freq);
}
int main(int argc, char **argv)
{
out("Starting...\n");
char *buff = NULL;
size_t sz;
int n;
scanf("%d\n",&n);
assert(1 <= n && n <= 100000);
for(int i = 0; i < n; i++) {
if(getline(&buff, &sz, stdin) < 0) return 0;
out("buff=%s\n", buff);
find_smallest_repeating(buff);
}
free(buff); //cleanup
return 0;
}
| true |
741c378e101dd6a98144b37c9666f04dc0629d40 | C++ | GabyZero/Platformer-60fps | /include/block.hpp | UTF-8 | 965 | 2.515625 | 3 | [] | no_license | #ifndef BLOCK_HPP
#define BLOCK_HPP
#include <SFML/Graphics.hpp>
#include "physics/icollidable.hpp"
#include "game.hpp"
class Block : public physics::ICollidable
{
protected:
sf::Sprite* sprite;
public:
Block();
Block(sf::IntRect &, const sf::Texture &,bool scalable=true);
~Block();
/** sf::Drawable implementaion **/
virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const;
void setScale(float,float);
/** ICollidable implementation **/
/*virtual void verticalCollisionEnter(const ICollidable &collidable);
virtual void horizontalCollisionEnter(const ICollidable &collidable);*/
virtual void collisionEnter(const ICollidable &collidable, sf::FloatRect collision);
virtual const sf::Vector2f& getPosition() const;
virtual sf::FloatRect getGlobalBounds() const;
virtual void update(float);
/** end ifcollidable**/
virtual void setPosition(float x, float y);
};
#endif | true |
3612b5ed14dd2dccb1a571e8355e500da30b41b2 | C++ | samnoon1971/CP | /Geometry/area of two circle intersection.cpp | UTF-8 | 1,063 | 2.671875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
#define pi acos(-1)
int main() {
double x1,y1,r1,x2,y2,r2;
cin>>x1>>y1>>r1;
cin>>x2>>y2>>r2;
double dis=sqrt(((x1-x2)*(x1-x2))+ (y1-y2)*(y1-y2));
double res=0.0;
if(dis>=r1+r2) {
res=0.0;
} else if(dis+min(r1,r2)<=max(r1,r2)) {
double r=min(r1,r2);
res=pi*r*r;
} else {
double p1=max(r1,r2);
double p2=min(r1,r2);
if(dis>=max(r1,r2)) {
double angle=acos((p1*p1 + dis*dis - p2*p2)/(2*p1*dis));
angle*=2;
res=p1*p1*(angle-sin(angle));
} else {
double angle1=acos((p1*p1 + dis*dis - p2*p2)/(2*p1*dis));
double angle2=acos((p2*p2 + dis*dis - p1*p1)/(2*p2*dis));
angle1*=2;
angle2*=2;
double res1=0.5*p1*p1*(angle1);
double res2=0.5*p2*p2*(angle2);
res=res1+res2-(0.5*p1*p1*sin(angle1))-(0.5*p2*p2*sin(angle2));
}
}
printf("%.10f\n",res);
return 0;
}
| true |
f445eefbb892bce46763d798f4dc6a6a5ff18eb4 | C++ | EtherTyper/algorithms_and_data_structures | /competitive/apac17/round_E/A.cpp | UTF-8 | 1,334 | 2.765625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
int blues(string s,int st)
{
int bl=0;
for(int i=st;i<s.size();i++)
if(s[i]=='B')
bl++;
return bl;
}
int blues_end(string s,int end)
{
ll bl=0;
for(int i=end;i>=0;i--)
if(s[i]=='B')
bl++;
return bl;
}
int blues_bw(string s,int a,int b)
{
int bl=0;
for(int i=a;i<=b;i++)
if(s[i]=='B')
bl++;
return bl;
}
int main(int argc, char const *argv[])
{
int t,c=1;
cin>>t;
ofstream ofile;
ofile.open("out.txt");
while(t--)
{
string s;
cin>>s;
ll len = s.size(),a,b;
cin>>a>>b;
if((b-a+1)<=len)
{
// cout<<blues(s,(a%len==0)?len-1:a%len-1)<<endl;
int bg=(a%len==0)?len-1:a%len-1;
ofile<<"Case #"<<c<<": "<<blues_bw(s,bg,bg+b-a)<<endl;
c++;
continue;
}
int bg=((a)%(len)==0)?len:(a%len),e=(b-(a+len-bg))%len;
e=(e==0)?len:e;
int tot=blues(s,0);
ll num=(b-(e)-(a+len-bg))/len;
num = (num<0)?0:num;
// cout<<" bg : "<<bg<<endl;
// cout<<" e : "<<e<<endl;
// cout<<" num : "<<num<<endl;
ll sum = num*tot;
// cout<<" sum : "<<sum<<endl;
// cout<<" blues : "<<blues(s,bg-1)<<endl;
// cout<<" blues_end : "<<blues_end(s,e-1)<<endl;
sum+=(blues(s,bg-1) + blues_end(s,e-1));
cout<<sum<<endl;
ofile<<"Case #"<<c<<": "<<sum<<endl;
c++;
}
return 0;
}
/*
4 8
8 - 5 +1
*/
| true |
ab7fb86df719c6c466312d458fd2f3cf7bced226 | C++ | emmason9/CPSC350_SyntaxChecker | /DelimiterSyntax.cpp | UTF-8 | 5,318 | 3.640625 | 4 | [] | no_license | /*
Emilee Mason
ID#2321064
emmason@chapman.edu
CPSC 350-01
Assignment 3: Syntax Checker
*/
#include "DelimiterSyntax.h"
#include <algorithm> //for transform to lower
DelimiterSyntax :: DelimiterSyntax(){
myFiles = new FileProcessor();
currentLineNumber = 0;
delimiterStack = new GenStack<char>();
delimiterLineNumberStack = new GenStack<int>();
}
DelimiterSyntax :: ~DelimiterSyntax(){
delete myFiles;
delete delimiterStack;
}
//opens and runs each line of the given file as well as prompts user if they want to do it again
void DelimiterSyntax :: RunSyntaxCheck(string FileName){
bool runAgainBool = true;
string currentFileName = FileName;
while(runAgainBool){
string currentLine;
bool errorBool = false;
bool fileTest = myFiles->OpenReaderFile(currentFileName);
if (!fileTest){ //if the reader can't opent the file
cout<<"File name given is not readable. Try again."<<endl;
errorBool = true;
}
//while there's no errors.
while(getline(myFiles->Reader, currentLine) && !errorBool){
currentLineNumber++;
errorBool = CheckLine(currentLine);
if(errorBool){
break;
}
}
if (delimiterStack->isEmpty() && !errorBool) {
cout<<"No delimiter errors found!"<<endl;
} else if (delimiterStack->isEmpty() == false){
cout<<"Missing ending delimiter. Starts at line "<<delimiterLineNumberStack->pop()<<endl;
break;
}
myFiles->Reader.close();
runAgainBool = RunAgain();
if(runAgainBool){
//reset line number for next file
currentLineNumber = 0;
string userFileName;
cout<<"What file name would you like to check?(please include the extention!) "<<endl;
cin>>userFileName;
cout<<"you said: "<<userFileName<<endl;
currentFileName = userFileName;
continue;
}
}//end of while loop
}
//returns T/F as to whether there is a deliimiter syntax error(t) or not(f).
bool DelimiterSyntax :: CheckLine(string line){
char poppedDelimiter;
//iterating through the line
for(int i=0; i<line.length(); ++i){
//check if the delimiter is in a char ex. '{' or not
if(line[i-1] == '\'' && line[i+1] == '\''){
continue;
//trying to not count the delimiters that are chars/strings
}
//want to push any starting delimiters first!
if(line[i] == '(' || line[i] == '{' || line[i] == '['){
delimiterStack->push(line[i]);
delimiterLineNumberStack->push(currentLineNumber);
}
//if we find any ending limiters, it should match with the top delimiter in the stack
//checking ()
if(line[i] == ')'){
poppedDelimiter = delimiterStack->pop();
if(poppedDelimiter != '('){
if(poppedDelimiter == '{'){
cout<<"Line "<<currentLineNumber<<":";
cout<<" Error... expected '}' and found "<<line[i]<<endl;
return true; //there is an error, so true
} else if (poppedDelimiter == '['){
cout<<"Line "<<currentLineNumber<<":";
cout<<" Error... expected ']' and found "<<line[i]<<endl;
return true; //there is an error, so true
}
} else {
delimiterLineNumberStack->pop(); //getting rid of the line number
}
//checking {}
} else if(line[i] == '}'){
poppedDelimiter = delimiterStack->pop();
if(poppedDelimiter != '{'){
if(poppedDelimiter == '('){
cout<<"Line "<<currentLineNumber<<":";
cout<<" Error... expected ')' and found "<<line[i]<<endl;
return true; //there is an error, so true
} else if (poppedDelimiter == '['){
cout<<"Line "<<currentLineNumber<<":";
cout<<" Error... expected ']' and found "<<line[i]<<endl;
return true; //there is an error, so true
}
} else {
delimiterLineNumberStack->pop(); //getting rid of the line number
}
//checking []
} else if(line[i] == ']'){
poppedDelimiter = delimiterStack->pop();
if(poppedDelimiter != '['){
if(poppedDelimiter == '{'){
cout<<"Line "<<currentLineNumber<<":";
cout<<" Error... expected '}' and found "<<line[i]<<endl;
return true; //there is an error, so true
} else if (poppedDelimiter == '('){
cout<<"Line "<<currentLineNumber<<":";
cout<<" Error... expected ')' and found "<<line[i]<<endl;
return true; //there is an error, so true
}
} else {
delimiterLineNumberStack->pop(); //getting rid of the line number
}
}
}//end of for loop
}
//asks user if they'd like to check another file with a different name
bool DelimiterSyntax :: RunAgain(){
while(true){
string userResponse;
cout<<"Would you like to check another file?\n'yes' or 'no'"<<endl;
cin>>userResponse;
transform(userResponse.begin(), userResponse.end(), userResponse.begin(), :: tolower);
if(userResponse == "yes"){
return true;
break;
} else if (userResponse == "no" || userResponse == "quit"){
return false;
break;
} else {
cout<<"Couldn't recognize your input. Try again. You can also 'quit'"<<endl;
}
}//end of while loop
}
| true |
924dbf0aee7c8e74dcfeb1ebb83954dd01b6ae22 | C++ | dolchg/game-engine-architecture | /SingleInstructionMultipleData/AddArrays.cpp | UTF-8 | 1,892 | 3.203125 | 3 | [] | no_license | #include "Tests.h"
#include <algorithm>
#include <chrono>
#include <iostream>
#include <stdlib.h>
void ArrayAdd(float* a, float* b, float* c, int n) {
for (int i = 0; i < n; i++) {
c[i] = a[i] + b[i];
}
}
void ArrayAddSIMD(float* a, float* b, float* c, int n) {
ASSERT(n % 4 == 0);
for (int i = 0; i < n; i += 4) {
__m128 aPack = _mm_load_ps(&a[i]);
__m128 bPack = _mm_load_ps(&b[i]);
__m128 result = _mm_add_ps(aPack, bPack);
_mm_store_ps(&c[i], result);
}
}
void AddArraysTest() {
constexpr int SIZE = 16000000;
alignas(16) float* arrayA = new float[SIZE];
alignas(16) float* arrayB = new float[SIZE];
alignas(16) float* arrayC = new float[SIZE];
for (int i = 0; i < SIZE; i++) {
arrayA[i] = 10 * rand() / RAND_MAX;
arrayB[i] = 10 * rand() / RAND_MAX;
}
std::cout << "\n=========================================================================================================\n";
std::cout << "\nTime spent to add two arrays of size " << SIZE << "\n\n";
auto begin = std::chrono::high_resolution_clock::now();
ArrayAdd(arrayA, arrayB, arrayC, SIZE);
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count();
std::cout << "Serially: " << duration << " ms\n";
begin = std::chrono::high_resolution_clock::now();
ArrayAddSIMD(arrayA, arrayB, arrayC, SIZE);
end = std::chrono::high_resolution_clock::now();
duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count();
std::cout << "SIMD 4 per pack: " << duration << " ms\n";
std::cout << "\n=========================================================================================================\n";
delete[] arrayA;
delete[] arrayB;
delete[] arrayC;
}
| true |
7861c61396236dc74bde13923a16fcb977e78ba4 | C++ | albertghtoun/transmem | /tests/libstdc++_validation/pair/member.cc | UTF-8 | 2,489 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <utility>
#include <cassert>
#include "tests.h"
#include "verify.h"
/// The pair we will use for our tests
typedef std::pair<int, int> intpair;
static intpair * member_pair = NULL;
void ctor_dtor_tests(int id)
{
// print simple output
global_barrier->arrive(id);
if (id == 0)
printf("Testing member pair constructors and destructors\n");
// the first test is simple ctor and dtor
std::cout << " No constructor is untraceable\n";
}
void op_eq_tests(int id)
{
// test operator= (copy)
global_barrier->arrive(id);
{
verifier v;
const intpair p(1, 2);
BEGIN_TX;
member_pair = new intpair();
*member_pair = p;
v.insert_all<intpair>(member_pair);
delete(member_pair);
member_pair = NULL;
END_TX;
v.check("pair operator= (1a)", id, 2, {1, 2});
}
// test operator= (copy)
global_barrier->arrive(id);
{
verifier v;
const std::pair<char, char> p(1, 2);
BEGIN_TX;
member_pair = new intpair();
*member_pair = p;
v.insert_all<intpair>(member_pair);
delete(member_pair);
member_pair = NULL;
END_TX;
v.check("pair operator= (1b)", id, 2, {1, 2});
}
// test operator= (move)
global_barrier->arrive(id);
{
verifier v;
intpair p(1, 2);
BEGIN_TX;
member_pair = new intpair();
*member_pair = std::make_pair(1, 2);
v.insert_all<intpair>(member_pair);
delete(member_pair);
member_pair = NULL;
END_TX;
v.check("pair operator= (2a)", id, 2, {1, 2});
}
// test operator= (move)
global_barrier->arrive(id);
{
verifier v;
intpair p(1, 2);
BEGIN_TX;
member_pair = new intpair();
*member_pair = std::make_pair<char, char>(1, 2);
v.insert_all<intpair>(member_pair);
delete(member_pair);
member_pair = NULL;
END_TX;
v.check("pair operator= (2b)", id, 2, {1, 2});
}
}
void swap_tests(int id)
{
// test swap
global_barrier->arrive(id);
{
verifier v;
intpair p(1, 2);
BEGIN_TX;
member_pair = new intpair(3, 4);
member_pair->swap(p);
v.insert_all<intpair>(member_pair);
delete(member_pair);
member_pair = NULL;
END_TX;
v.check("pair swap", id, 2, {1, 2});
}
}
| true |
10764651d4600625df60f1cdf5ceb35fb8b94e30 | C++ | eriser/linAnil | /vs/utils/Tween.hpp | UTF-8 | 8,838 | 3.015625 | 3 | [] | no_license | //
// Created by toramisu on 2015/7/31.
//
#pragma once
#include <math.h>
// Algorithm Reference:
//http://www.robertpenner.com/easing/
//http://www.cnblogs.com/cloudgamer/archive/2009/01/06/Tween.html
#ifndef PI
#define PI 3.1415926f
#endif
const float EPSINON = 0.000001f;
#define EQUAL_ZERO(x) ((x >= - EPSINON) && (x <= EPSINON)) ? true : false
class CTween {
public:
CTween(void);
~CTween(void);
// Linear
float Linear_easeIn(float t, float b, float c, float d) {
return c * t / d + b;
}
float Linear_easeOut(float t, float b, float c, float d){
return c * t / d + b;
}
float Linear_easeInOut(float t, float b, float c, float d) {
return c * t / d + b;
}
// Quadratic
float Quad_easeIn(float t, float b, float c, float d){
return c * (t /= d) * t + b;
}
float Quad_easeOut(float t, float b, float c, float d){
return -c * (t /= d) * (t - 2) + b;
}
float Quad_easeInOut(float t, float b, float c, float d){
if ((t /= d / 2) < 1)
return c / 2 * t * t + b;
return -c / 2 * ((--t) * (t - 2) - 1) + b;
}
// Cubic
float Cubic_easeIn(float t, float b, float c, float d);
float Cubic_easeOut(float t, float b, float c, float d);
float Cubic_easeInOut(float t, float b, float c, float d);
// Quartic
float Quart_easeIn(float t, float b, float c, float d);
float Quart_easeOut(float t, float b, float c, float d);
float Quart_easeInOut(float t, float b, float c, float d);
// Quintic
float Quint_easeIn(float t, float b, float c, float d);
float Quint_easeOut(float t, float b, float c, float d);
float Quint_easeInOut(float t, float b, float c, float d);
// Sinusoidal
float Sine_easeIn(float t, float b, float c, float d);
float Sine_easeOut(float t, float b, float c, float d);
float Sine_easeInOut(float t, float b, float c, float d);
// Exponential
float Expo_easeIn(float t, float b, float c, float d);
float Expo_easeOut(float t, float b, float c, float d);
float Expo_easeInOut(float t, float b, float c, float d);
// Circular
float Circ_easeIn(float t, float b, float c, float d);
float Circ_easeOut(float t, float b, float c, float d);
float Circ_easeInOut(float t, float b, float c, float d);
// Elastic
float Elastic_easeIn(float t, float b, float c, float d, float a = 0.0f, float p = 0.0f);
float Elastic_easeOut(float t, float b, float c, float d, float a = 0.0f, float p = 0.0f);
float Elastic_easeInOut(float t, float b, float c, float d, float a = 0.0f, float p = 0.0f);
// Back
float Back_easeIn(float t, float b, float c, float d, float s = 0.0f);
float Back_easeOut(float t, float b, float c, float d, float s = 0.0f);
float Back_easeInOut(float t, float b, float c, float d, float s = 0.0f);
// Bounce
float Bounce_easeOut(float t, float b, float c, float d);
float Bounce_easeIn(float t, float b, float c, float d);
float Bounce_easeInOut(float t, float b, float c, float d);
public:
float t, b, c, d, a, p;
};
CTween::CTween(void) {
}
CTween::~CTween(void) {
}
// Quadratic
// Cubic
float CTween::Cubic_easeIn(float t, float b, float c, float d) {
return c * (t /= d) * t * t + b;
}
float CTween::Cubic_easeOut(float t, float b, float c, float d) {
return c * ((t = t / d - 1) * t * t + 1) + b;
}
float CTween::Cubic_easeInOut(float t, float b, float c, float d) {
if ((t /= d / 2) < 1)
return c / 2 * t * t * t + b;
return c / 2 * ((t -= 2) * t * t + 2) + b;
}
// Quartic
float CTween::Quart_easeIn(float t, float b, float c, float d) {
return c * (t /= d) * t * t * t + b;
}
float CTween::Quart_easeOut(float t, float b, float c, float d) {
return -c * ((t = t / d - 1) * t * t * t - 1) + b;
}
float CTween::Quart_easeInOut(float t, float b, float c, float d) {
if ((t /= d / 2) < 1)
return c / 2 * t * t * t * t + b;
return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
}
// Quintic
float CTween::Quint_easeIn(float t, float b, float c, float d) {
return c * (t /= d) * t * t * t * t + b;
}
float CTween::Quint_easeOut(float t, float b, float c, float d) {
return c * ((t = t / d - 1) * t * t * t * t + 1) + b;
}
float CTween::Quint_easeInOut(float t, float b, float c, float d) {
if ((t /= d / 2) < 1)
return c / 2 * t * t * t * t * t + b;
return c / 2 * ((t -= 2) * t * t * t * t + 2) + b;
}
// Sinusoidal
float CTween::Sine_easeIn(float t, float b, float c, float d) {
return -c * cos(t / d * (PI / 2)) + c + b;
}
float CTween::Sine_easeOut(float t, float b, float c, float d) {
return c * sin(t / d * (PI / 2)) + b;
}
float CTween::Sine_easeInOut(float t, float b, float c, float d) {
return -c / 2 * (cos(PI * t / d) - 1) + b;
}
// Exponential
float CTween::Expo_easeIn(float t, float b, float c, float d) {
return (t == 0) ? b : c * pow(2, 10 * (t / d - 1)) + b;
}
float CTween::Expo_easeOut(float t, float b, float c, float d) {
return (t == d) ? b + c : c * (-pow(2, -10 * t / d) + 1) + b;
}
float CTween::Expo_easeInOut(float t, float b, float c, float d) {
if (t == 0)
return b;
if (t == d)
return b + c;
if ((t /= d / 2) < 1)
return c / 2 * pow(2, 10 * (t - 1)) + b;
return c / 2 * (-pow(2, -10 * --t) + 2) + b;
}
// Circular
float CTween::Circ_easeIn(float t, float b, float c, float d) {
return -c * (sqrt(1 - (t /= d) * t) - 1) + b;
}
float CTween::Circ_easeOut(float t, float b, float c, float d) {
return c * sqrt(1 - (t = t / d - 1) * t) + b;
}
float CTween::Circ_easeInOut(float t, float b, float c, float d) {
if ((t /= d / 2) < 1)
return -c / 2 * (sqrt(1 - t * t) - 1) + b;
return c / 2 * (sqrt(1 - (t -= 2) * t) + 1) + b;
}
// Elastic
float CTween::Elastic_easeIn(float t, float b, float c, float d, float a/* = 0.0f*/, float p/* = 0.0f*/) {
float s = 0;
if (t == 0)
return b;
if ((t /= d) == 1)
return b + c;
if (!p)
p = d * .3f;
if (!a || a < abs(c)) {
a = c;
s = p / 4;
}
else
s = p / (2 * PI) * asin(c / a);
return -(a * pow(2, 10 * (t -= 1)) * sin((t * d - s) * (2 * PI) / p)) + b;
}
float CTween::Elastic_easeOut(float t, float b, float c, float d, float a/* = 0.0f*/, float p/* = 0.0f*/) {
float s = 0;
if (t == 0)
return b;
if ((t /= d) == 1)
return (b + c);
if (!p)
p = d * .3f;
if (!a || a < abs(c)) {
a = c;
s = p / 4;
}
else
s = p / (2 * PI) * sin((float) c / a);
return (a * pow(2.0f, (int) -10 * t) * sin((t * d - s) * (2 * PI) / p) + c + b);
}
float CTween::Elastic_easeInOut(float t, float b, float c, float d, float a/* = 0.0f*/, float p/* = 0.0f*/) {
float s = 0;
if (t == 0)
return b;
if ((t /= d / 2) == 2)
return b + c;
if (!p)
p = d * (.3f * 1.5f);
if (!a || a < abs(c)) {
a = c;
s = p / 4;
}
else
s = p / (2 * PI) * asin(c / a);
if (t < 1)
return -.5f * (a * pow(2, 10 * (t -= 1)) * sin((t * d - s) * (2 * PI) / p)) + b;
return a * pow(2, -10 * (t -= 1)) * sin((t * d - s) * (2 * PI) / p) * .5f + c + b;
}
// Back
float CTween::Back_easeIn(float t, float b, float c, float d, float s/* = 0.0f*/) {
if (EQUAL_ZERO(s))
s = 1.70158f;
return c * (t /= d) * t * ((s + 1) * t - s) + b;
}
float CTween::Back_easeOut(float t, float b, float c, float d, float s/* = 0.0f*/) {
if (EQUAL_ZERO(s))
s = 1.70158f;
return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
}
float CTween::Back_easeInOut(float t, float b, float c, float d, float s/* = 0.0f*/) {
if (EQUAL_ZERO(s))
s = 1.70158f;
if ((t /= d / 2) < 1)
return c / 2 * (t * t * (((s *= (1.525f)) + 1) * t - s)) + b;
return c / 2 * ((t -= 2) * t * (((s *= (1.525f)) + 1) * t + s) + 2) + b;
}
// Bounce
float CTween::Bounce_easeOut(float t, float b, float c, float d) {
if ((t /= d) < (1 / 2.75)) {
return c * (7.5625f * t * t) + b;
}
else if (t < (2 / 2.75)) {
return c * (7.5625f * (t -= (1.5f / 2.75f)) * t + .75f) + b;
}
else if (t < (2.5 / 2.75)) {
return c * (7.5625f * (t -= (2.25f / 2.75f)) * t + .9375f) + b;
}
else {
return c * (7.5625f * (t -= (2.625f / 2.75f)) * t + .984375f) + b;
}
}
float CTween::Bounce_easeIn(float t, float b, float c, float d) {
return c - Bounce_easeOut(d - t, 0, c, d) + b;
}
float CTween::Bounce_easeInOut(float t, float b, float c, float d) {
if (t < d / 2)
return Bounce_easeIn(t * 2, 0, c, d) * .5f + b;
else return Bounce_easeOut(t * 2 - d, 0, c, d) * .5f + c * .5f + b;
}
| true |
17e6ea6c10a489c6b375207789d38405224b6295 | C++ | sabrinalugoa21/Spongebob_Squarepants | /Spongebob_squarepants/intermediate/type/TypeChecker.h | UTF-8 | 3,690 | 3.28125 | 3 | [] | no_license | #ifndef TYPECHECKER_H_
#define TYPECHECKER_H_
#include "intermediate/type/Typespec.h"
namespace intermediate { namespace type {
using namespace std;
using namespace intermediate::type;
class TypeChecker
{
public:
/**
* Check if a type specification is integer.
* @param typespec the type specification to check.
* @return true if integer, else false.
*/
static bool isInteger(Typespec *typespec);
/**
* Check if both type specifications are integer.
* @param typespec1 the first type specification to check.
* @param typespec2 the second type specification to check.
* @return true if both are integer, else false.
*/
static bool areBothInteger(Typespec *typespec1, Typespec *typespec2);
/**
* Check if a type specification is real.
* @param typespec the type specification to check.
* @return true if real, else false.
*/
static bool isReal(Typespec *typespec);
/**
* Check if a type specification is integer or real.
* @param typespec the type specification to check.
* @return true if integer or real, else false.
*/
static bool isIntegerOrReal(Typespec *typespec);
/**
* Check if at least one of two type specifications is real.
* @param typespec1 the first type specification to check.
* @param typespec2 the second type specification to check.
* @return true if at least one is real, else false.
*/
static bool isAtLeastOneReal(Typespec *typespec1, Typespec *typespec2);
/**
* Check if a type specification is boolean.
* @param type the type specification to check.
* @return true if boolean, else false.
*/
static bool isBoolean(Typespec *typespec);
/**
* Check if both type specifications are boolean.
* @param typespec1 the first type specification to check.
* @param typespec2 the second type specification to check.
* @return true if both are boolean, else false.
*/
static bool areBothBoolean(Typespec *typespec1, Typespec *typespec2);
/**
* Check if a type specification is char.
* @param type the type specification to check.
* @return true if char, else false.
*/
static bool isChar(Typespec *typespec);
/**
* Check if a type specification is string.
* @param type the type specification to check.
* @return true if boolean, else false.
*/
static bool isString(Typespec *typespec);
/**
* Check if both type specifications are string.
* @param typespec1 the first type specification to check.
* @param typespec2 the second type specification to check.
* @return true if both are boolean, else false.
*/
static bool areBothString(Typespec *typespec1, Typespec *typespec2);
/**
* Check if two type specifications are assignment compatible.
* @param targetTypespec the target type specification.
* @param value_typespec the value type specification.
* @return true if the value can be assigned to the target, else false.
*/
static bool areAssignmentCompatible(Typespec *targetTypespec,
Typespec *valueTypespec);
/**
* Check if two type specifications are comparison compatible.
* @param typespec1 the first type specification to check.
* @param typespec2 the second type specification to check.
* @return true if the types can be compared to each other, else false.
*/
static bool areComparisonCompatible(Typespec *typespec1,
Typespec *typespec2);
};
}} // namespace intermediate::type
#endif /* TYPECHECKER_H_ */
| true |
a5bfcca04b08e08d4ae01c7e29f5157e1238c60c | C++ | RippeR37/AI-2015-Vindinium-bots | /random_bot.h | UTF-8 | 363 | 2.53125 | 3 | [] | no_license | #pragma once
#include "game.h"
struct Bot
{
Bot(const Game& game, Rng& rng);
void
crunch_it_baby(const Game& game, const OmpFlag& continue_flag, const double& start_time, const double& duration);
Direction
get_move(const Game& game) const;
void
advance_game(Game& game, const Direction& direction);
private:
Rng& rng;
};
| true |
b774d89ab1ac463b5682595d0622e6727cf7e253 | C++ | Seantheprogrammer93/CPP-Inheritance-and-Polymorphism | /Hatchback.cpp | UTF-8 | 608 | 2.984375 | 3 | [
"Unlicense"
] | permissive | #include "Hatchback.h"
int Hatchback::vehicleTrunkSize()
{
std::cout << "Hatchback trunk size: " << trunk << std::endl;
return trunk;
}
double Hatchback::vehiclePrice()
{
std::cout << "Hatchback price: " << price << std::endl;
return price;
}
int Hatchback::vehicleNumberOfDoors()
{
std::cout << "Hatchback door count: " << doors << std::endl;
return doors;
}
bool Hatchback::vehicleEngineIsOn()
{
if (engine == true)
{
std::cout << "Hatchback engine is on!" << std::endl;
}
else
{
std::cout << "Hatchback engine is off!" << std::endl;
}
return engine;
} | true |
cec56f03fb71395e6306d5f1667a3abeffc23920 | C++ | A-Hidden/zhang_liming | /作业/6-18/main.cpp | GB18030 | 562 | 3.953125 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int integerPower(int,unsigned int);//
int base=0;
unsigned int exponent=0;//
cout<<"Please enter numbers what you want to calculate";//ʾ
cin >> base ;
cin >> exponent;//ȡ
cout<<"integerPower("<<base<<","<<exponent<<")="<<integerPower(base,exponent);
}
int integerPower(int base,unsigned int exponent)
{
int result=1;
for( int i=1;i<=exponent;i++)
{
result*=base;
}//end the "for"loop
return result;
}//end the function
| true |
b6094e70b09c8c5d117001c81edbcd3cd307d560 | C++ | ailyanlu1/c100 | /P2/test_RST.cpp | UTF-8 | 2,662 | 3.203125 | 3 | [
"MIT"
] | permissive | #include "RST.hpp"
#include "countint.hpp"
#include <cmath>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
using namespace std;
/**
* A simple partial test driver for the RST class template.
* P2 CSE 100
* Author: P. Kube (c) 2010, 2013
*/
int main(int argc, char** argv) {
int N = 1000;
if(argc > 1) N = atoi(argv[1]);
// a good RST implementation should need no more than this number
// of key comparisons when inserting N keys
double maxcompsperkey = (log(N) * 2.5);
/* Create an STL vector of some countints, in sorted order */
vector<countint> v;
for(int i=0; i<N; i++) {
// v.push_back(i);
v.push_back(i);
}
/* Create an empty instance of RST holding countint */
BST<countint>* r = new RST<countint>();
/* Clear the comparison counter */
countint::clearcount();
/* Insert the data items, in order */
cout << "Inserting " << N << " sorted keys in initially empty RST...";
vector<countint>::iterator vit = v.begin();
vector<countint>::iterator ven = v.end();
for(; vit != ven; ++vit) {
// all these inserts are unique, so should return a std::pair
// with second part true
std::pair<BST<countint>::iterator,bool> pr = r->insert(*vit);
if(! pr.second ) {
cout << "Incorrect bool return value when inserting " << *vit << endl;
return -1;
}
countint rc = *(pr.first);
countint bc = *vit;
if(rc < bc || bc < rc) {
cout << "Incorrect iterator return value when inserting " << *vit << endl;
return -1;
}
}
cout << " done." << endl;
// r->inorder();
/* How many comparisons did it take to do the inserts, avg per key? */
double compsperkey = countint::getcount() / (double) N;
cout << "That took " << compsperkey << " average comparisons per key, ";
if(compsperkey <= maxcompsperkey) cout << "OK. " << endl;
else if (compsperkey <= maxcompsperkey * 2) cout << "could be better... " << endl;
else {
cout << "way too many!" << endl;
return -1;
}
/* Test iterator; should iterate the entire tree inorder */
cout << "Checking traversal using iterator...\n";
vit = v.begin();
BST<countint>::iterator en = r->end();
BST<countint>::iterator it = r->begin();
int i = 0;
for(; it != en; ++it) {
//cout << *it << endl;
countint rc = *it;
countint bc = *vit;
if(rc < bc || bc < rc) {
cout << endl << "Incorrect inorder iteration of RST." << endl;
return -1;
}
++i;
++vit;
}
if(i!=N) {
cout << endl << "Early termination during inorder iteration of RST." << endl;
return -1;
}
cout << " OK." << endl;
return 0;
}
| true |
334c8b9e0fc9caab02792de95554bfc5113e73dc | C++ | uaf-arctic-eco-modeling/dvm-dos-tem | /src/tbc-debug-util.cpp | UTF-8 | 1,934 | 2.53125 | 3 | [
"MIT",
"LicenseRef-scancode-other-permissive"
] | permissive | //
// tbc-debug-util.cpp
// dvm-dos-tem
//
// Created by Tobey Carman on 9/13/13.
// 2013 Spatial Ecology Lab.
//
#include <iostream>
#include <unistd.h> // for hostname stuff...
#ifdef WITHMPI
#include <mpi.h>
#endif
#include "../include/tbc-debug-util.h"
#ifdef WITHMPI
// For now, not using any of these funcitons w/o MPI, so have
// included all of them in the #ifdef to make compiling easier.
void tbc_mpi_pp_error(int err) {
switch (err) {
case MPI_SUCCESS: {
std::cout << "MPI_SUCCESS\n";
break;
}
case MPI_ERR_REQUEST: {
std::cout << "MPI_ERR_REQUEST\n";
break;
}
case MPI_ERR_ARG: {
std::cout << "MPI_ERR_ARG\n";
break;
}
default: {
std::cout << "Hmmm.? Unknown MPI Return Code?\n";
break;
}
}
}
void PAUSE_to_attach_gdb(int myrank, int stop_in_rank) {
/* Debugging help from here:
http://www.open-mpi.org/faq/?category=debugging
basically, compile the program and start it like normal. Will get a
messages to console from each process...
in another console, cd to dvm-dos-tem and type e.g.:
$ gdb --pid 94206 DVMDOSTEM
Then in that window, do
(gdb) bt
and you shoudl see stack
then move up stack with
(gdb) frame <whatever number>
then set the i to a non-zero value
(gdb) set var i = 7
then set a breakpoint after this pause
*/
if (myrank == stop_in_rank) {
int i = 0;
char hostname[256];
gethostname(hostname, sizeof(hostname));
printf("PID %d on %s ready for attach\n", getpid(), hostname);
fflush(stdout);
while (0 == i) {
sleep(5);
}
}
}
/* another version that will stop on all ranks */
void PAUSE_to_attach_gdb() {
int i = 0;
char hostname[256];
gethostname(hostname, sizeof(hostname));
printf("PID %d on %s ready for attach\n", getpid(), hostname);
fflush(stdout);
while (0 == i) {
sleep(5);
}
}
#endif
| true |
d57ac27a2b3e821118679cad2454fcee666e7711 | C++ | jigyasa3003/Algorithms | /Сборник моих алгоритмов/Теория чисел/Диофант через Евклида.cpp | UTF-8 | 1,002 | 2.53125 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <deque>
#include <queue>
#include <algorithm>
#include <utility>
#include <string>
#include <cmath>
#include <iomanip>
#include <cctype>
#define mp make_pair
#define pb push_back
#define x first
#define y second
#define ins insert
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<ll,ll> pii;
ll gcd(ll a,ll b,ll &x,ll &y)
{
if(a == 0)
{
x=0;
y=1;
return b;
}
ll x1,y1,d;
d=gcd(b%a,a,x1,y1);
y=x1;
x=y1-(b/a)*x1;
return d;
}
void test()
{
//Diophant's: ax+by=c
ll a,b,c,x,y,nod;
cin>>a>>b>>c;
nod=gcd(a,b,x,y);
if(c%nod == 0)
{
ll mn=c/nod;
cout<<a*mn<<"*"<<x<<"+"<<b*mn<<"*"<<y<<" = "<<c<<endl;
}
else
cout<<"No solution"<<endl;
}
int main()
{
ios_base::sync_with_stdio(0);
test();
return 0;
}
| true |
63cf13b78ca2697e6f2cd73c702d444a241f61e2 | C++ | brianrho/FPM | /examples/search_database/search_database.ino | UTF-8 | 3,953 | 2.640625 | 3 | [] | no_license | #include <SoftwareSerial.h>
#include <FPM.h>
/* Search the fingerprint database for a print */
/* pin #2 is IN from sensor (GREEN wire)
pin #3 is OUT from arduino (WHITE/YELLOW wire)
*/
SoftwareSerial fserial(2, 3);
FPM finger(&fserial);
FPM_System_Params params;
void setup()
{
Serial.begin(9600);
Serial.println("1:N MATCH test");
fserial.begin(57600);
if (finger.begin()) {
finger.readParams(¶ms);
Serial.println("Found fingerprint sensor!");
Serial.print("Capacity: "); Serial.println(params.capacity);
Serial.print("Packet length: "); Serial.println(FPM::packet_lengths[params.packet_len]);
} else {
Serial.println("Did not find fingerprint sensor :(");
while (1) yield();
}
}
void loop()
{
Serial.println("Send any character to search for a print...");
while (Serial.available() == 0) yield();
search_database();
while (Serial.read() != -1);
}
int search_database(void) {
int16_t p = -1;
/* first get the finger image */
Serial.println("Waiting for valid finger");
while (p != FPM_OK) {
p = finger.getImage();
switch (p) {
case FPM_OK:
Serial.println("Image taken");
break;
case FPM_NOFINGER:
Serial.println(".");
break;
case FPM_PACKETRECIEVEERR:
Serial.println("Communication error");
break;
case FPM_IMAGEFAIL:
Serial.println("Imaging error");
break;
case FPM_TIMEOUT:
Serial.println("Timeout!");
break;
case FPM_READ_ERROR:
Serial.println("Got wrong PID or length!");
break;
default:
Serial.println("Unknown error");
break;
}
yield();
}
/* convert it */
p = finger.image2Tz();
switch (p) {
case FPM_OK:
Serial.println("Image converted");
break;
case FPM_IMAGEMESS:
Serial.println("Image too messy");
return p;
case FPM_PACKETRECIEVEERR:
Serial.println("Communication error");
return p;
case FPM_FEATUREFAIL:
Serial.println("Could not find fingerprint features");
return p;
case FPM_INVALIDIMAGE:
Serial.println("Could not find fingerprint features");
return p;
case FPM_TIMEOUT:
Serial.println("Timeout!");
return p;
case FPM_READ_ERROR:
Serial.println("Got wrong PID or length!");
return p;
default:
Serial.println("Unknown error");
return p;
}
/* search the database for the converted print */
uint16_t fid, score;
p = finger.searchDatabase(&fid, &score);
/* now wait to remove the finger, though not necessary;
this was moved here after the search because of the R503 sensor,
which seems to wipe its buffers after each scan */
Serial.println("Remove finger");
while (finger.getImage() != FPM_NOFINGER) {
delay(500);
}
Serial.println();
if (p == FPM_OK) {
Serial.println("Found a print match!");
} else if (p == FPM_PACKETRECIEVEERR) {
Serial.println("Communication error");
return p;
} else if (p == FPM_NOTFOUND) {
Serial.println("Did not find a match");
return p;
} else if (p == FPM_TIMEOUT) {
Serial.println("Timeout!");
return p;
} else if (p == FPM_READ_ERROR) {
Serial.println("Got wrong PID or length!");
return p;
} else {
Serial.println("Unknown error");
return p;
}
// found a match!
Serial.print("Found ID #"); Serial.print(fid);
Serial.print(" with confidence of "); Serial.println(score);
}
| true |
f5f2148870663f1ec456ddc688531945a0718346 | C++ | Shivamnirwani/Pathfinding_algorithms | /Roundrobin.cpp | UTF-8 | 1,129 | 2.671875 | 3 | [] | no_license | # include <iostream>
using namespace std;
int main()
{
int n, bt[n],f,r_bt[n], wt[n], i ,t=0, tq,tat[n];
float sum,avgwt,avgtat;
cout<<"Enter no. of process: ";
cin>>n;
cout<<"Enter the time quantum: ";
cin>>tq;
cout<<"Enter burst time: ";
for(i=0; i<n;i++)
cin>>bt[i];
for(i=0; i<n;i++)
r_bt[i]=bt[i];
while(true)
{
f=true;
for(i=0;i<n;i++)
{
if(r_bt[i]>0)
{
f= false;
if(r_bt[i]> tq)
{
t=t+tq;
r_bt[i]= r_bt[i]- tq;
}
else
{
t=t+r_bt[i];
wt[i]=t-bt[i];
r_bt[i]=0;
tat[i]=bt[i]+wt[i];
}
}
}
if(f==true)
break;
}
cout<<"The ture around time of processes are:- \n";
for(i=0;i<n;i++)
cout<<"P"<<i+1<<" - "<<tat[i]<<"\n";
cout<<"The waiting time of processes are:- \n";
for(i=0;i<n;i++)
cout<<"P"<<i+1<<" - "<<wt[i]<<"\n";
sum=0;
for(i=0;i<n;i++)
sum=sum+wt[i];
avgwt=sum/n ;
sum=0;
for(i=0;i<n;i++)
sum=sum+tat[i];
avgtat=sum/n;
cout<<" \n the average waiting time: "<<avgwt;
cout<<" \n the average turn around time: "<<avgtat;
return 0;
}
| true |
fdf83d3d380b88842416753540218ea819a64cec | C++ | nijiahe/code | /code/windows/c_c++_code/早期c_c++/STL/6.set红黑树.cpp | GB18030 | 1,281 | 3.53125 | 4 | [] | no_license | #include<iostream>
#include<set>
#include<string>
using namespace std;
struct strless
{
bool operator()(const char *str1,const char* str2) const
{/*str1<str2ظֵ,str1=str20,str1>str2,ȽϴСֵһ*/
return strcmp(str1, str2)<0 ;
}
};
void main60()
{/*Ԫ,*/
set<char*, strless>myset1;
myset1.insert("zzt");
myset1.insert("ly");
myset1.insert("njh");
for (auto ibegin = myset1.begin(); ibegin != myset1.end(); ibegin++)
{
cout << *ibegin << endl;
}
cin.get();
}
void main61()
{
const char* cmd[] = { "abc","calc","ly","njh","zzt" };
set<const char*, strless>myset1(cmd, cmd + 5, strless());
for (auto ibegin = myset1.begin(); ibegin != myset1.end(); ibegin++)
{
cout << *ibegin << endl;
}
/*ַinsertʱһpair,Լpairģʵ*/
//pair<set<const char*>::iterator, bool>p=myset1.insert("9876");
auto p = myset1.insert("9876");
/*p.firstһconditional,*,*pinsertֵ,p.secondصboolֵ*/
cout << *(p.first) << " " << p.second << endl;
/*set<const char *, strless>::iterator pfind = myset1.find("abc");
cout << "\n\n\n" << *pfind << endl;*/
cin.get();
} | true |
89f1df9adc6e4ce5770b7eef6484a403e31b412f | C++ | micahwelf/FLTK-Ada | /src/c_fl_menu_button.cpp | UTF-8 | 1,931 | 2.515625 | 3 | [
"Unlicense"
] | permissive |
#include <FL/Fl_Menu_Button.H>
#include "c_fl_menu_button.h"
#include "c_fl_type.h"
class My_Menu_Button : public Fl_Menu_Button {
public:
using Fl_Menu_Button::Fl_Menu_Button;
friend void menu_button_set_draw_hook(MENUBUTTON m, void * d);
friend void fl_menu_button_draw(MENUBUTTON m);
friend void menu_button_set_handle_hook(MENUBUTTON m, void * h);
friend int fl_menu_button_handle(MENUBUTTON m, int e);
protected:
void draw();
void real_draw();
int handle(int e);
int real_handle(int e);
d_hook_p draw_hook;
h_hook_p handle_hook;
};
void My_Menu_Button::draw() {
(*draw_hook)(this->user_data());
}
void My_Menu_Button::real_draw() {
Fl_Menu_Button::draw();
}
int My_Menu_Button::handle(int e) {
return (*handle_hook)(this->user_data(), e);
}
int My_Menu_Button::real_handle(int e) {
return Fl_Menu_Button::handle(e);
}
void menu_button_set_draw_hook(MENUBUTTON m, void * d) {
reinterpret_cast<My_Menu_Button*>(m)->draw_hook = reinterpret_cast<d_hook_p>(d);
}
void fl_menu_button_draw(MENUBUTTON m) {
reinterpret_cast<My_Menu_Button*>(m)->real_draw();
}
void menu_button_set_handle_hook(MENUBUTTON m, void * h) {
reinterpret_cast<My_Menu_Button*>(m)->handle_hook = reinterpret_cast<h_hook_p>(h);
}
int fl_menu_button_handle(MENUBUTTON m, int e) {
return reinterpret_cast<My_Menu_Button*>(m)->real_handle(e);
}
MENUBUTTON new_fl_menu_button(int x, int y, int w, int h, char* label) {
My_Menu_Button *m = new My_Menu_Button(x, y, w, h, label);
return m;
}
void free_fl_menu_button(MENUBUTTON m) {
delete reinterpret_cast<My_Menu_Button*>(m);
}
void fl_menu_button_type(MENUBUTTON m, unsigned int t) {
reinterpret_cast<Fl_Menu_Button*>(m)->type(t);
}
const void * fl_menu_button_popup(MENUBUTTON m) {
return reinterpret_cast<Fl_Menu_Button*>(m)->popup();
}
| true |
a71b28d91dfead00ff5468d658a3c73e59e0411a | C++ | st58229/CPP | /Cviceni_05/Exceptions.h | UTF-8 | 469 | 2.609375 | 3 | [] | no_license | #pragma once
#ifndef EXCEPTIONS_H
#define EXCEPTIONS_H
#include <string>
using namespace std;
struct Exceptions
{
private:
string message;
public:
Exceptions(string message);
virtual string getMessage();
};
struct NoSuchElementException : Exceptions { NoSuchElementException(string message) : Exceptions(message) {} };
struct WrongInputException : Exceptions { WrongInputException(string message) : Exceptions(message) {} };
#endif | true |
7ffd4223f7b521bdd111af2c24619b21fc83ea0b | C++ | Delaunay/strat3 | /src/graphics/Shapes.h | UTF-8 | 2,201 | 2.953125 | 3 | [] | no_license | #ifndef STRAT3_GRAPHICS_SHAPES_HEADER
#define STRAT3_GRAPHICS_SHAPES_HEADER
#include <memory>
#include <vector>
#include "Scale.h"
#include "Painter.h"
#include "utility.h"
#include "item.h"
template<typename T>
std::unique_ptr<GraphicItem> draw_line(const std::vector<T>& v, const sf::FloatRect& rct)
{
Painter l;
std::unique_ptr<GraphicItem> it(new GraphicItem);
auto minmax = std::minmax_element(v.begin(), v.end());
Bounded2DScale<float> xy((*minmax.first), (*minmax.second),
0, v.size(), rct);
sf::Vector2f p1 = xy(0, v[0]);
sf::Vector2f p2;
for(int i = 1, n = v.size(); i < n; i++)
{
p2 = xy(i, v[i]);
it->add_item(l.line(p1, p2));
p1 = p2;
}
return it;
}
template<typename T>
std::unique_ptr<GraphicItem> draw_line(const std::vector<T>& vx,
const std::vector<T>& vy, const sf::FloatRect& rct)
{
Painter l;
std::unique_ptr<GraphicItem> it(new GraphicItem);
auto xminmax = std::minmax_element(vx.begin(), vx.end());
auto yminmax = std::minmax_element(vy.begin(), vy.end());
Bounded2DScale<float> xy((*xminmax.first), (*xminmax.second),
(*yminmax.first), (*yminmax.second), rct);
sf::Vector2f p1 = xy(vx[0], vy[0]);
sf::Vector2f p2;
for(int i = 1, n = std::min(vx.size(), vy.size()); i < n; i++)
{
p2 = xy(vx[i], vy[i]);
it->add_item(l.line(p1, p2));
p1 = p2;
}
return it;
}
template<typename T>
std::unique_ptr<GraphicItem> draw_points(const std::vector<T>& vx,
const std::vector<T>& vy, const sf::FloatRect& rct)
{
Painter l;
std::unique_ptr<GraphicItem> it(new GraphicItem);
auto xminmax = std::minmax_element(vx.begin(), vx.end());
auto yminmax = std::minmax_element(vy.begin(), vy.end());
Bounded2DScale<float> xy((*xminmax.first), (*xminmax.second),
(*yminmax.first), (*yminmax.second), rct);
for(int i = 0, n = std::min(vx.size(), vy.size()); i < n; i++)
{
it->add_item(l.point(xy(vx[i], vy[i])));
}
return it;
}
#endif
| true |
f3c12463429d0c3e1a6c97de66aa2994ac978035 | C++ | onievui/DuelWitch | /Sources/Utils/LoadDataHolder.h | SHIFT_JIS | 1,304 | 3.09375 | 3 | [] | no_license | #pragma once
#ifndef LOAD_DATA_HOLDER_DEFINED
#define LOAD_DATA_HOLDER_DEFINED
#include "ILoadDataHolder.h"
#include "LoadDataManager.h"
template<class T, LoadDataID DataID>
/// <summary>
/// ǂݍ݃f[^ێNX
/// </summary>
class LoadDataHolder : public ILoadDataHolder {
friend class LoadDataManager;
public:
// RÂǂݍ݃f[^ID
static constexpr LoadDataID ID = DataID;
public:
// RXgN^
LoadDataHolder()
: m_data() {
// LoadDataManager::GetIns()->Regiser(this);
}
// fXgN^
~LoadDataHolder() {
// LoadDataManager::GetIns()->Unregister(this);
}
private:
// f[^ǂݍ
bool Load() override {
if (!m_data) {
m_data = std::make_unique<T>();
}
return m_data->Load();
}
// f[^ēǂݍ݂
bool Reload() override {
return m_data->Reload();
}
// f[^
void Dispose() override {
m_data.reset();
}
// ǂݍ݃f[^ID擾
LoadDataID GetID() const override {
return ID;
}
public:
// f[^擾
const T* Get() const {
return m_data.get();
}
public:
T* operator->() {
return m_data.get();
}
private:
// ǂݍރf[^{
std::unique_ptr<T> m_data;
};
#endif // !LOAD_DATA_HOLDER_DEFINED
| true |
c36b96ef0a5d8d2790d432df02ac0bfadd704eae | C++ | jameschristianto/cpp | /Unordered Set/src/main.cpp | UTF-8 | 3,327 | 3.65625 | 4 | [] | no_license | #include <iostream>
#include <unordered_set>
#include <iterator>
using namespace std;
void print(unordered_set<int> mySet);
void getSize(unordered_set<int> mySet);
void insert(unordered_set<int> &mySet);
void check(unordered_set<int> &mySet);
void erase(unordered_set<int> &mySet);
void eraseArea(unordered_set<int> &mySet);
void clear(unordered_set<int> &mySet);
unordered_set<int> intSet;
unordered_set<char> charSet = {'a', 'b', 'c'};
int main()
{
int selected;
intSet.insert(1);
intSet.insert(7);
intSet.insert(3);
intSet.insert(2);
intSet.insert(5);
do
{
cout << "1. Print" << endl;
cout << "2. Size" << endl;
cout << "3. Insert" << endl;
cout << "4. Check" << endl;
cout << "5. Erase" << endl;
cout << "6. Erase Area" << endl;
cout << "7. Clear" << endl;
cout << endl;
cout << "Input command : ";
cin >> selected;
switch (selected)
{
case 1:
print(intSet);
break;
case 2:
getSize(intSet);
break;
case 3:
insert(intSet);
break;
case 4:
check(intSet);
break;
case 5:
erase(intSet);
break;
case 6:
eraseArea(intSet);
break;
case 7:
clear(intSet);
break;
default:
break;
}
} while (1);
system("pause");
return 0;
}
void print(unordered_set<int> mySet)
{
cout << endl;
if (mySet.empty()){
cout << "Set is empty..." << endl;
cout << endl;
return;
}
//method 1
for (auto x : mySet)
{
cout << x << endl;
}
//method 2
//set<int>::iterator itr;
//for (itr = mySet.begin(); itr != mySet.end(); itr++)
//{
// cout << *itr << endl;
//}
cout << endl;
}
void getSize(unordered_set<int> mySet)
{
cout << endl;
cout << "Set size : " << mySet.size() << endl;
cout << endl;
}
void insert(unordered_set<int> &mySet)
{
int value;
cout << endl;
cout << "Value : ";
cin >> value;
cout << endl;
intSet.insert(value);
}
void check(unordered_set<int> &mySet)
{
int value;
int counter = 1;
cout << endl;
cout << "Value : ";
cin >> value;
if (mySet.find(value) != mySet.end())
{
auto pos = mySet.find(value);
for (auto it = mySet.begin(); it != pos; it++)
counter++;
cout << "Position : " << counter << endl;
}
else cout << "Not fount..." << endl;
cout << endl;
}
void erase(unordered_set<int> &mySet)
{
int value;
cout << endl;
cout << "Value : ";
cin >> value;
cout << endl;
intSet.erase(value);
}
void eraseArea(unordered_set<int> &mySet)
{
int positionStart, positionEnd;
unordered_set<int>::iterator itr = mySet.begin();
unordered_set<int>::iterator itr2 = mySet.begin();
cout << endl;
cout << "Position start : ";
cin >> positionStart;
cout << "Position end : ";
cin >> positionEnd;
cout << endl;
advance(itr, positionStart - 1);
advance(itr2, positionEnd);
mySet.erase(itr, itr2);
}
void clear(unordered_set<int> &mySet)
{
mySet.clear();
} | true |
4ac3d8f8ceee8a60d6ad32ad17edaeb3a993500a | C++ | shikharkrdixit/cppstuff | /stl/containeradapters/klargestelements.cpp | UTF-8 | 497 | 2.953125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
void klargestelements(int arr[],int n,int k){
priority_queue<int,vector<int>,greater<int>> pq(arr,arr+k);
for(int i=k;i<n;i++){
if(arr[i]>pq.top()){
pq.pop();
pq.push(arr[i]);
}
}
while(pq.empty()==false){
cout<<pq.top()<<" ";
pq.pop();
}
}
int main() {
int n,k;
cin>>n>>k;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
klargestelements(arr,n,k);
return 0;
} | true |
f7bb8ef96f707139bd3770b9820b44ec6aaf3600 | C++ | CLEMENTINATOR/TeamWiigen | /libwiisys/headers/Libwiisys/Exceptions/Exception.h | UTF-8 | 1,079 | 2.984375 | 3 | [] | no_license | #ifndef _EXCEPTION_H_
#define _EXCEPTION_H_
#include <string>
#include <ogcsys.h>
#include "../Object.h"
/*! \namespace Libwiisys::Exceptions
*
* \brief Exceptions used in Libwiisys
*/
namespace Libwiisys
{
namespace Exceptions
{
/*! \class Exception
* \brief Simple exception class
* \author Arasium, Teton, Fanta
* \version 1.0
*
* The Exception class allow the user to create & catch "custom" Exceptions
* This class must be the base class of all other exceptions. This will allow e better
* tracking of errors.
*/
class Exception : public Object
{
public:
virtual std::string GetType();
/*!
* \brief Constructor
* \param message The message text of your exception
*/
Exception(const std::string& message);
/*!
* \brief Return the exception message
* \return The exception message
*/
std::string GetMessage();
virtual std::string ToString();
private:
std::string _message;
};
}
}
#endif
| true |
d9d893a90d904e0a7e2e589c9358a46ecf64ba3f | C++ | sslab-gatech/apisan | /llvm/tools/clang/test/CXX/expr/expr.prim/expr.prim.lambda/p3.cpp | UTF-8 | 504 | 2.578125 | 3 | [
"NCSA",
"MIT"
] | permissive | // RUN: %clang_cc1 -fsyntax-only -std=c++11 %s -verify
void test_nonaggregate(int i) {
auto lambda = [i]() -> void {}; // expected-note 3{{candidate constructor}}
decltype(lambda) foo = { 1 }; // expected-error{{no matching constructor}}
static_assert(!__is_literal(decltype(lambda)), "");
auto lambda2 = []{}; // expected-note {{lambda}}
decltype(lambda2) bar = {}; // expected-error{{call to implicitly-deleted default constructor}}
static_assert(!__is_literal(decltype(lambda2)), "");
}
| true |
7b2c5e176255ff6bd8a41135d6086cadc054ce46 | C++ | huisam/JinLearnedList | /Algorithm/baekjoon/c++/RGB거리.cpp | UTF-8 | 646 | 2.625 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
long long a[1001][3];
int min(int num1, int num2) { return num1 < num2 ? num1 : num2; }
int main() {
ios_base::sync_with_stdio(false);
int n;
cin >> n;
vector<vector<int>> d(n+1, vector<int>(3));
for (int i = 1; i <= n; i++) {
cin >> d[i][0] >> d[i][1] >> d[i][2];
}
a[1][0] = d[1][0];
a[1][1] = d[1][1];
a[1][2] = d[1][2];
for (int i = 2; i <= n; i++) {
a[i][0] = min(a[i - 1][1], a[i - 1][2]) + d[i][0];
a[i][1] = min(a[i - 1][0], a[i - 1][2]) + d[i][1];
a[i][2] = min(a[i - 1][0], a[i - 1][1]) + d[i][2];
}
cout << min(a[n][0], min(a[n][1], a[n][2])) << '\n';
} | true |
7da48d0ddbbe39c9f0ba42c74575ac1ed7fdbbe9 | C++ | smitropoulos/c_client | /include/TCP_ConnectionHandler.h | UTF-8 | 809 | 2.53125 | 3 | [] | no_license | //
// Created by Stefanos Mitropoulos on 2019-05-20.
//
#ifndef TCP_CLIENT_TCP_CONNECTIONHANDLER_H
#define TCP_CLIENT_TCP_CONNECTIONHANDLER_H
#include <netdb.h>
#include <cstdio>
#include <cstdlib>
#include <strings.h>
#include <spdlog/spdlog.h>
class TCP_ConnectionHandler {
private:
TCP_ConnectionHandler() = default;
int mSocket{};
int mPort{8080};
std::string mHost{};
bool init{};
public:
static TCP_ConnectionHandler& getInstance() {
static TCP_ConnectionHandler xInstance;
return xInstance;
}
void setup(const std::string &host, unsigned int port) {
this->mPort = port;
this->mHost = host;
init = true;
}
void Connect();
int getSocket() const {
return mSocket;
}
};
#endif //TCP_CLIENT_TCP_CONNECTIONHANDLER_H
| true |
3ade24cefb66460fd062b086ecb5d96bddb48a67 | C++ | wildkyske/TestLib | /Source/Utility/src/variant.cpp | UTF-8 | 3,216 | 3.0625 | 3 | [] | no_license | #include "../include/variant.h"
#include "../include/StlUtil.h"
#include <string.h>
Variant::Variant()
: mFixedSize(sizeof(long long))
, mSize(mFixedSize)
, mSharedMemory(false)
{
}
Variant::~Variant()
{
}
void Variant::destroy()
{
if (mSharedMemory)
{
free(ptr);
mSharedMemory = false;
memset(&ptr, 0, mFixedSize);
}
mType = "";
mSize = 0;
}
void Variant::zero()
{
if (mSharedMemory)
{
memset(ptr, 0, mSize);
}
else
{
memset(&ptr, 0, mFixedSize);
}
}
bool Variant::isValid() const
{
return mSize == 0 || mType == "";
}
int Variant::size() const
{
return mSize;
}
bool Variant::isShared() const
{
return mSharedMemory;
}
std::string Variant::typeString() const
{
return mType;
}
void Variant::construct( char c )
{
mSize = sizeof(c);
mType = std::string(typeid(c).name());
mSharedMemory = false;
this->c = c;
}
void Variant::construct( unsigned char uc )
{
mSize = sizeof(uc);
mType = std::string(typeid(uc).name());
mSharedMemory = false;
this->uc = uc;
}
void Variant::construct( short s )
{
mSize = sizeof(s);
mType = std::string(typeid(s).name());
mSharedMemory = false;
this->s = s;
}
void Variant::construct( unsigned short us )
{
mSize = sizeof(us);
mType = std::string(typeid(us).name());
mSharedMemory = false;
this->us = us;
}
void Variant::construct( int i )
{
mSize = sizeof(i);
mType = std::string(typeid(i).name());
mSharedMemory = false;
this->i = i;
}
void Variant::construct( unsigned int ui )
{
mSize = sizeof(ui);
mType = std::string(typeid(ui).name());
mSharedMemory = false;
this->ui = ui;
}
void Variant::construct( long long ll )
{
mSize = sizeof(ll);
mType = std::string(typeid(ll).name());
mSharedMemory = false;
this->ll = ll;
}
void Variant::construct( unsigned long long ull )
{
mSize = sizeof(ull);
mType = std::string(typeid(ull).name());
mSharedMemory = false;
this->ull = ull;
}
void Variant::construct( float f )
{
mSize = sizeof(f);
mType = std::string(typeid(f).name());
mSharedMemory = false;
this->f = f;
}
void Variant::construct( double d )
{
mSize = sizeof(d);
mType = std::string(typeid(d).name());
mSharedMemory = false;
this->d = d;
}
void Variant::construct( void* ptr )
{
mSize = sizeof(ptr);
mType = std::string(typeid(ptr).name());
mSharedMemory = false;
this->ptr = ptr;
}
//--
char Variant::toChar() const
{
return c;
}
unsigned char Variant::toUChar() const
{
return uc;
}
short Variant::toShort() const
{
return s;
}
unsigned short Variant::toUShort() const
{
return us;
}
int Variant::toInt() const
{
return i;
}
unsigned int Variant::toUInt() const
{
return ui;
}
long long Variant::toLongLong() const
{
return ll;
}
unsigned long long Variant::toULongLong() const
{
return ull;
}
float Variant::toFloat() const
{
return f;
}
double Variant::toDouble() const
{
return d;
}
void* Variant::toVoidPtr() const
{
return ptr;
}
tstring Variant::toString() const
{
return stlu::toString<int>(i);
}
| true |
ceaed554a3c79bb9707dc3409926b58b6850748d | C++ | srobbins511/Assignment4 | /Student.cpp | UTF-8 | 304 | 2.75 | 3 | [] | no_license | #include "Student.h"
Student::Student()
{
timeWaiting = 0;
id = 0;
timeArrival = 0;
waitTime = 0;
}
Student::Student(int i, unsigned int wt, unsigned int ta)
{
timeWaiting = 0;
id = i;
waitTime = wt;
timeArrival = ta;
}
Student::~Student()
{
} | true |
5d8584dc26df019fc28ecf0005c744be42ecb970 | C++ | ktaishev/lw | /source.cpp | UTF-8 | 22,941 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <sstream>
#include <locale>
#include <set>
#include "utility.h"
#include "set_of_kss.h"
#include "set_of_pipes.h"
#include "graph.h"
void pipes_setup(set_of_pipes&);
void ks_setup(set_of_kss&);
void graph_setup(set_of_pipes&, set_of_kss&, graph&);
int main()
{
set_of_pipes pipes;
set_of_kss kss;
graph g;
setlocale(LC_ALL, "Russian");
std::cout << "Лабораторная работа за 1 семестр 2 курса" << std::endl;
bool finish = false;
print_main_menu();
while (!finish)
{
std::cout << "\tВыбранный пункт: ";
int msg = get_number(0, 4);
if (msg == 0)
{
finish = true;
std::cout << "\tЗавершение работы" << std::endl;
}
else if (msg == 1)
{
pipes_setup(pipes);
std::cout << "\tВы в главном меню" << std::endl;
print_main_menu();
}
else if (msg == 2)
{
ks_setup(kss);
std::cout << "\tВы в главном меню" << std::endl;
print_main_menu();
}
else if (msg == 3)
{
graph_setup(pipes, kss, g);
std::cout << "\tВы в главном меню" << std::endl;
print_main_menu();
}
else if (msg == 4)
{
print_main_menu();
}
else
{
std::cout << "\tКоманда не распознана. Повторите ввод. Введите 4 для получения помощи" << std::endl;
}
}
return 0;
}
void pipes_setup(set_of_pipes& pipes)
{
bool finish = false;
print_pipe_menu();
while (!finish)
{
std::cout << "\tВыбранный пункт: ";
int msg = get_number(0, 12);
if (msg == 0)
{
finish = true;
}
else if (msg == 1)
{
std::cout << "\tВведите параметры трубы:" << std::endl;
std::cout << "\tВведите длину: ";
int length_tmp = get_number(0, INT_MAX);
std::cout << "\tВведите диаметр (500-1420): ";
int diameter_tmp = get_number(500, 1420);
pipes.add_pipe(length_tmp, diameter_tmp);
std::cout << "\tТруба успешно добавлена" << std::endl;
PRINT_HASH_LINE;
}
else if (msg == 2)
{
std::cout << "\tВведите ID удаляемой трубы: ";
int index = get_number(0, pipes.return_pipe_count() - 1);
pipes.delete_pipe(index);
std::cout << "\tТруба ID " << index << " успешно удалена" << std::endl;
PRINT_HASH_LINE;
}
else if (msg == 3)
{
std::cout << "\tВведите ID трубы для изменения статуса ремонта: ";
int index = get_number(0, pipes.return_pipe_count() - 1);
pipes.change_repair_status(index);
PRINT_HASH_LINE;
}
else if (msg == 4)
{
pipes.print_all_pipes_to_console();
PRINT_HASH_LINE;
}
else if (msg == 5)
{
std::cout << "\tВведите ID трубы для выбора: ";
int index = get_number(0, pipes.return_pipe_count() - 1);
pipes.select_pipe(index);
PRINT_HASH_LINE;
}
else if (msg == 6)
{
std::cout << "\tВведите ID трубы для удаления из выбранных: ";
int index = get_number(0, pipes.return_pipe_count() - 1);
pipes.deselect_pipe(index);
PRINT_HASH_LINE;
}
else if (msg == 7)
{
pipes.print_selected_pipes_to_console();
PRINT_HASH_LINE;
}
else if (msg == 8)
{
std::cout << "\tВыберите параметр для поиска (ID - 0 | Длина - 1 | Диаметр - 2 | Состояние работоспособности - 3): ";
int parametr_id = get_number(0, 3);
if (parametr_id == 0)
{
std::cout << "\tВведите ID: ";
int index = get_number(0, pipes.return_pipe_count() - 1);
pipes.search_pipe(index, index, 0);
}
else if (parametr_id == 1)
{
std::cout << "\tВведите минимальное значение: ";
int left = get_number(0, INT_MAX);
std::cout << "\tВведите максимальное значение: ";
int right = get_number(left, INT_MAX);
pipes.search_pipe(left, right, 1);
}
else if (parametr_id == 2)
{
std::cout << "\tВведите минимальное значение: ";
int left = get_number(0, INT_MAX);
std::cout << "\tВведите максимальное значение: ";
int right = get_number(left, INT_MAX);
pipes.search_pipe(left, right, 2);
}
else
{
std::cout << "\tВведите состояние трубы для поиска (Работает - 0 | В ремонте - 1): ";
int param = get_number(0, 1);
pipes.search_pipe(param, param, 3);
}
PRINT_HASH_LINE;
}
else if (msg == 9)
{
std::cout << "\tВыберите параметр для группового изменения (Длина - 1 | Диаметр - 2 | Состояние работоспособности - 3): ";
int parametr_id = get_number(1, 3);
std::cout << "\tВведите новое значение: ";
int new_value;
if (parametr_id == 1)
new_value = get_number(0, INT_MAX);
else if (parametr_id == 1)
new_value = get_number(500, 1420);
else
new_value = get_number(0, 1);
pipes.bunch_editing_pipe(new_value, parametr_id);
PRINT_HASH_LINE;
}
else if (msg == 10)
{
pipes.save_to_file();
PRINT_HASH_LINE;
}
else if (msg == 11)
{
pipes.load_from_file();
PRINT_HASH_LINE;
}
else if (msg == 12)
{
print_pipe_menu();
}
else
{
std::cout << "\tКоманда не распознана. Повторите ввод. Введите 11 для получения помощи" << std::endl;
PRINT_HASH_LINE;
}
}
}
void ks_setup(set_of_kss& kss)
{
bool finish = false;
print_ks_menu();
while (!finish)
{
std::cout << "\tВыбранный пункт: ";
int msg = get_number(0, 13);
if (msg == 0)
{
finish = true;
}
else if (msg == 1)
{
std::cout << "\tВведите параметры компрессорной станции:" << std::endl;
std::cout << "\tВведите имя: ";
std::string name_tmp;
std::cin >> name_tmp;
std::cout << "\tВведите количество цехов: ";
int num_of_shops_tmp = get_number(0, INT_MAX);
std::cout << "\tВведите количество активных цехов: ";
int num_of_active_shops_tmp = get_number(0, num_of_shops_tmp);
std::cout << "\tВведите эффективность (0-100): ";
int efficiency = get_number(0, 100);
kss.add_ks(name_tmp, num_of_shops_tmp, num_of_active_shops_tmp, efficiency / 100.0);
std::cout << "\tКомпрессорная станция успешно добавлена" << std::endl;
PRINT_HASH_LINE;
}
else if (msg == 2)
{
std::cout << "\tВведите ID удаляемой компрессорной станции: ";
int index = get_number(0, kss.return_ks_count() - 1);
kss.delete_ks(index);
std::cout << "\tКомрпессорная станция ID " << index << " успешно удалена" << std::endl;
PRINT_HASH_LINE;
}
else if (msg == 3)
{
std::cout << "\tВведите ID трубы для изменения закрытия цеха: ";
int index = get_number(0, kss.return_ks_count() - 1);
kss.close_shop(index);
PRINT_HASH_LINE;
}
else if (msg == 4)
{
std::cout << "\tВведите ID трубы для изменения открытия цеха: ";
int index = get_number(0, kss.return_ks_count() - 1);
kss.open_shop(index);
PRINT_HASH_LINE;
}
else if (msg == 5)
{
kss.print_all_kss_to_console();
PRINT_HASH_LINE;
}
else if (msg == 6)
{
std::cout << "\tВведите ID компрессорной станции для выбора: ";
int index = get_number(0, kss.return_ks_count() - 1);
kss.select_ks(index);
PRINT_HASH_LINE;
}
else if (msg == 7)
{
std::cout << "\tВведите ID компрессорной станции для удаления из выбранных: ";
int index = get_number(0, kss.return_ks_count() - 1);
kss.deselect_ks(index);
PRINT_HASH_LINE;
}
else if (msg == 8)
{
kss.print_selected_kss_to_console();
PRINT_HASH_LINE;
}
else if (msg == 9)
{
std::cout << "\tВыберите параметр для поиска (ID - 0 | Имя - 1 | Количество цехов - 2 | Количество активных цехов - 3 | Эффективность - 4): ";
int parametr_id = get_number(0, 4);
if (parametr_id == 0)
{
std::cout << "\tВведите ID: ";
int index = get_number(0, kss.return_ks_count() - 1);
kss.search_ks(index, index, 0);
}
else if (parametr_id == 1)
{
std::cout << "\tВведите имя для поиска: ";
std::string param;
std::cin >> param;
kss.search_ks_by_name(param);
}
else if (parametr_id == 2)
{
std::cout << "\tВведите минимальное значение: ";
int left = get_number(0, INT_MAX);
std::cout << "\tВведите максимальное значение: ";
int right = get_number(left, INT_MAX);
kss.search_ks(left, right, 2);
}
else
{
std::cout << "\tВведите минимальное значение: ";
int left = get_number(0, INT_MAX);
std::cout << "\tВведите максимальное значение: ";
int right = get_number(left, INT_MAX);
kss.search_ks(left, right, 4);
}
std::cout << "\tПараметр успешно изменен" << std::endl;
PRINT_HASH_LINE;
}
else if (msg == 10)
{
std::cout << "\tВыберите параметр для группового изменения (Имя - 1 | Количество цехов - 2 | Количество активных цехов - 3 | Эффективность - 4): ";
int parametr_id = get_number(1, 4);
std::cout << "\tВведите новое значение: ";
if (parametr_id == 1)
{
std::string new_value;
std::cin >> new_value;
kss.bunch_editing_ks_name(new_value);
}
else if (parametr_id == 2 || parametr_id == 3)
{
int new_value = get_number(0, INT_MAX);
kss.bunch_editing_ks(new_value, parametr_id);
}
else
{
int new_value = get_number(0, 100);
kss.bunch_editing_ks(new_value / 100.0 , parametr_id);
}
PRINT_HASH_LINE;
}
else if (msg == 11)
{
kss.save_to_file();
PRINT_HASH_LINE;
}
else if (msg == 12)
{
kss.load_from_file();
PRINT_HASH_LINE;
}
else if (msg == 13)
{
print_ks_menu();
}
else
{
std::cout << "\tКоманда не распознана. Повторите ввод. Введите 13 для получения помощи" << std::endl;
PRINT_HASH_LINE;
}
}
}
void graph_setup(set_of_pipes& pipes, set_of_kss& kss, graph& g)
{
unsigned int free_nodes_count = kss.return_ks_count();
unsigned int free_edges_count = pipes.return_pipe_count();
bool finish = false;
print_graph_menu();
g.init(kss.return_ks_count());
while (!finish)
{
std::cout << "\tВыбранный пункт: ";
int msg = get_number(0, 11);
if (msg == 0)
{
finish = true;
}
else if (msg == 1)
{
std::cout << "\tВведите ID компрессорной станции для добавленив в граф: ";
int index = get_number(0, kss.return_ks_count() - 1);
if (kss.is_node(index) == true)
std::cout << "\tКомпрессорная станция уже является веришной" << std::endl;
else
{
g.add_node(index);
kss.set_node(index, true);
}
PRINT_HASH_LINE;
}
else if (msg == 2)
{
std::cout << "\tВведите ID компрессорной станции для удаления из графа: ";
int index = get_number(0, g.return_node_count() - 1);
if (kss.is_node(index) == false)
std::cout << "\tКомпрессорная станция не является веришной" << std::endl;
else
{
auto edges_to_free = g.delete_node(index);
for (auto it = edges_to_free.begin(); it != edges_to_free.end(); it++)
pipes.set_edge(*it, false);
kss.set_node(index, false);
}
PRINT_HASH_LINE;
}
else if (msg == 3)
{
std::cout << "\tВведите ID компрессорной станции для просмотра: ";
int index = get_number(0, g.return_node_count() - 1);
if (kss.is_node(index) == false)
std::cout << "\tКомпрессорная станция не является веришной" << std::endl;
else
g.print_node(index);
PRINT_HASH_LINE;
}
else if (msg == 4)
{
//Печатает информацию о всех вершинах, даже не инициализированных
//Возможно стоит делать запуск отсюда print_node для всех кс, которые вершины
std::cout << "\tВсе вершины:" << std::endl;
g.print_nodes();
PRINT_HASH_LINE;
}
else if (msg == 5)
{
//Один раз поймал ошибку vector range error, обращение было к 0 трубе
//В дальнейшем повторить ошибку не удалось
std::cout << "\tВведите начальную вершину для соединения: ";
unsigned int node1 = get_number(0, g.return_node_count() - 1);
std::cout << "\tВведите конечную вершину для соединения: ";
unsigned int node2 = get_number(0, g.return_node_count() - 1);
if (kss.is_node(node1) == false)
std::cout << "\tКомпресорная станция ID " << node1 << " не является вершиной" << std::endl;
else if (kss.is_node(node2) == false)
std::cout << "\tКомпресорная станция ID " << node2 << " не является вершиной" << std::endl;
else if (node1 == node2)
std::cout << "\tНевозможно соединить вершину с самой собой";
else
{
std::cout << "\tВведите соединяющую трубу: ";
unsigned int pipe_id = get_number(0, pipes.return_pipe_count() - 1);
if (pipes.is_edge(pipe_id) == true)
std::cout << "\tТруба уже задействована в нефтесети, соединение с помощью нее не возможно" << std::endl;
else
{
g.connect_two_nodes(node1, node2, pipe_id);
pipes.set_nodes(pipe_id, node1, node2);
pipes.set_edge(pipe_id, true);
}
}
PRINT_HASH_LINE;
}
else if (msg == 6)
{
std::cout << "\tВведите начальную вершину для отсоединения: ";
unsigned int node1 = get_number(0, g.return_node_count() - 1);
std::cout << "\tВведите конечную вершину для отсоединения: ";
unsigned int node2 = get_number(0, g.return_node_count() - 1);
int pipe_id = g.disconnect_two_nodes(node1, node2);
if (pipe_id != -1)
pipes.set_edge(pipe_id, false);
PRINT_HASH_LINE;
}
else if (msg == 7)
{
std::cout << "\tВведите вершины, дуги между которыми нужно развернуть: " << std::endl;
std::cout << "\tВведите начальную вершину: ";
unsigned int node1 = get_number(0, g.return_node_count() - 1);
std::cout << "\tВведите конечную вершину: ";
unsigned int node2 = get_number(0, g.return_node_count() - 1);
if (node1 == node2)
std::cout << "\tВведите две отличные вершины";
else
g.redirect_arc(node1, node2);
PRINT_HASH_LINE;
}
else if (msg == 8)
{
g.top_sort();
std::cout << "\tТопологическая сортировка завершена" << std::endl;
PRINT_HASH_LINE;
}
else if (msg == 9)
{
std::cout << "\tВведите начальную вершину: ";
unsigned int node1 = get_number(0, g.return_node_count() - 1);
std::cout << "\tВведите конечную вершину: ";
unsigned int node2 = get_number(0, g.return_node_count() - 1);
std::cout << "\tОтобразить кратчайший путь? (Нет - 0 | Да - 1): ";
bool show_path = get_number(0, 1);
if (kss.is_node(node1) == false)
std::cout << "\tКомпресорная станция ID " << node1 << " не является вершиной" << std::endl;
else if (kss.is_node(node2) == false)
std::cout << "\tКомпресорная станция ID " << node2 << " не является вершиной" << std::endl;
else if (node1 == node2)
{
std::cout << "\tДистанция: 0" << std::endl;
if (show_path)
{
std::cout << "\tКратчайший путь: V(" << node1 << ") -> V(" << node2 << ")" << std::endl;
}
}
else
{
auto [distance, path] = g.minimal_distance(node1, node2, pipes);
if (distance == UINT_MAX)
std::cout << "\tНе существует пути между указанными вершинами" << std::endl;
else
{
std::cout << "\tДистанция: " << distance << std::endl;
if (show_path)
{
std::cout << "\tКратчайший путь: ";
for (auto rit = path.rbegin(); rit + 1!= path.rend(); rit++)
std::cout << "V(" << *rit << ") -> ";
std::cout << "V(" << *(path.rend() - 1) << ")" << std::endl;
}
}
}
PRINT_HASH_LINE;
}
else if (msg == 10)
{
std::cout << "\tВведите начальную вершину: ";
unsigned int node1 = get_number(0, g.return_node_count() - 1);
std::cout << "\tВведите конечную вершину: ";
unsigned int node2 = get_number(0, g.return_node_count() - 1);
if (kss.is_node(node1) == false)
std::cout << "\tКомпресорная станция ID " << node1 << " не является вершиной" << std::endl;
else if (kss.is_node(node2) == false)
std::cout << "\tКомпресорная станция ID " << node2 << " не является вершиной" << std::endl;
else if (node1 == node2)
{
std::cout << "\tПоток равен бесконечности, указаны идентичные вершины" << std::endl;
}
else
{
auto flow = g.max_flow(node1, node2, pipes);
std::cout << "\tПоток между указанными вершинами: " << flow << std::endl;
}
PRINT_HASH_LINE;
}
else if (msg == 11)
{
print_graph_menu();
}
else
{
std::cout << "\tКоманда не распознана. Повторите ввод. Введите 4 для получения помощи" << std::endl;
}
}
} | true |
f5425d24a1b61811c546376d73b1e6f9bc5901ff | C++ | MattMarti/Rocketry-VT_MotorControl_v1.0.0 | /include/filters.hpp | UTF-8 | 3,325 | 2.90625 | 3 | [] | no_license | #ifndef FILTERS_H
#define FILTERS_H
#include <cstdint>
#include <cmath>
#include <deque>
class low_pass
{
public:
double value, rc;
low_pass(double rc);
double step(double sample, double dt);
private:
bool first;
};
class high_pass
{
public:
double value, rc;
high_pass(double rc);
double step(double sample, double dt);
private:
low_pass lpf;
};
class running_average
{
public:
double value;
unsigned num_samples;
running_average();
double step(double sample);
};
class moving_average
{
public:
double value;
unsigned num_samples;
moving_average(unsigned num_samples);
double step(double sample);
private:
running_average ravg;
std::deque<double> samples;
};
class running_variance
{
public:
double value;
running_variance();
double step(double sample);
private:
unsigned num_samples;
double S;
running_average mean;
};
template <uint8_t N> class derivative
{
public:
double value;
const uint8_t freq;
const double dt;
const static int order = N;
derivative<N>(uint8_t freq = 1) : value(0), freq(freq),
dt(1.0/freq), current(NAN), samples(0), d_dx(freq) { };
double step(double sample)
{
return step(sample, 1.0/freq);
}
double step(double sample, double dx)
{
if (samples <= N) samples++;
double slope = d_dx(sample, dx);
double last = current;
current = slope;
if (samples <= N) return 0;
if (dx == 0) return 0;
else return (value = (slope - last) / dx);
}
double operator () (double x) { return step(x); }
double operator () (double x, double dx) { return step(x, dx); }
void reset()
{
value = 0;
current = NAN;
samples = 0;
d_dx.reset();
}
private:
double current;
uint8_t samples;
derivative<N-1> d_dx;
};
template <> class derivative<0>
{
public:
derivative(uint8_t) { };
double step(double sample) { return sample; }
double step(double sample, double) { return sample; }
double operator () (double x) { return x; }
double operator () (double x, double) { return x; }
void reset() { }
};
template <uint8_t N> class integral
{
public:
double value;
const uint8_t freq;
const double dt;
const static int order = N;
integral<N>(uint8_t freq = 1) : value(0), freq(freq),
dt(1.0/freq), sum_dx(freq) { }
double step(double sample)
{
return (value += sum_dx(sample) * dt);
}
double operator () (double x) { return step(x); }
void reset()
{
value = 0;
sum_dx.reset();
}
private:
integral<N-1> sum_dx;
};
template <> class integral<0>
{
public:
integral(uint8_t) { };
double step(double sample) { return sample; }
double operator () (double x) { return x; }
void reset() { }
};
class range_accumulator
{
public:
double value;
const double range;
range_accumulator(double range);
range_accumulator(double min, double max);
double step(double bounded);
double operator () (double b);
private:
bool first;
double previous;
derivative<1> diff;
};
#endif // FILTERS_H
| true |
8d104b852916fe8bb104cc73da8b7ba584204655 | C++ | AlexeyG/HackerRank | /implementation/ViralAdvertising/main.cpp | UTF-8 | 395 | 2.765625 | 3 | [] | no_license | #include <iostream>
using namespace std;
long long solve(int day, int shared_day1=5) {
int shared = shared_day1;
int liked;
long long liked_total = 0;
while (day--) {
liked = shared / 2;
liked_total += liked;
shared = liked * 3;
}
return liked_total;
}
int main() {
int day;
cin >> day;
cout << solve(day) << endl;
return 0;
} | true |
b784b94ac19ca2ab901a912d394dcf10feeb9189 | C++ | Zanzal/X-Studio2-Mirror | /Logic/EncryptedX3Stream.cpp | UTF-8 | 5,995 | 3.046875 | 3 | [
"MIT"
] | permissive | #include "stdafx.h"
#include "EncryptedX3Stream.h"
namespace Logic
{
namespace IO
{
// -------------------------------- CONSTRUCTION --------------------------------
/// <summary>Creates an encrypted file stream using another stream as input</summary>
/// <param name="src">The input stream.</param>
/// <exception cref="Logic::ArgumentNullException">Stream is null</exception>
EncryptedX3Stream::EncryptedX3Stream(StreamPtr src) : StreamDecorator(src), DECRYPT_KEY(0)
{
}
/// <summary>Creates an encrypted file stream using a file as input</summary>
/// <param name="path">The full path.</param>
/// <param name="mode">The creation mode.</param>
/// <param name="access">The file access.</param>
/// <param name="share">The sharing permitted.</param>
/// <exception cref="Logic::FileNotFoundException">File not found</exception>
/// <exception cref="Logic::IOException">An I/O error occurred</exception>
EncryptedX3Stream::EncryptedX3Stream(Path path, FileMode mode, FileAccess access, FileShare share)
: StreamDecorator( StreamPtr(new FileStream(path, mode, access, share)) ), DECRYPT_KEY(0)
{
}
/// <summary>Closes the stream without throwing</summary>
EncryptedX3Stream::~EncryptedX3Stream()
{
StreamDecorator::SafeClose();
}
// ------------------------------- STATIC METHODS -------------------------------
/// <summary>Determines whether a stream uses X3:TC file encryption.</summary>
/// <param name="s">stream.</param>
/// <returns></returns>
bool EncryptedX3Stream::IsEncrypted(StreamPtr s)
{
// Verify length
if (s->GetLength() < 3)
return false;
// Prepare
DWORD origin = s->GetPosition();
WORD header, key;
// Generate key: XOR first byte with 0xC8
s->Seek(0, SeekOrigin::Begin);
s->Read(reinterpret_cast<byte*>(&key), 1);
key ^= DECRYPT_SEED;
// Generate WORD from first byte
reinterpret_cast<byte*>(&key)[1] = reinterpret_cast<byte*>(&key)[0];
// Read encrypted 2-byte header. reset position
s->Read(reinterpret_cast<BYTE*>(&header), 2);
s->Seek(origin, SeekOrigin::Begin);
// Check for encrypted GZip header
return (header ^ key) == 0x8b1f;
}
// ------------------------------- PUBLIC METHODS -------------------------------
/// <summary>Reads/decodes from the stream into the specified buffer.</summary>
/// <param name="buffer">The destination buffer</param>
/// <param name="length">The length of the buffer</param>
/// <returns>Number of bytes read</returns>
/// <exception cref="Logic::ArgumentNullException">Buffer is null</exception>
/// <exception cref="Logic::NotSupportedException">Stream is not readable</exception>
/// <exception cref="Logic::IOException">An I/O error occurred</exception>
DWORD EncryptedX3Stream::Read(BYTE* buffer, DWORD length)
{
REQUIRED(buffer);
// Init: Generate key from 1st byte
if (DECRYPT_KEY == 0)
{
// Read first byte
DWORD origin = StreamDecorator::GetPosition();
StreamDecorator::Seek(0, SeekOrigin::Begin);
StreamDecorator::Read(&DECRYPT_KEY, 1);
StreamDecorator::Seek(origin, SeekOrigin::Begin);
// Generate key
DECRYPT_KEY ^= DECRYPT_SEED;
}
// Skip reading first byte
if (StreamDecorator::GetPosition() == 0)
StreamDecorator::Seek(1, SeekOrigin::Begin);
// Read+decode buffer
DWORD bytesRead = StreamDecorator::Read(buffer, length);
Encode(buffer, bytesRead);
// Return length
return bytesRead;
}
/// <summary>Writes/encodes the specified buffer to the stream</summary>
/// <param name="buffer">The buffer.</param>
/// <param name="length">The length of the buffer.</param>
/// <returns>Number of bytes written</returns>
/// <exception cref="Logic::ArgumentNullException">Buffer is null</exception>
/// <exception cref="Logic::NotSupportedException">Stream is not writeable</exception>
/// <exception cref="Logic::IOException">An I/O error occurred</exception>
DWORD EncryptedX3Stream::Write(const BYTE* buffer, DWORD length)
{
REQUIRED(buffer);
DWORD keylen = 0;
// Init: Generate key and write to first byte
if (DECRYPT_KEY == 0 && length > 0)
{
// Verify position
if (StreamDecorator::GetPosition() != 0)
throw IOException(HERE, L"First write operation must be positioned at start of stream");
// Generate/write key
DECRYPT_KEY = buffer[0] ^ DECRYPT_SEED;
StreamDecorator::Write(&DECRYPT_KEY, 1);
keylen = 1;
}
// Copy buffer so we can encode it
ByteArrayPtr copy(new BYTE[length]);
memcpy(copy.get(), buffer, length);
// Encode + Write
Encode(copy.get(), length);
return StreamDecorator::Write(copy.get(), length) + keylen;
}
// ------------------------------ PROTECTED METHODS -----------------------------
// ------------------------------- PRIVATE METHODS ------------------------------
/// <summary>Encodes a byte array</summary>
/// <param name="buffer">Buffer to encode</param>
/// <param name="length">Length of buffer</param>
void EncryptedX3Stream::Encode(byte* buffer, DWORD length)
{
// Encode buffer
for (DWORD i = 0; i < length; i++)
buffer[i] ^= DECRYPT_KEY;
}
}
} | true |
9adc913b51549c6ec4aede7e90d819ae687b9ca2 | C++ | ygalkin/coding-challenges | /src/leetcode/remove-duplicates-from-sorted-array.h | UTF-8 | 454 | 3.1875 | 3 | [] | no_license | // https://leetcode.com/problems/remove-duplicates-from-sorted-array/
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.empty()) {
return 0;
}
size_t unique{ 0 };
for (size_t i{ 1 }; i < nums.size(); ++i) {
if (nums[i] != nums[unique]) {
++unique;
nums[unique] = nums[i];
}
}
return unique + 1;
}
};
| true |
1277070041eae5ce3e9ddd1cb7575db293e9e4e7 | C++ | algoparc/1DVisibilityIndex | /src/BuildConvexHull.cpp | UTF-8 | 7,002 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | /*
Copyright 2016-2018 Ben Karsin, Nodari Sitchinava, Colin Lambrechts
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "BuildConvexHull.h"
#include<stdlib.h>
#include<stdio.h>
//=====Constructors=============================================================
/* Not needed to implement as there are no variables etc.
BuildConvexHull::BuildConvexHull() {
}
BuildConvexHull::BuildConvexHull(const BuildConvexHull& orig) {
}
BuildConvexHull& BuildConvexHull::operator=(const BuildConvexHull& orig) {
}
BuildConvexHull::~BuildConvexHull() {
}*/
//=====Getters and Setters======================================================
//=====Methods==================================================================
Hull* buildAndSaveHull(Ray* crits, int numPoints) {
//The temporary list that contains the convex hull points (including the artificial points)
Hull* tmpHull = (Hull*)malloc(sizeof(Hull));
tmpHull->crits = (Ray**)malloc((numPoints)*sizeof(Ray*));
tmpHull->size = 0; //Denotes the current size of the convex hull
tmpHull->crits[0] = &crits[0];
tmpHull->size += 1;
for (int i = 0; i < numPoints; i++) {
//remove all points that violate the convex hull property
while (tmpHull->size >= 2 && //and the sequence of the last two points with the selected point does not make a counter-clockwise turn
(1LL*(tmpHull->crits[tmpHull->size - 1]->y - tmpHull->crits[tmpHull->size - 2]->y) * (crits[i].x - tmpHull->crits[tmpHull->size - 1]->x)
- 1LL*(tmpHull->crits[tmpHull->size - 1]->x - tmpHull->crits[tmpHull->size - 2]->x) * (crits[i].y - tmpHull->crits[tmpHull->size - 1]->y))
<= 0LL) {
//Remove the last point from tmpHull
// tmpHull[tmpHull->size] = nullptr;
tmpHull->size -= 1;
}
//append the last selected point to
tmpHull->crits[tmpHull->size] = &crits[i];
tmpHull->size += 1;
}
//append the last point
// tmpHull->points[tmpHull->size] = *e;
// tmpHull->crits[tmpHull->size] = &crits[numPoints - 1];
// tmpHull->size += 1;
//optimise array size and require dynamically allocated array, because of sharing
Hull* newHull = (Hull*)malloc(sizeof(Hull));
newHull->size = tmpHull->size;
newHull->crits = (Ray**)malloc(tmpHull->size*sizeof(Ray*));
for(int j=0; j<tmpHull->size; j++) {
newHull->crits[j] = tmpHull->crits[j];
}
free(tmpHull);
//actually use the ConvexHull class and return
// l = hull;
// return tmpHull->size;
return newHull;
// return new ConvexHull(hull, tmpHull->size);
}
int buildConvexHull(Point* l, int numPoints) {
//The temporary list that contains the convex hull points (including the artificial points)
Point* tmpHull = new Point[numPoints + 2];
int hullSize = 0; //Denotes the current size of the convex hull
Point* s = new Point(l[0].getX(), -1);
Point* e = new Point(l[numPoints - 1].getX(), -1);
tmpHull[0] = *s; // append the first point
hullSize += 1;
for (int i = 0; i < numPoints; i++) {
//remove all points that violate the convex hull property
while (hullSize >= 2 && //and the sequence of the last two points with the selected point does not make a counter-clockwise turn
(1LL*(tmpHull[hullSize - 1].getY() - tmpHull[hullSize - 2].getY()) * (l[i].getX() - tmpHull[hullSize - 1].getX())
- 1LL*(tmpHull[hullSize - 1].getX() - tmpHull[hullSize - 2].getX()) * (l[i].getY() - tmpHull[hullSize - 1].getY()))
<= 0LL) {
//Remove the last point from tmpHull
// tmpHull[hullSize] = nullptr;
hullSize -= 1;
}
//append the last selected point to
tmpHull[hullSize] = l[i];
hullSize += 1;
}
//append the last point
tmpHull[hullSize] = *e;
hullSize += 1;
//optimise array size and require dynamically allocated array, because of sharing
Point* hull = new Point[hullSize];
for (int j = 0; j < hullSize; j++) {
hull[j] = tmpHull[j];
}
delete[] tmpHull;
//actually use the ConvexHull class and return
l = hull;
return hullSize;
// return new ConvexHull(hull, hullSize);
}
/*
Hull* buildConvexHullPar(Point* l, Ray* crits, int numPoints) {
//The temporary list that contains the convex hull points (including the artificial points)
Hull* tmpHull = (Hull*)malloc(sizeof(Hull));
tmpHull->points = (Point*)malloc((numPoints)*sizeof(Point));
tmpHull->crits = (Ray**)malloc((numPoints)*sizeof(Ray*));
tmpHull->size = 0; //Denotes the current size of the convex hull
Point* s = &l[0];
Point* e = &l[numPoints-1];
tmpHull->points[0] = *s; // append the first point
tmpHull->crits[0] = crits;
tmpHull->size += 1;
for (int i = 0; i < numPoints; i++) {
//remove all points that violate the convex hull property
while (tmpHull->size >= 2 && //and the sequence of the last two points with the selected point does not make a counter-clockwise turn
(1LL*(tmpHull->points[tmpHull->size - 1].getY() - tmpHull->points[tmpHull->size - 2].getY()) * (l[i].getX() - tmpHull->points[tmpHull->size - 1].getX())
- 1LL*(tmpHull->points[tmpHull->size - 1].getX() - tmpHull->points[tmpHull->size - 2].getX()) * (l[i].getY() - tmpHull->points[tmpHull->size - 1].getY()))
<= 0LL) {
//Remove the last point from tmpHull
// tmpHull[tmpHull->size] = nullptr;
tmpHull->size -= 1;
}
//append the last selected point to
tmpHull->points[tmpHull->size] = l[i];
tmpHull->crits[tmpHull->size] = &crits[i];
tmpHull->size += 1;
}
//append the last point
// tmpHull->points[tmpHull->size] = *e;
// tmpHull->crits[tmpHull->size] = &crits[numPoints - 1];
// tmpHull->size += 1;
//optimise array size and require dynamically allocated array, because of sharing
// Point* hull = new Point[tmpHull->size];
// for (int j = 0; j < tmpHull->size; j++) {
// hull[j] = tmpHull[j];
// }
// delete[] tmpHull;
//actually use the ConvexHull class and return
// l = hull;
// return tmpHull->size;
return tmpHull;
// return new ConvexHull(hull, tmpHull->size);
}
*/
| true |
2eb4e4d03d1829a1f2b0b3c7c55fd2cde3f6839f | C++ | BradfordMedeiros/ModEngine | /src/common/util_test.cpp | UTF-8 | 2,747 | 2.78125 | 3 | [] | no_license | #include "./util_test.h"
void utilParseAndSerializeQuatTest() {
std::vector<std::string> rawQuatsTests = {
"0 0 -1 45", // 0
"3 3 3 10", // 1
"3 3 3 250", // 2
"1 2 3 30", // 3
"3 3 3 10", // 4
"1 0 -1 0", // 5
"4 3 34 0", // 6
"4 3 34 70", // 7
"0 0 -1 30", // 8
"2 -1 0 250", // 9
"0 0 -1 30", // 10
"0 1 0 30", // 11
"0 -1 0 0", // 12
"0 1 0 0", // 13
"0 1 0 354", // 14
};
int numFailingTests = 0;
std::string errorStr = "\n";
for (int i = 0; i < rawQuatsTests.size(); i++){
auto rawquat = rawQuatsTests.at(i);
auto rawParsed = parseVec4(rawquat);
auto normalizedRaw = glm::normalize(glm::vec3(rawParsed.x, rawParsed.y, rawParsed.z));
auto normalizedRaw4 = glm::vec4(normalizedRaw.x, normalizedRaw.y, normalizedRaw.z, rawParsed.w);
auto serializedParsed = parseVec4(serializeQuat(parseQuat(parseVec4(rawQuatsTests.at(i)))));
if (!aboutEqual(normalizedRaw4, serializedParsed)){
numFailingTests++;
errorStr = errorStr + "test: " + std::to_string(i) + " - " + "got : " + print(serializedParsed) + " but wanted: " + print(normalizedRaw4) + " - original: " + print(rawParsed) + "\n";
}
}
if (errorStr != ""){
throw std::logic_error("num failing tests: " + std::to_string(numFailingTests) + errorStr);
}
}
struct orientationPosTestPair {
glm::vec3 fromPos;
glm::vec3 toPos;
glm::vec3 expectedPos;
};
void orientationFromPosTest(){
std::vector<orientationPosTestPair> tests = {
orientationPosTestPair {
.fromPos = glm::vec3(0.f, 0.f, 0.f),
.toPos = glm::vec3(1.f, 0.f, 0.f),
.expectedPos = glm::vec3(1.f, 0.f, 0.f),
},
orientationPosTestPair {
.fromPos = glm::vec3(1.f, 1.f, 0.f),
.toPos = glm::vec3(2.f, 2.f, 0.f),
.expectedPos = glm::vec3(0.707107, 0.707107, 0.f),
},
orientationPosTestPair {
.fromPos = glm::vec3(2.f, 2.f, 0.f),
.toPos = glm::vec3(1.f, 1.f, 0.f),
.expectedPos = glm::vec3(-0.707107, -0.707107, 0.f),
},
orientationPosTestPair {
.fromPos = glm::vec3(0.f, 0.f, 0.f),
.toPos = glm::vec3(0.f, 2.f, 0.f),
.expectedPos = glm::vec3(0.f, 1.f, 0.f),
},
orientationPosTestPair {
.fromPos = glm::vec3(0.f, 2.f, 0.f),
.toPos = glm::vec3(0.f, 0.f, 0.f),
.expectedPos = glm::vec3(0.f, -1.f, 0.f),
},
};
for (auto &test : tests){
auto direction = orientationFromPos(test.fromPos, test.toPos);
auto newPosition = direction * glm::vec3(0.f, 0.f, -1.f);
if (!aboutEqual(newPosition, test.expectedPos)){
throw std::logic_error("unexpected position: expected: " + print(test.expectedPos) + " got: " + print(newPosition));
}
}
}
| true |
8fa0520f1a641696d2dfebd365c86caece25cd73 | C++ | rahulsah123/CodeMonk | /solutions/hackerrank/30-abstract-classes.cpp | UTF-8 | 1,234 | 3.34375 | 3 | [
"MIT"
] | permissive | /**
* @author yangyanzhan
* @email yangyanzhan@gmail.com
* @homepage http://www.yangyanzhan.com
* @github_project https://github.com/yangyanzhan/CodeMonk
* @online_judge hackerrank
* @problem_id 30-abstract-classes
* @problem_address https://www.hackerrank.com/challenges/30-abstract-classes
**/
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <iterator>
#include <map>
#include <regex>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
using namespace std;
class Book {
protected:
string title;
string author;
public:
Book(string t, string a) {
title = t;
author = a;
}
virtual void display() = 0;
};
class MyBook : public Book {
private:
int price;
public:
MyBook(string t, string a, int p) : Book(t, a) { price = p; }
void display() {
cout << "Title: " << title << endl;
cout << "Author: " << author << endl;
cout << "Price: " << price << endl;
}
};
int main(int argc, char *argv[]) {
string title, author;
int price;
getline(cin, title);
getline(cin, author);
cin >> price;
MyBook novel(title, author, price);
novel.display();
return 0;
}
| true |
c10e48d10be819384e653df3a3d0975d434d7b32 | C++ | PolytechAngersMecatroniqueClub/istiaENGRAIS | /engrais_control/src/9_WeightedModel/WeightedModel.cpp | UTF-8 | 4,083 | 3.296875 | 3 | [] | no_license | //********************************************************************************************************
#include "WeightedModel.h"
//--------------------------------------------------------------------------------------------------------
void WeightedModel::assignPoints(const Model & m, bool isFrontMsg){ //Assign points to weighted model
std::pair<Point, Point> points = m.getFirstAndLastPoint(!isFrontMsg); //Get closest and farthest point
if(points.first.getX() >= 0){ //If closest point is positive, assign it to closest points
this->positivePoints.first = points.first;
this->positivePoints.second = points.second;
}
else{ //If they are negative, assign it to negative points
this->negativePoints.first = points.first;
this->negativePoints.second = points.second;
}
}
//--------------------------------------------------------------------------------------------------------
bool WeightedModel::checkIfSameModel(const Model & m) const { //Check if the two models are approximately the same
double slopeRatio = this->a / m.getSlope(); //Calculate slope ratio
double interceptRatio = this->b / m.getIntercept(); //Calculate intercept ratio
double slopeDifference = fabs(this->a - m.getSlope()); //Calculate slope difference
double interceptDifference = fabs(this->b - m.getIntercept()); //Calculate intercept difference
bool isSlopeTheSame = ((1 - Pearl::sameSlopeThreshold <= slopeRatio && slopeRatio <= 1 + Pearl::sameSlopeThreshold) || slopeDifference <= Pearl::sameSlopeThreshold); //Checks if slope is approximately the same
bool isInterceptTheSame = ((1 - Pearl::sameInterceptThreshold <= interceptRatio && interceptRatio <= 1 + Pearl::sameInterceptThreshold) || interceptDifference <= Pearl::sameInterceptThreshold); //Checks if interpect is approximately the same
if(isSlopeTheSame && isInterceptTheSame){ //Return true if both are the same
return true;
}
return false; //False otherwise
}
//--------------------------------------------------------------------------------------------------------
void WeightedModel::fuseModels(const Model & m, bool isFrontMsg){ //Calculate the final model using center of mass formula
this->a = (this->getSlope() * this->getTotalCounter() + m.getSlope()) / (double)(this->getTotalCounter() + 1); //Calculate the final slope
this->b = (this->getIntercept() * this->getTotalCounter() + m.getIntercept()) / (double)(this->getTotalCounter() + 1); //Calculate the final intercept
this->assignPoints(m, isFrontMsg); //Reassign points to the new models
this->cont[isFrontMsg]++; //Increment counter
}
//--------------------------------------------------------------------------------------------------------
Model WeightedModel::toModel() const { //Converts to regular model
Model ret(this->a, this->b); //Declare model with calculated slope and intercept
if(this->negativePoints.second.isAssigned()) //Assign negative-most point
ret.pushPoint(this->negativePoints.second);
else if(this->positivePoints.first.isAssigned())
ret.pushPoint(this->positivePoints.first);
if(this->positivePoints.second.isAssigned()) //Assign positive-most point
ret.pushPoint(this->positivePoints.second);
else if(this->negativePoints.first.isAssigned())
ret.pushPoint(this->negativePoints.first);
return ret;
}
//--------------------------------------------------------------------------------------------------------
std::ostream & operator << (std::ostream & out, const WeightedModel & wm){ //Print Object
out << "WeightedModel: [ a: " << wm.a << ", b: " << wm.b << ", contBack: " << wm.cont[0] << ", contFront: " << wm.cont[1] << std::endl;
out << wm.positivePoints.first << " " << wm.positivePoints.second << "]" << std::endl;
out << wm.negativePoints.first << " " << wm.negativePoints.second << "]" << std::endl;
return out;
}
//******************************************************************************************************** | true |
39a0915115a15eaf95b178113d134e64c2b3fb9a | C++ | HansKing98/OOP | /lesson04/main.cpp | UTF-8 | 308 | 3.375 | 3 | [] | no_license | #include <iostream>
using namespace std;
class point
{
public:
point(int rх, int rу)
{
x = rх;
y = rу;
}
void show() { cout << "(" << x << "," << y << ")" << endl; }
private:
int x;
int y;
};
int main()
{
point p(3, 4);
p.show();
} | true |
b2647417c5471375a4f7399b3edb8f8b861ab018 | C++ | SrTobi/xnet | /samples/network_interface_lister/network_interface_lister.cpp | UTF-8 | 690 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <xnet/network_interface_lister.hpp>
void print_network_interface(const boost::asio::ip::udp& protocol)
{
boost::asio::io_service service;
xnet::udp_interface_lister lister(service, protocol);
for (auto& entry : lister)
{
std::cout << " " << entry.host_name() << ": " << entry.endpoint().address() << std::endl;
}
}
int main()
{
std::cout << "Local ipv4 network interfaces:" << std::endl;
print_network_interface(boost::asio::ip::udp::v4());
std::cout << std::endl << std::endl;
std::cout << "Local ipv6 network interfaces:" << std::endl;
print_network_interface(boost::asio::ip::udp::v6());
#ifdef WIN32
std::cin.get();
#endif
return 0;
} | true |
e3f5ea2e0fc4abbc2c2f943fe7261a966ce25c11 | C++ | shuest/leetcode | /739.cpp | UTF-8 | 623 | 2.796875 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<cmath>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
using namespace std;
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
vector<int> res(temperatures.size());
stack<pair<int, int>> s;
int len = temperatures.size();
for(int i = 0; i < len; i++) {
while( !s.empty() && temperatures[i] > s.top().first) {
res[s.top().second] = i - s.top().second;
s.pop();
}
s.push(pair<int,int>(temperatures[i],i));
}
return res;
}
}; | true |
bfda2a552292fdd6dea674812591ab16f32335bc | C++ | FlorianZeni/Mage_2D_Game | /sources/FillBar.cpp | UTF-8 | 826 | 2.84375 | 3 | [] | no_license | //
// Created by zenif on 31/07/2021.
//
#include <iostream>
#include "FillBar.h"
FillBar::FillBar(sf::Vector2f position, sf::Vector2f size, float* maxValue, float* currentValue) :
GameObject(), position(position), size(size), maxValue(maxValue), currentValue(currentValue) {
backShape.setPosition(position);
frontShape.setPosition(position);
frontShape.setScale(*currentValue / *maxValue, 1);
backShape.setFillColor(sf::Color::Red);
frontShape.setFillColor(sf::Color::Green);
}
void FillBar::draw(sf::RenderWindow &window) {
updateBar();
window.draw(backShape);
window.draw(frontShape);
}
void FillBar::updateBar() {
frontShape.setScale(*currentValue / *maxValue, 1);
// std::cout << *currentValue / *maxValue << std::endl;
}
bool FillBar::toBeRemoved() {
return false;
}
| true |
181a236dead6cae2493066fb995c126d0a661b82 | C++ | mextier/Patience | /csprite.cpp | WINDOWS-1251 | 17,122 | 2.796875 | 3 | [] | no_license | //====================================================================================================
//
//====================================================================================================
#include "csprite.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "tga.h"
//====================================================================================================
//
//====================================================================================================
//----------------------------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------------------------
CSprite::CSprite(void)
{
Width=0;
Height=0;
Data=NULL;
}
//----------------------------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------------------------
CSprite::~CSprite()
{
Release();
}
//====================================================================================================
//
//====================================================================================================
//----------------------------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------------------------
uint32_t CSprite::ConvertColor(COLOR_MODE color_mode,uint32_t color)
{
uint8_t ir=0;
uint8_t ig=0;
uint8_t ib=0;
if (color_mode==COLOR_MODE_RGB)
{
ir=(color>>16)&0xFF;
ig=(color>>8)&0xFF;
ib=(color)&0xFF;
}
if (color_mode==COLOR_MODE_BGR)
{
ib=(color>>16)&0xFF;
ig=(color>>8)&0xFF;
ir=(color)&0xFF;
}
if (color_mode==COLOR_MODE_GBR)
{
ig=(color>>16)&0xFF;
ig=(color>>8)&0xFF;
ir=(color)&0xFF;
}
if (color_mode==COLOR_MODE_GRB)
{
ig=(color>>16)&0xFF;
ir=(color>>8)&0xFF;
ib=(color)&0xFF;
}
if (color_mode==COLOR_MODE_RBG)
{
ir=(color>>16)&0xFF;
ib=(color>>8)&0xFF;
ig=(color)&0xFF;
}
if (color_mode==COLOR_MODE_BRG)
{
ib=(color>>16)&0xFF;
ir=(color>>8)&0xFF;
ig=(color)&0xFF;
}
color=ir;
color<<=8;
color|=ig;
color<<=8;
color|=ib;
return(color);
}
//----------------------------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------------------------
uint32_t CSprite::ForwardColor(COLOR_MODE color_mode,uint32_t color)
{
return(color);
}
//====================================================================================================
//
//====================================================================================================
//====================================================================================================
//
//====================================================================================================
//----------------------------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------------------------
bool CSprite::Load(const char *file_name)
{
Release();
Data=reinterpret_cast<uint32_t*>(LoadTGAFromFile(file_name,Width,Height));
if (Data==NULL) return(false);
// -
uint32_t *ptr=Data;
int32_t n;
int32_t length=Width*Height;
uint32_t alpha_mask=0xFF;
alpha_mask<<=24;
for(n=0;n<length;n++)
{
uint32_t color=*ptr;
*ptr=(color&0x00FFFFFF)|alpha_mask;
ptr++;
}
return(true);
}
//----------------------------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------------------------
bool CSprite::Load(HMODULE hModule,int32_t id)
{
Release();
Data=reinterpret_cast<uint32_t*>(LoadTGAFromResource(hModule,id,Width,Height));
if (Data==NULL) return(false);
// -
uint32_t *ptr=Data;
int32_t n;
int32_t length=Width*Height;
uint32_t alpha_mask=0xFF;
alpha_mask<<=24;
for(n=0;n<length;n++)
{
uint32_t color=*ptr;
*ptr=(color&0x00FFFFFF)|alpha_mask;
ptr++;
}
return(true);
}
//----------------------------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------------------------
void CSprite::Put(IVideo *iVideo_Ptr,int32_t x,int32_t y,bool alpha,color_func_ptr_t color_func_ptr,COLOR_MODE color_mode) const
{
if (Data==NULL || Width==0 || Height==0) return;//
uint32_t *vptr;
uint32_t linesize;
iVideo_Ptr->GetVideoPointer(vptr,linesize);
uint32_t screen_width;
uint32_t screen_height;
iVideo_Ptr->GetScreenSize(screen_width,screen_height);
int32_t x1=x;
int32_t x2=x+Width;
int32_t y1=y;
int32_t y2=y+Height;
if (x2<0) return;//
if (y2<0) return;//
if (x1>static_cast<int32_t>(screen_width)) return;//
if (y1>static_cast<int32_t>(screen_height)) return;//
//
if (x1<0) x1=0;
if (x2>static_cast<int32_t>(screen_width)) x2=screen_width;
if (y1<0) y1=0;
if (y2>static_cast<int32_t>(screen_height)) y2=screen_height;
int32_t ly,lx;
uint32_t *s_ptr=Data+((x1-x)+(y1-y)*Width);
uint32_t *v_ptr=vptr+(x1+y1*linesize);
int32_t dv_ptr=linesize;
int32_t ds_ptr=Width;
if (alpha==false)
{
int32_t length=(x2-x1);
for(ly=y1;ly<y2;ly++,v_ptr+=dv_ptr,s_ptr+=ds_ptr)
{
uint32_t *s_ptr_l=s_ptr;
uint32_t *v_ptr_l=v_ptr;
for(lx=0;lx<length;lx++)
{
uint32_t color=*s_ptr_l;
s_ptr_l++;
*v_ptr_l=(*color_func_ptr)(color_mode,color);
v_ptr_l++;
}
//memcpy(v_ptr,s_ptr,length*sizeof(uint32_t));
}
}
else
{
int32_t length=x2-x1;
for(ly=y1;ly<y2;ly++,v_ptr+=dv_ptr,s_ptr+=ds_ptr)
{
uint32_t *s_ptr_l=s_ptr;
uint32_t *v_ptr_l=v_ptr;
for(lx=0;lx<length;lx++)
{
uint32_t color=*s_ptr_l;
s_ptr_l++;
if (color&0xFF000000) *v_ptr_l=(*color_func_ptr)(color_mode,color);
v_ptr_l++;
}
}
}
}
//----------------------------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------------------------
void CSprite::PutSpriteItem(IVideo *iVideo_Ptr,int32_t x,int32_t y,int32_t offsetx,int32_t offsety,int32_t width,int32_t height,bool alpha,color_func_ptr_t color_func_ptr,COLOR_MODE color_mode) const
{
if (Data==NULL || Width==0 || Height==0) return;//
uint32_t *vptr;
uint32_t linesize;
iVideo_Ptr->GetVideoPointer(vptr,linesize);
uint32_t screen_width;
uint32_t screen_height;
iVideo_Ptr->GetScreenSize(screen_width,screen_height);
int32_t x1=x;
int32_t x2=x+width;
int32_t y1=y;
int32_t y2=y+height;
if (x2<0) return;//
if (y2<0) return;//
if (x1>static_cast<int32_t>(screen_width)) return;//
if (y1>static_cast<int32_t>(screen_height)) return;//
//
if (x1<0) x1=0;
if (x2>static_cast<int32_t>(screen_width)) x2=screen_width;
if (y1<0) y1=0;
if (y2>static_cast<int32_t>(screen_height)) y2=screen_height;
int32_t ly,lx;
uint32_t *s_ptr=Data+((offsetx+(x1-x))+(offsety+(y1-y))*Width);
uint32_t *v_ptr=vptr+(x1+y1*linesize);
int32_t dv_ptr=linesize;
int32_t ds_ptr=Width;
if (alpha==false)
{
int32_t length=(x2-x1);
for(ly=y1;ly<y2;ly++,v_ptr+=dv_ptr,s_ptr+=ds_ptr)
{
uint32_t *s_ptr_l=s_ptr;
uint32_t *v_ptr_l=v_ptr;
for(lx=0;lx<length;lx++)
{
uint32_t color=*s_ptr_l;
s_ptr_l++;
*v_ptr_l=(*color_func_ptr)(color_mode,color);
v_ptr_l++;
}
//memcpy(v_ptr,s_ptr,length*sizeof(uint32_t));
}
}
else
{
int32_t length=x2-x1;
for(ly=y1;ly<y2;ly++,v_ptr+=dv_ptr,s_ptr+=ds_ptr)
{
uint32_t *s_ptr_l=s_ptr;
uint32_t *v_ptr_l=v_ptr;
for(lx=0;lx<length;lx++)
{
uint32_t color=*s_ptr_l;
s_ptr_l++;
if (color&0xFF000000) *v_ptr_l=color;
v_ptr_l++;
}
}
}
}
//----------------------------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------------------------
void CSprite::PutSpriteItemMask(IVideo *iVideo_Ptr,int32_t x,int32_t y,int32_t offsetx,int32_t offsety,int32_t width,int32_t height,uint8_t *Mask,color_func_ptr_t color_func_ptr,COLOR_MODE color_mode) const
{
if (Data==NULL || Width==0 || Height==0 || Mask==NULL) return;//
uint32_t *vptr;
uint32_t linesize;
iVideo_Ptr->GetVideoPointer(vptr,linesize);
uint32_t screen_width;
uint32_t screen_height;
iVideo_Ptr->GetScreenSize(screen_width,screen_height);
int32_t x1=x;
int32_t x2=x+width;
int32_t y1=y;
int32_t y2=y+height;
if (x2<0) return;//
if (y2<0) return;//
if (x1>static_cast<int32_t>(screen_width)) return;//
if (y1>static_cast<int32_t>(screen_height)) return;//
//
if (x1<0) x1=0;
if (x2>static_cast<int32_t>(screen_width)) x2=screen_width;
if (y1<0) y1=0;
if (y2>static_cast<int32_t>(screen_height)) y2=screen_height;
int32_t ly,lx;
uint8_t *m_ptr=Mask;
uint32_t *s_ptr=Data+((offsetx+(x1-x))+(offsety+(y1-y))*Width);
uint32_t *v_ptr=vptr+(x1+y1*linesize);
int32_t dm_ptr=width;
int32_t dv_ptr=linesize;
int32_t ds_ptr=Width;
int32_t length=x2-x1;
for(ly=y1;ly<y2;ly++,v_ptr+=dv_ptr,s_ptr+=ds_ptr,m_ptr+=dm_ptr)
{
uint8_t *m_ptr_l=m_ptr;
uint32_t *s_ptr_l=s_ptr;
uint32_t *v_ptr_l=v_ptr;
for(lx=0;lx<length;lx++)
{
uint32_t color=*s_ptr_l;s_ptr_l++;
uint8_t m=*m_ptr_l;m_ptr_l++;
if (m!=0) *v_ptr_l=(*color_func_ptr)(color_mode,color);
v_ptr_l++;
}
}
}
//----------------------------------------------------------------------------------------------------
// RGB
//----------------------------------------------------------------------------------------------------
void CSprite::PutBlendSpriteItem(IVideo *iVideo_Ptr,int32_t x,int32_t y,int32_t offsetx,int32_t offsety,int32_t width,int32_t height,color_func_ptr_t color_func_ptr,COLOR_MODE color_mode) const
{
if (Data==NULL || Width==0 || Height==0) return;//
uint32_t *vptr;
uint32_t linesize;
iVideo_Ptr->GetVideoPointer(vptr,linesize);
uint32_t screen_width;
uint32_t screen_height;
iVideo_Ptr->GetScreenSize(screen_width,screen_height);
int32_t x1=x;
int32_t x2=x+width;
int32_t y1=y;
int32_t y2=y+height;
if (x2<0) return;//
if (y2<0) return;//
if (x1>static_cast<int32_t>(screen_width)) return;//
if (y1>static_cast<int32_t>(screen_height)) return;//
//
if (x1<0) x1=0;
if (x2>static_cast<int32_t>(screen_width)) x2=screen_width;
if (y1<0) y1=0;
if (y2>static_cast<int32_t>(screen_height)) y2=screen_height;
int32_t ly,lx;
uint32_t *s_ptr=Data+((offsetx+(x1-x))+(offsety+(y1-y))*Width);
uint32_t *v_ptr=vptr+(x1+y1*linesize);
int32_t dv_ptr=linesize;
int32_t ds_ptr=Width;
int32_t length=x2-x1;
uint8_t ir=0;
uint8_t ig=0;
uint8_t ib=0;
for(ly=y1;ly<y2;ly++,v_ptr+=dv_ptr,s_ptr+=ds_ptr)
{
uint32_t *s_ptr_l=s_ptr;
uint32_t *v_ptr_l=v_ptr;
for(lx=0;lx<length;lx++)
{
uint32_t color=*s_ptr_l;s_ptr_l++;
uint32_t new_color=(*color_func_ptr)(color_mode,color);
ir=(new_color>>16)&0xFF;
ig=(new_color>>8)&0xFF;
ib=(new_color)&0xFF;
color=*v_ptr_l;
uint8_t vb=(color)&0xFF;
uint8_t vg=(color>>8)&0xFF;
uint8_t vr=(color>>16)&0xFF;
float ii=(static_cast<float>(ir)+static_cast<float>(ig)+static_cast<float>(ib))/(255.0f*3);
float iii=(1.0f-ii);
uint8_t r=static_cast<uint8_t>((static_cast<float>(vr)*iii+static_cast<float>(ir)*ii));
uint8_t g=static_cast<uint8_t>((static_cast<float>(vg)*iii+static_cast<float>(ig)*ii));
uint8_t b=static_cast<uint8_t>((static_cast<float>(vb)*iii+static_cast<float>(ib)*ii));
color=r;
color<<=8;
color|=g;
color<<=8;
color|=b;
*v_ptr_l=color;
v_ptr_l++;
}
}
}
//----------------------------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------------------------
void CSprite::SetAlpha(uint8_t alpha,uint8_t r,uint8_t g,uint8_t b)
{
if (Data==NULL || Width==0 || Height==0) return;//
uint32_t *ptr=Data;
int32_t n;
int32_t length=Width*Height;
uint32_t alpha_mask=alpha;
alpha_mask<<=24;
for(n=0;n<length;n++)
{
uint32_t color=*ptr;
uint8_t bi=static_cast<uint8_t>(color&0xFF);
uint8_t gi=static_cast<uint8_t>((color>>8)&0xFF);
uint8_t ri=static_cast<uint8_t>((color>>16)&0xFF);
if (ri==r && gi==g && bi==b) *ptr=(color&0x00FFFFFF)|alpha_mask;
ptr++;
}
}
//----------------------------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------------------------
void CSprite::Release(void)
{
if (Data!=NULL) delete[](Data);
Data=NULL;
Width=0;
Height=0;
}
//----------------------------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------------------------
int32_t CSprite::GetWidth(void) const
{
return(Width);
}
//----------------------------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------------------------
int32_t CSprite::GetHeight(void) const
{
return(Height);
}
//----------------------------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------------------------
void CSprite::Normalize(void)
{
int32_t x;
int32_t y;
// , -
int32_t max_color=0;
for(y=0;y<Height;y++)
{
for(x=0;x<Width;x++)
{
uint32_t color=Data[x+y*Width];
int32_t alpha=(color>>24)&0xff;
if (alpha==0) continue;
int32_t r=(color>>16)&0xff;
int32_t g=(color>>8)&0xff;
int32_t b=(color>>0)&0xff;
if (max_color<r) max_color=r;
if (max_color<g) max_color=g;
if (max_color<b) max_color=b;
}
}
if (max_color==0) max_color=1;
for(y=0;y<Height;y++)
{
for(x=0;x<Width;x++)
{
uint32_t color=Data[x+y*Width];
int32_t alpha=(color>>24)&0xff;
if (alpha==0) continue;
int32_t r=(color>>16)&0xff;
int32_t g=(color>>8)&0xff;
int32_t b=(color>>0)&0xff;
int32_t new_r=(255*r)/max_color;
int32_t new_g=(255*g)/max_color;
int32_t new_b=(255*b)/max_color;
color=0xff;
color<<=8;
color|=new_r;
color<<=8;
color|=new_g;
color<<=8;
color|=new_b;
Data[x+y*Width]=color;
}
}
}
//----------------------------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------------------------
bool CSprite::Save(const char *file_name) const
{
return(SaveTGA(file_name,Width,Height,reinterpret_cast<uint8_t*>(Data)));
}
| true |
054d4caecdd6045b66319b9d763e7b9f3fefeab5 | C++ | LANLhakel/FESTR | /common/parallel/mpi/TaskPool.h | UTF-8 | 10,412 | 3.09375 | 3 | [
"BSD-2-Clause"
] | permissive | #ifndef LANL_ASC_PEM_TASKPOOL_H_
#define LANL_ASC_PEM_TASKPOOL_H_
/**
* @file TaskPool.h
* @brief Implements MPI parallelism using dynamic load balancing.
* @author Peter Hakel
* @version 0.9
* @date Created on 3 February 2016\n
* Last modified on 27 February 2020
* @copyright (c) 2016, Triad National Security, LLC.
* All rights reserved.\n
*/
#include <mpi.h>
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <queue>
//-----------------------------------------------------------------------------
/// Framework for a dynamic distribution of parallel tasks using MPI
/** Assumptions and restrictions:\n
* There are at least two processes.\n
* The rank of the root process is 0.\n
* All processes (ranks) run on chips of the same architecture.\n
* \n
* Type IT must contain public members: char *b,\n
* and public methods: void allocate_buffer(const int), \n
* void clear_buffer(), int pack(), void unpack().\n
* \n
* Type OT must contain public members: char *b, int case_id, int rank,\n
* and public methods: void allocate_buffer(const int), \n
* void clear_buffer(), int pack(), void unpack().\n
*/
template <typename IT, typename OT> // IT: input type; OT: output type
class TaskPool
{
public:
/// Default constructor
TaskPool();
/**
* @brief Parametrized constructor: without task queue initialization
* @param[in] comm_in MPI communicator for *this task pool
* @param[in] tf Pointer to the distributed task function
* @param[in] rf Pointer to the root-process function
*/
TaskPool(const MPI_Comm comm_in,
void (*tf)(const IT &, OT &),
void (*rf)(const OT &));
/**
* @brief Parametrized constructor: with task queue initialization
* @param[in] comm_in MPI communicator for *this task pool
* @param[in] tf Pointer to the distributed task function
* @param[in] rf Pointer to the root-process function
* @param[in] qin Task queue
*/
TaskPool(const MPI_Comm comm_in,
void (*tf)(const IT &, OT &),
void (*rf)(const OT &),
const std::queue<IT> &qin);
/// Destructor
~TaskPool();
/**
* @brief Setter for the task queue
* @param[in] qin Task queue
*/
void set_queue(const std::queue<IT> &qin);
///
/**
* @brief Adds a task to the queue
* @param[in] itobj Input object for TaskPool::perform_task
*/
void add_task(const IT &itobj);
/// Processes the queue of parallel tasks
void execute();
private:
/// MPI communicator for *this task pool
MPI_Comm comm;
/// Number of MPI processes in *this communicator
int nranks;
/// Rank id of *this process
int my_rank;
/**
* @brief Function pointer to the distributed task
* @param[in] itobj Input for the distributed task
* @param[out] otobj Output from the distributed task
*/
void (*perform_task)(const IT &itobj, OT &otobj);
/**
* @brief Function pointer to the root-process task
* @param[in] otobj Output from the distributed task;
* used as input for the root-process task
*/
void (*process_results)(const OT &otobj);
/// Pool of tasks to be done
std::queue<IT> q;
/// Constructor helper
void init();
};
//-----------------------------------------------------------------------------
template <typename IT, typename OT>
void TaskPool<IT, OT>::init()
{
MPI_Comm_size(comm, &nranks);
MPI_Comm_rank(comm, &my_rank);
if (my_rank == 0)
perform_task = NULL; // root process does not call perform_task()
else
process_results = NULL; // only root process calls process_results()
}
//-----------------------------------------------------------------------------
template <typename IT, typename OT>
TaskPool<IT, OT>::TaskPool():
comm(MPI_COMM_WORLD), nranks(0), my_rank(0),
perform_task(NULL), process_results(NULL), q()
{}
//-----------------------------------------------------------------------------
template <typename IT, typename OT>
TaskPool<IT, OT>::TaskPool(const MPI_Comm comm_in,
void (*tf)(const IT &, OT &),
void (*rf)(const OT &)):
comm(comm_in), nranks(0), my_rank(0),
perform_task(tf), process_results(rf), q()
{
init();
}
//-----------------------------------------------------------------------------
template <typename IT, typename OT>
TaskPool<IT, OT>::TaskPool(const MPI_Comm comm_in,
void (*tf)(const IT &, OT &),
void (*rf)(const OT &),
const std::queue<IT> &qin):
comm(comm_in), nranks(0), my_rank(0),
perform_task(tf), process_results(rf), q()
{
init();
set_queue(qin);
}
//-----------------------------------------------------------------------------
template <typename IT, typename OT>
TaskPool<IT, OT>::~TaskPool()
{
comm = MPI_COMM_WORLD;
nranks = 0;
my_rank = 0;
perform_task = NULL;
process_results = NULL;
IT itobj;
while (!q.empty())
{
itobj = q.front();
if (itobj.b != NULL) itobj.clear_buffer();
q.pop();
}
}
//-----------------------------------------------------------------------------
template <typename IT, typename OT>
void TaskPool<IT, OT>::set_queue(const std::queue<IT> &qin)
{
if (my_rank == 0) q = qin; // only root process maintains the queue
}
//-----------------------------------------------------------------------------
template <typename IT, typename OT>
void TaskPool<IT, OT>::add_task(const IT &itobj)
{
if (my_rank == 0) q.push(itobj); // only root process maintains the queue
}
//-----------------------------------------------------------------------------
template <typename IT, typename OT>
void TaskPool<IT, OT>::execute()
{
if (nranks < 2)
{
if (my_rank == 0)
{
std::cerr << "Error: at least two MPI processes are required "
<< "in order to use TaskPool.\nnranks = " << nranks
<< std::endl;
}
MPI_Finalize();
exit(EXIT_FAILURE);
}
int rank; // communicating process
int tag; // message tag
MPI_Status st;
IT itobj; // parallel input
OT otobj; // parallel output
int nbytes; // size of next message: > 0 to continue; = 0 to terminate
if (my_rank == 0) // root process path
{
int j; // indexes worker ranks
int nq = q.size(); // number of to-do tasks in the queue
int ninit = std::min(nq, nranks-1); // number of initial tasks
for (j = 1; j <= ninit; ++j) // initial distribution of tasks
{
// send continuation message
rank = tag = j;
itobj = q.front();
nbytes = itobj.pack();
MPI_Send(&nbytes, 1, MPI_INT, rank, tag, comm);
// send distributed task
tag = j + nranks;
MPI_Send(itobj.b, nbytes, MPI_BYTE, rank, tag, comm);
itobj.clear_buffer();
q.pop();
}
nq -= ninit;
// send termination messages to unused ranks
nbytes = 0;
for (j = ninit+1; j < nranks; ++j)
{
rank = tag = j;
MPI_Send(&nbytes, 1, MPI_INT, rank, tag, comm);
}
// listener and task-pool distribution loop
int case_id = 0;
while (nq > 0)
{
MPI_Recv(&nbytes, 1, MPI_INT,
MPI_ANY_SOURCE, MPI_ANY_TAG, comm, &st);
rank = otobj.rank = st.MPI_SOURCE;
tag = rank + 3*nranks;
otobj.allocate_buffer(nbytes);
MPI_Recv(otobj.b, nbytes, MPI_BYTE, rank, tag, comm, &st);
// send continuation message to the available rank
tag = rank;
itobj = q.front();
nbytes = itobj.pack();
MPI_Send(&nbytes, 1, MPI_INT, rank, tag, comm);
// send next distributed task and update task queue
tag = rank + nranks;
MPI_Send(itobj.b, nbytes, MPI_BYTE, rank, tag, comm);
itobj.clear_buffer();
q.pop();
--nq;
// process task results
otobj.unpack();
++case_id;
otobj.case_id = case_id;
(*process_results)(otobj);
}
for (j = 1; j <= ninit; ++j) // final collection of results
{
// receive the next completed task
MPI_Recv(&nbytes, 1, MPI_INT,
MPI_ANY_SOURCE, MPI_ANY_TAG, comm, &st);
rank = otobj.rank = st.MPI_SOURCE;
tag = rank + 3*nranks;
otobj.allocate_buffer(nbytes);
MPI_Recv(otobj.b, nbytes, MPI_BYTE, rank, tag, comm, &st);
// send termination message
tag = rank;
nbytes = 0;
MPI_Send(&nbytes, 1, MPI_INT, rank, tag, comm);
// process task results
otobj.unpack();
++case_id;
otobj.case_id = case_id;
(*process_results)(otobj);
}
} // end root process path
else // my_rank != 0
{
rank = 0; // communication with the root process
IT itobj; // parallel input
while (true)
{
// continuation/termination
tag = my_rank;
MPI_Recv(&nbytes, 1, MPI_INT, rank, tag, comm, &st);
if (nbytes == 0) break; // no more tasks for this rank
// receive new task from root process
tag = my_rank + nranks;
itobj.allocate_buffer(nbytes);
MPI_Recv(itobj.b, nbytes, MPI_BYTE, rank, tag, comm, &st);
itobj.unpack();
// perform the distributed task
(*perform_task)(itobj, otobj);
// send results of completed task back to the root process
tag = my_rank + 2*nranks;
nbytes = otobj.pack();
MPI_Send(&nbytes, 1, MPI_INT, rank, tag, comm);
tag = my_rank + 3*nranks;
MPI_Send(otobj.b, nbytes, MPI_BYTE, rank, tag, comm);
otobj.clear_buffer();
}
} // if (my_rank == 0)
MPI_Barrier(comm);
}
//-----------------------------------------------------------------------------
#endif // LANL_ASC_PEM_TASKPOOL_H_
| true |
0117afb3e01c0f8f17195f2c76a4077583a5b167 | C++ | medhaaiyah/Computer-Science-I | /Assignment_4/userListCommands.cpp | UTF-8 | 3,765 | 3.6875 | 4 | [] | no_license | /*
* Assignment 4 for CS 1337.013
* Programmer: Medha Aiyah
* Description: The userListCommands.cpp file includes the constructor and destructor and the execute code that was called
* in the userListCommands.h file.
*/
#include "userListCommands.h"
#include <iostream>
#include <string>
insertCommand::insertCommand(userList &ids, std::istream &in, std::ostream &out)
: userListCommand(ids, in, out)
{
}
insertCommand::~insertCommand()
{
}
void insertCommand::execute()
{
std::string userName = read("Enter the user id to be added:");
std::string password = read("Enter the password for user " + userName + ":");
bool result = userIds.add(userName, password);
if (result)
{
display("User " + userName+ " was successfully added");
}
else
{
display("User " + userName+ " could not be added and may already exist");
}
}
printCommand::printCommand(userList &ids, std::istream &in, std::ostream &out)
: userListCommand(ids, in, out)
{
}
printCommand::~printCommand()
{
}
void printCommand::execute()
{
display("Current list of users and passwords\n");
userIds.print(out);
}
//This is a findCommand Constructor
findCommand::findCommand(userList &ids, std::istream &in, std::ostream &out)
: userListCommand(ids, in, out)
{
}
//This is a findCommand Destructor
findCommand::~findCommand()
{
}
//This function is used to display whether or not the user was found or not found
void findCommand::execute()
{
std::string userName = read("Enter the user id to search for:");
bool result = userIds.find(userName);
if (result)
{
display("User " + userName+ " was found");
}
else
{
display("User " + userName+ " was not found");
}
}
//This is a updateCommand Constructor
updateCommand::updateCommand(userList &ids, std::istream &in, std::ostream &out)
: userListCommand(ids, in, out)
{
}
//This is a updateCommand Destructor
updateCommand::~updateCommand()
{
}
//This function will first read that the userName is valid. Then if it is valid it will ask it to enter the
//password it will want it to be updated to.
void updateCommand::execute()
{
std::string userName = read("Enter the user id to be updated:");
bool result = userIds.find(userName);
if(result)
{
std::string password = read("Enter the new password for user " + userName);
userIds.update(userName, password);
display("The password for user " + userName+ " was successfully updated");
}
else
{
display("User " + userName+ " was not found");
}
}
//This is a eraseCommand Constructor
eraseCommand::eraseCommand(userList &ids, std::istream &in, std::ostream &out)
: userListCommand(ids, in, out)
{
}
//This is a eraseCommand Destructor
eraseCommand::~eraseCommand()
{
}
//This function will first read that the userName is valid. If it is it will use the erase function to erase the
//user.
void eraseCommand::execute()
{
std::string userName = read("Enter the user id to be erased:");
bool result = userIds.erase(userName);
if (result)
{
display("The entry for user " + userName+ " was successfully erased");
}
else
{
display("User " + userName+ " was not found");
}
}
//This is a printReverse Constructor
printReverse::printReverse(userList &ids, std::istream &in, std::ostream &out)
: userListCommand(ids, in, out)
{
}
//This is a printReverse Destructor
printReverse::~printReverse()
{
}
//This function is used to display the user's information in reverse order.
void printReverse::execute()
{
display("Current list of users and passwords in reverse order");
userIds.printReverse(out);
}
| true |
7955d8cde832f548e525a3b1c5d3f138e56d39e0 | C++ | oryband/homework | /spl/assignments/hw4/client/src/ConnectionHandler.cpp | UTF-8 | 3,152 | 3 | 3 | [] | no_license | #include "ConnectionHandler.h"
using std::string;
using std::cin;
using std::cout;
using std::cerr;
using std::endl;
using std::exception;
using boost::asio::ip::tcp;
using boost::asio::ip::address;
using boost::asio::buffer;
using boost::system::error_code;
using boost::system::system_error;
ConnectionHandler :: ConnectionHandler(
const string host, const short port) :
_host(host), _port(port), _io(), _socket(_io) {}
ConnectionHandler :: ~ConnectionHandler() {
close();
}
const bool ConnectionHandler :: connect() {
cout << "Connecting to " << _host << ":" << _port << " ..." << endl;
try {
// Server's end-point.
tcp::endpoint endpoint(address::from_string(_host), _port);
error_code error;
_socket.connect(endpoint, error);
if (error) {
throw system_error(error);
}
} catch (exception& e) {
cerr << "connect() failed (" << e.what() << ")" << endl;
return false;
}
return true;
}
void ConnectionHandler :: close() {
try {
_socket.close();
} catch (exception& e) {
cout << "close() failed: connection already closed" << endl;
}
}
const bool ConnectionHandler :: getBytes(
char bytes[], const unsigned int size) {
size_t tmp = 0;
error_code error;
try {
while ( ! error && size > tmp ) {
tmp += _socket.read_some(
buffer(bytes + tmp, size - tmp),
error);
}
if (error) {
throw system_error(error);
}
} catch (exception& e) {
//cerr << "getBytes() failed (" << e.what() << ")" << endl;
return false;
}
return true;
}
const bool ConnectionHandler :: sendBytes(
const char bytes[], const unsigned int size) {
size_t tmp = 0; // FIXME should be int?
error_code error;
try {
while ( ! error && size > tmp ) {
tmp += _socket.write_some(
buffer(bytes + tmp, size - tmp),
error);
}
if (error) {
throw system_error(error);
}
} catch (exception& e) {
//cerr << "sendBytes() failed (" << e.what() << ")" << endl;
return false;
}
return true;
}
const bool ConnectionHandler :: getLine(string& line) {
return getFrameAscii(line, '\n');
}
const bool ConnectionHandler :: sendLine(const string& line) {
return sendFrameAscii(line, '\n');
}
const bool ConnectionHandler :: getFrameAscii(
string& frame, const char delimeter) {
char ch;
do {
if ( ! getBytes(&ch, 1) ) {
return false;
}
try {
frame.append(1, ch);
} catch (exception& e) {
cerr << "getFrameAscii() failed (" << e.what() << ")" << endl;
return false;
}
} while (delimeter != ch);
return true;
}
const bool ConnectionHandler :: sendFrameAscii(
const string& frame, const char delimiter) {
if ( ! sendBytes(frame.c_str(), frame.length())) {
return false;
} else {
return sendBytes(&delimiter, 1);
}
}
| true |
6ea13f684ff65ece273cb2ea4313a8d691aac60b | C++ | MattKovtun/myBash | /archieve/move.h | UTF-8 | 1,557 | 2.921875 | 3 | [] | no_license | //
// Created by natasha on 3/20/17.
//
////////////////////////////////////////////////////////////
/////////////////DONE///////////////DONE////////////////////
////////////////////////////////////////////////////////////
bool asking_rename() {
char type;
while (!cin.fail() && type != 'y' && type != 'n') {
cout << " <-- Do you want to rename these files? y/n " << endl;
cin >> type;
}
return type == 'y' ? true : false; }
void _copy(string s, fs::path dest, bool ask) {
fs::path src(s);
if (fs::is_directory(dest))dest /= src.filename();
ask = (ask == false ? asking_rename() : true);
if (ask) {
try {
fs::rename(src, dest);
cout << "Success" << endl;
}
catch (...) {
cout << "No such file " << s << endl;
}
}
}
int move(int argc, const char *argv[]) {
vector<string> to_rename_move;
bool h = false;
for (int i = 1; i < argc - 1; i++){
if(!h) h = (argv[i] == string("-h") ? true : false);
if(!h) h = (argv[i] == string("--help") ? true : false);
}
if(h){helping(3);}
else{
bool answerF = false;
for (int i = 1; i < argc - 2; i++) {
if(!answerF)answerF = (argv[i] == string("-f") ? true : false);
if (argv[i] != string("-f"))to_rename_move.push_back(string(argv[i]));
}
fs::path dest(argv[argc - 2]); // ????????
for (int i = 0; i < to_rename_move.size(); ++i) { // ???????????????
_copy(to_rename_move[i], dest, answerF);
}}
}
| true |
4686ec92335de66365cc74a7c9e9736dd52690f1 | C++ | gbrlas/AVSP | /CodeJamCrawler/dataset/11_18499_20.cpp | UTF-8 | 1,550 | 2.734375 | 3 | [] | no_license | #include<string.h>
#include<stdio.h>
//#include<algorithm>
#include<string.h>
#include <stdlib.h>
#include<ctype.h>
double WP(int,int);
double OWP(int,int);
double OOWP(int,int);
char fix[101][101];
int main()
{
int n,t,i,j;
double rip;
freopen("A-small-attempt1.in","r",stdin);
freopen("A-small.txt","w",stdout);
scanf("%d\n",&t);
for(i=0;i<t;i++)
{
scanf("%d",&n);
printf("Case #%d:\n",i+1);
rip=0;
for(j=0;j<n;j++)
{
scanf("%s",fix[j]);
}
for(j=0;j<n;j++)
{
rip=(0.25*WP(j,n))+(0.5*OWP(j,n))+(0.25*OOWP(j,n));
printf("%lf\n",rip);
}
}
}
double WP(int j,int n)
{
int i,tot=0,win=0;
for(i=0;i<n;i++)
if(fix[j][i] == '1' || fix[j][i] == '0')
{
tot++;
if(fix[j][i] == '1')
win++;
}
// printf("\t%lf\t",((double)(win))/((double)(tot)));
return ((double)(win))/((double)(tot));
}
double OWP(int j,int n)
{
int i,k,tot,win,totOps=0;
double wp[100],sum;
for(i=0;i<n;i++)
{
tot=0;
win=0;
wp[i]=0;
if(i != j && (fix[i][j] == '1' || fix[i][j] == '0'))
{
totOps++;
for(k=0;k<n;k++)
{
if((fix[i][k] == '1' || fix[i][k] == '0') && k!=j)
{
tot++;
if(fix[i][k] == '1')
win++;
}
}
}
if(tot != 0)
wp[i] = ((double)(win))/((double)(tot));
}
sum=0;
for(i=0;i<n;i++)
sum+=wp[i];
return sum/(double)(totOps);
}
double OOWP(int j,int n)
{
double sum=0;
int i,tot=0;
for(i=0;i<n;i++)
if(i!=j && (fix[i][j] == '0' || fix[i][j] == '1'))
{
sum+=OWP(i,n);
tot++;
}
if(tot == 0)
return 0;
else
return sum/(double)(tot);
}
| true |
c1842a8c7ae9499cf37a5bcbec74d60b9ed3e3d9 | C++ | jainiti/assignment2 | /Questions/diagnol_1_rest_0/prg7.cpp | UTF-8 | 405 | 2.84375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int rows, cols, i, j;
cin>>rows>>cols;
for(i=1; i<=rows; i++)
{
for(j=1; j<=cols; j++)
{
if(i == j || (j == (cols+1) - i))
{
cout<<"1";
}
else
{
cout<<"0";
}
}
cout<<"\n";
}
return 0;
}
| true |
fcb961699df22118985af7620bf1c9681f7ec759 | C++ | marcos-willian/POO | /TP2/P1/Programa_teste.cpp | UTF-8 | 941 | 3.328125 | 3 | [] | no_license | #include <iostream>
#include "Matrix.h"
using namespace std;
int main()
{
Matrix Y(3,2,1);
Matrix X(4,1,3);
cout << "Y:: " << endl;
Y.print();
cout << "Numero de linhas de Y:: " << Y.getRows()<<endl;
cout << "Numero de colunas de Y:: " << Y.getCols()<<endl;
cout << "Z é transposta de Y:: " << endl;
Matrix Z = Y.transpose();
Z.print();
cout << "Numero de linhas de Z:: " << Z.getRows()<<endl;
cout << "Numero de colunas de Z:: " << Z.getCols()<<endl;
cout << endl << "X:: " << endl;
X.print();
cout << "Numero de linhas de X:: " << X.getRows()<<endl;
cout << "Numero de colunas de X:: " << X.getCols()<<endl;
cout << "Testando inserção de elemento em matriz: ";
cout << "Matriz Original: " << endl;
Y.print();
Y.putElement(1, 1, 10);
cout << "Matriz modificada: " << endl;
Y.print();
return 0;
} | true |
e12db20898594904f1f0ab5da4bebcb25cf3ea54 | C++ | K3ikoku/Factory | /Factory/Factory/GameManager.cpp | UTF-8 | 6,106 | 3.359375 | 3 | [] | no_license | #include "GameManager.h"
GameManager::GameManager() :
m_playAgain('y'), m_dayNr(0)
{
}
GameManager::~GameManager()
{
}
void GameManager::GameLoop()
{
while (m_playAgain == 'y')
{
//Create the instances of the armies and the factory
m_factory = new UnitFactory();
m_hoard = new ZombieHoard();
m_town = new Town(m_factory);
std::cout << "A necromancer comes closer to the town of North Haverbrook\n" << std::endl;
std::cout << "As night is closing in he begins to draw powers from the dark summing unholy creatures of the night\n" << std::endl;
//A check to see if there are any towns people living
while (0 < m_town->TownPopulation())
{
std::cout << "You scouts to the town to see how they prepare for the nightly raids\n" << std::endl;
//Summon humans based on how much money the town has
SummonHuman(m_factory, m_town);
//Check if the zombies have more power than the cheapest unit and run the create zombie loop
if (25 < m_hoard->GetBudget())
{
std::cout << "It's currently day nr: " << m_dayNr << "\n" << std::endl;
SummonZombies(m_factory, m_hoard);
}
std::cout << "Night comes and you prepare for battle\n" << std::endl;
//Store how many humans and zombies there are before the battle
m_hoardPreBattle = m_hoard->HordePopulation();
m_townPreBattle = m_town->TownPopulation();
//Start the battle function
m_hoard->Attack(m_town);
//Calculate and print how many zombies and humans were lost
int diff = m_hoardPreBattle - m_hoard->HordePopulation();
std::cout << "You lost " << diff << " creatures durin the night.\n" << std::endl;
diff = m_townPreBattle - m_town->TownPopulation();
std::cout << "You killed " << diff << " of the filthy humans during the night.\n" << std::endl;
//Do a check if the hoard has any zombies or power to summon new ones
if (0 < m_hoard->HordePopulation() || 25 <= m_hoard->GetBudget())
{
m_dayNr++;
std::cout << "Press any button to proceed to the next day\n" << std::endl;
std::cin >> m_userInput;
std::cout << "\n" << std::endl;
}
//If all zombies are dead and the necromancer is out of power tell the player they lost the game
else
{
std::cout << "All of your zombies are dead and you have depleted your powers." << std::endl;
std::cout << "You made it until day: " << m_dayNr << "until your horde got crushed.\n" << std::endl;
std::cout << "You loose." << std::endl;
break;
}
}
//If all humans are dead print out that the player won
if (0 < m_town->TownPopulation())
{
std::cout << "You have laid waste to the town only rubbel and corpses remain." << std::endl;
std::cout << "Corpses that shall soon fill the ranks of your hoard. Congratulations" << std::endl;
}
std::cout << "Do you want to play again? y/n " << std::endl;
std::cin >> m_userInput;
std::cout << "\n" << std::endl;
m_playAgain = m_userInput;
}
m_dayNr = 0;
}
void GameManager::SummonZombies(UnitFactory * factory, ZombieHoard* hoard)
{
m_userInput = 'y';
while (25 <= hoard->GetBudget() && m_userInput == 'y')
{
//Reset the new unit variable to prevent any future troubles
m_newUnit = nullptr;
std::cout << "You currently have " << hoard->GetBudget() << " power to spend\n" << std::endl;
std::cout << "What do you want to summon? \n" << std::endl;
std::cout << "Please type in the letter for the unit you want to create" << std::endl;
std::cout << "Letter / Unit / Cost \n\nz / Zombie / 25 \nh / Zombie Hound / 35" << std::endl;
std::cout << "f / Flying Terror / 75 \nb / Brute Zombie / 100\n" << std::endl;
//Take the players inputed character and send it to the factory to create a new unit
std::cin >> m_userInput;
std::cout << "\n" << std::endl;
m_newUnit = factory->CreateZombie(m_userInput, hoard->GetBudget());
if (m_newUnit != nullptr)
{
hoard->AddToHoard(m_newUnit);
hoard->SubtractFromBudget(m_newUnit->GetCost());
}
else
{
//Restart the function if anything went wrong
m_userInput = 'y';
}
//Check if the player can afford a new unit and ask them if they want to.
if (25 <= hoard->GetBudget() && m_userInput != 'y')
{
std::cout << "Do you want to summon another creature? : y/n" << std::endl;
std::cin >> m_userInput;
std::cout << "\n" << std::endl;
}
}
}
void GameManager::SummonHuman(UnitFactory * factory, Town * town)
{
//As long as the humans have enough money to buy a new unit create the most powerful unit they can afford
while (25 <= town->GetBudget())
{
m_newUnit = nullptr;
if (250 <= town->GetBudget())
{
m_townInput = 'k';
std::cout << "Your scout reports that the town has summoned a powerful Knight.\n" << std::endl;
}
else if (50 <= town->GetBudget())
{
m_townInput = 'a';
std::cout << "One of your undead scouts tells you that the one of the peasants in town has armed themself with a pitchfork and leather armor\n" << std::endl;
}
else
{
m_townInput = 'p';
std::cout << "One of the children in town has grown up and is now able to partake in the protection of the town. \n" << std::endl;
}
m_newUnit = factory->CreateHuman(m_townInput);
town->AddTownPeople(m_newUnit);
town->SubtractFromBudget(m_newUnit->GetCost());
}
}
| true |
1d96a05d2b6a7b15252e2b9346dc118aef732567 | C++ | zkEloHub/LC-SourceCode | /lc162_1.cpp | UTF-8 | 248 | 3.03125 | 3 | [] | no_license | class Solution { // 找峰值.
public: // 直接遍历, 性能一般.
int findPeakElement(vector<int>& nums) {
int len = nums.size();
int i = 1;
while (i < len && nums[i] > nums[i-1]) i++;
return i-1;
}
}; | true |
1e0e38e2d48fa7698b2127e98ce1ad625b50ae12 | C++ | souradipbakli/hacktoberfest2021 | /CPP/MultipleInheritance.cpp | UTF-8 | 992 | 3.71875 | 4 | [
"CC0-1.0"
] | permissive | /* C++ Program to demonstrate an Example of Multiple Inheritance */
#include<iostream>
using namespace std;
class M
{
protected:
int m;
public :
void get_M(int );
};
class N
{
protected:
int n;
public:
void get_N(int);
};
class P: public M, public N
{
public:
void display(void);
};
void M::get_M(int x)
{
m=x;
}
void N::get_N(int y)
{
n=y;
}
void P::display(void)
{
cout<<"\n\tm = "<<m<<endl;
cout<<"\n\tn = "<<n<<endl;
cout<<"\n\tm*n = "<<m*n<<endl;
}
int main()
{
P p;
p.get_M(10);
p.get_N(20);
p.display();
return 0;
}
| true |
0caaf566a6c8fc482fb06eb26a61bded0b0417a0 | C++ | fmenozzi/learn-opengl | /src/01-getting-started/02-hello-triangle.cpp | UTF-8 | 4,502 | 2.59375 | 3 | [] | no_license | #include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <cstdio>
#include <cstdlib>
#define GLSL(src) "#version 150 core\n" #src
#define GLERR do {\
GLuint glerr;\
while ((glerr = glGetError()) != GL_NO_ERROR)\
fprintf(stderr, "%s:%d glGetError() = 0x%04x\n", __FILE__, __LINE__, glerr);\
} while (0)
const GLuint WIDTH = 800;
const GLuint HEIGHT = 600;
void key_callback(GLFWwindow* window, int key, int, int action, int) {
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
}
void cleanup(int status) {
glfwTerminate();
exit(status);
}
int main() {
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
auto window = glfwCreateWindow(WIDTH, HEIGHT, "Getting Started - Hello Triangle", nullptr, nullptr);
if (!window) {
fprintf(stderr, "Failed to create GLFW window\n");
cleanup(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
gladLoadGL();
int width, height;
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
glfwSetKeyCallback(window, key_callback);
GLfloat vertices[] = {
0.5f, 0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
-0.5f, -0.5f, 0.0f,
-0.5f, 0.5f, 0.0f,
};
GLuint indices[] = {
0, 1, 3,
1, 2, 3,
};
// VAO
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
// VBO
GLuint vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// EBO
GLuint ebo;
glGenBuffers(1, &ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
GLint status;
GLchar infolog[512];
// Vertex shader
const GLchar* vertex_source = GLSL(
in vec3 position;
void main() {
gl_Position = vec4(position, 1.0);
}
);
GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex_shader, 1, &vertex_source, nullptr);
glCompileShader(vertex_shader);
glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE) {
glGetShaderInfoLog(vertex_shader, 512, nullptr, infolog);
fprintf(stderr, "Failed to compile vertex shader\n");
fprintf(stderr, "%s\n", infolog);
cleanup(EXIT_FAILURE);
}
// Fragment shader
const GLchar* fragment_source = GLSL(
out vec4 color;
void main() {
color = vec4(1.0, 0.5f, 0.2f, 1.0f);
}
);
GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment_shader, 1, &fragment_source, nullptr);
glCompileShader(fragment_shader);
glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &status);
if (!status) {
glGetShaderInfoLog(fragment_shader, 512, nullptr, infolog);
fprintf(stderr, "Failed to compile fragment shader\n");
fprintf(stderr, "%s\n", infolog);
cleanup(EXIT_FAILURE);
}
// Create shader program
GLuint shader_program = glCreateProgram();
glAttachShader(shader_program, vertex_shader);
glAttachShader(shader_program, fragment_shader);
glLinkProgram(shader_program);
glGetProgramiv(shader_program, GL_LINK_STATUS, &status);
if (!status) {
glGetShaderInfoLog(shader_program, 512, nullptr, infolog);
fprintf(stderr, "Failed to link shader program\n");
fprintf(stderr, "%s\n", infolog);
cleanup(EXIT_FAILURE);
}
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
glUseProgram(shader_program);
// Position attribute
GLint pos_attrib = glGetAttribLocation(shader_program, "position");
glEnableVertexAttribArray(pos_attrib);
glVertexAttribPointer(pos_attrib, 3, GL_FLOAT, GL_FALSE, 3*sizeof(GL_FLOAT), (GLvoid*)0);
while (!glfwWindowShouldClose(window)) {
glfwPollEvents();
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glDrawElements(GL_TRIANGLES, sizeof(indices), GL_UNSIGNED_INT, 0);
glfwSwapBuffers(window);
}
cleanup(EXIT_SUCCESS);
}
| true |
dcfde4377b1bebe5cd02fd7ab1a43993841b95e0 | C++ | SharifulCSECoU/competitive-programming | /uva-online-judge/accepted-solutions/11343 - Isolated Segments.cpp | UTF-8 | 2,311 | 3.109375 | 3 | [] | no_license | //*****************
// LAM PHAN VIET **
// UVA 11343 - Isolated Segments
// Time limit: 1s
//********************************
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
#define maxN 102
class Segment {
int x1, y1, x2, y2;
double a, b, c;
public:
Segment() {
x1 = y1 = x2 = y2 = 0;
a = b = c = 0;
}
void Read() {
scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
Create();
}
void Create() {
a = y1 - y2;
b = x2 - x1;
c = x1*y2 - x2*y1;
}
double Side(int x, int y) {
return (a*x + b*y + c);
}
double Distance(int x, int y, int k) {
if (k==1) return sqrt((x1-x)*(x1-x) + (y1-y)*(y1-y));
return sqrt((x2-x)*(x2-x) + (y2-y)*(y2-y));
}
double Length() {
return sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
}
bool isCollide(Segment s) {
double sidea, sideb, sidec, sided;
sidea = s.Side(x1, y1);
sideb = s.Side(x2, y2);
sidec = Side(s.x1, s.y1);
sided = Side(s.x2, s.y2);
if (sidea*sideb<0 && sidec*sided<0) return true;
if (sidea*sideb>0 || sidec*sided>0) return false;
double len = Length(), lens = s.Length();
if (!sidea && s.Distance(x1, y1, 1)+s.Distance(x1, y1, 2)==lens) return true;
if (!sideb && s.Distance(x2, y2, 1)+s.Distance(x2, y2, 2)==lens) return true;
if (!sidec && Distance(s.x1, s.y1, 1)+Distance(s.x1, s.y1, 2)==len) return true;
if (!sided && Distance(s.x2, s.y2, 1)+Distance(s.x2, s.y2, 2)==len) return true;
return false;
}
};
Segment seg[maxN];
bool Isolated[maxN];
main() {
// freopen("343.inp", "r", stdin); freopen("343.out", "w", stdout);
int Case, n;
scanf("%d", &Case);
while (Case--) {
scanf("%d", &n);
for (int i=0; i<n; i++) {
seg[i].Read();
Isolated[i] = true;
}
for (int i=0; i<n; i++)
for (int j=i+1; j<n; j++)
if (seg[i].isCollide(seg[j])) {
Isolated[i] = Isolated[j] = false;
}
int Count = 0;
for (int i=0; i<n; i++)
if (Isolated[i]) Count++;
printf("%d\n", Count);
}
}
/* lamphanviet@gmail.com - 2011 */
| true |
448f2b569fb9af368d4fa0e079fb8de8841973cd | C++ | erwanbou/LatticeTester | /analysis/include/SimpleMRG.h | UTF-8 | 2,254 | 2.96875 | 3 | [] | no_license |
//
// Class for simple MRG
//
#ifndef SIMPLEMRG_H
#define SIMPLEMRG_H
#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <sstream>
#include <iomanip>
#include <time.h>
#include <NTL/tools.h>
#include <NTL/ctools.h>
#include <NTL/ZZ.h>
#include <NTL/ZZ_p.h>
#include "NTL/vec_ZZ.h"
#include "NTL/vec_ZZ_p.h"
#include <NTL/vec_vec_ZZ.h>
#include <NTL/vec_vec_ZZ_p.h>
#include <NTL/mat_ZZ.h>
#include <NTL/matrix.h>
#include <NTL/LLL.h>
using namespace std;
using namespace NTL;
class SimpleMRG {
public:
// Constructor. Create the matrix m_A with the given coefficients (a_i)
// and initialize the current m_state to the input state.
SimpleMRG (const ZZ modulus, const int k, const vec_ZZ a, vec_ZZ state)
{
m_modulus = modulus;
ZZ_p::init(modulus);
m_k = k;
m_A.SetDims(k, k);
// update last lign of the companion matrix
for (int j = 0; j < k; j++)
m_A[k-1][j] = conv<ZZ_p>( a[k-1-j] );
// update upper diagonal of the companion matrix
for (int i = 0; i < k-1; i++)
m_A[i][i+1] = 1;
m_stateIndex = 0;
m_state.SetLength(k);
m_state = conv<vec_ZZ_p> (state);
}
// Destructor
~SimpleMRG () {}
// Update m_state from current m_index to new index;
void goToIndex (int index)
{
while (m_stateIndex < index) {
m_state = m_A * m_state;
m_stateIndex++;
}
}
// Give the last value calculated
ZZ_p getLastValue () const { return m_state[m_k-1]; }
// Update m_state to the next step and give the new value calculated
ZZ_p getNextValue ()
{
// update the state
m_state = m_A * m_state;
m_stateIndex++;
// get the value
return m_state[m_k-1];
}
// access function
ZZ getModulus () const { return m_modulus; }
// access function
int getOrder () const { return m_k; }
// access function
mat_ZZ_p getCompanionMatrix () const { return m_A; }
// access function
int getStateIndex () const { return m_stateIndex; }
// access function
vec_ZZ_p getState () const { return m_state; }
private:
// modulus of the MRG
ZZ m_modulus;
// order of the MRG
int m_k;
// representation matrix A with (a_i) coefficients
mat_ZZ_p m_A;
// index current state
int m_stateIndex;
// Values of current state
vec_ZZ_p m_state;
};
#endif
| true |
f51e3a86652d23f13949cccf2ae827c95f02358e | C++ | gabalwto/Prot | /system/synchronization/semaphore.hh | UTF-8 | 830 | 2.65625 | 3 | [
"MIT"
] | permissive | #ifndef __PROT_LIBRARY_SYSTEM_LOCK_SEMAPHORE_H_
#define __PROT_LIBRARY_SYSTEM_LOCK_SEMAPHORE_H_
#include "defines.hh"
#include "lock.hh"
#include <system/time/timedelta.hh>
namespace Prot {
namespace Lock {
class Semaphore : public ILock
{
public:
virtual LockType Type();
virtual Bool Get();
virtual Void Free();
virtual Bool TryGet();
/** semaphore will invalid if
set i_set < 0 or
i_max < i_set or
i_max > MAXIMUM_COUNT */
Semaphore(Int32 i_set, Int32 i_max);
~Semaphore();
Bool SetMax(Int32 i_max);
Int32 Current();
Int32 Maximum();
Bool Wait(Time::TimeUnit t);
/** return false if i_num <= 0 or i_num add to current count
larger than maximum count */
Bool Post(Int32 i_num = 1);
public:
static const Int32 MAXIMUM_COUNT = 2109876543;
private:
AnyPtr _smo;
};
}
}
#endif
| true |
854ba2c67f35ab72802beaa578b40e17ac8967ca | C++ | pkgw/casa | /code/alma/ASDMBinaries/SDMDataObjectWriter.h | UTF-8 | 34,722 | 2.859375 | 3 | [] | no_license | #ifndef SDMDataObjectWriter_CLASS
#define SDMDataObjectWriter_CLASS
#include <string>
#include <map>
#include <set>
#include <vector>
#include <bitset>
//#include <boost/regex.hpp>
#include <iostream>
#include <fstream>
#include <sstream>
#include "SDMDataObject.h"
#include "CAtmPhaseCorrection.h"
#include "CCorrelationMode.h"
#include "CCorrelatorType.h"
#include "CNetSideband.h"
#include "CProcessorType.h"
using namespace std;
using namespace AtmPhaseCorrectionMod;
using namespace CorrelationModeMod;
using namespace CorrelatorTypeMod;
using namespace NetSidebandMod;
using namespace ProcessorTypeMod;
namespace asdmbinaries {
/**
* A class to represent an exception thrown while writing a MIME message containing ALMA binary data.
*/
class SDMDataObjectWriterException {
public:
/**
* An empty contructor.
*/
SDMDataObjectWriterException();
/**
* A constructor with a message associated with the exception.
* @param m a string containing the message.
*/
SDMDataObjectWriterException(const string& m);
/**
* The destructor.
*/
virtual ~SDMDataObjectWriterException();
/**
* Returns the message associated to this exception.
* @return a string.
*/
string getMessage() const;
protected:
string message;
};
inline SDMDataObjectWriterException::SDMDataObjectWriterException() : message ("SDMDataObjectWritererException") {}
inline SDMDataObjectWriterException::SDMDataObjectWriterException(const string& m) : message(m) {}
inline SDMDataObjectWriterException::~SDMDataObjectWriterException() {}
inline string SDMDataObjectWriterException::getMessage() const {
return "SDMDataObjectWriterException : " + message;
}
/**
* A general class to write MIME messages containing ALMA binary data.
*
* An instance of this class can be used to write :
* <ul>
* <li> Correlator data :
* <ul>
* <li>Integration : full resolution data. </li>
* <li>Subintegration : channel average data. </li>
* </ul>
* </li>
* <li> Total Power data.
* <li> Water Vapor Radiometer (WVR) data.
* </ul>
*
* The MIME message is written on standard output, a disk file or a char buffer depending on the constructor
* used to create an instance of SDMDataObjectWriter.
*
* @section how-to-use How to use an instance of SDMDataObjectWriter.
* Whatever is the type of binary data (total power, WVR, integration, subintegration) to write, the following
* scheme must be respected when using an SDMDataObjectWriter.
*
* <ol>
* <li> Instantiate an SDMDataObjectWriter by using the appropriate constructor depending on the kind of desired output
* (standard output, disk file, memory).</li>
* <li> Write the binary data by using the appropriate methods depending on the kind of binary data. </li>
* <li> Conclude the usage of this instance of SDMDataObjectWriter by calling the done method (done()).
* </ol>
*
* Example:
*
* @code
* // open a disk file
* ofstream osf("myCorrData.dat");
*
* // builds an SDMDataObjectWriter which will write the data in the file "myCorrData.dat".
* SDMDataObjectWriter sdmdow(&osf, "uid://X1/X2/X3", "ALMA Binary Data");
*
* // Here produce the binary data by using one the sequences detailed below.
* .
* .
* // done with sdmdow.
* sdmdow.done();
*
* // Do not forget to close the file !!
* osf.close()
* .
* .
* @endcode
*
* Example of a MIME message output in an ostringstream :
*
* @code
* // create an osstringstream
* ostringstream oss;
*
* // builds an SDMDataObjectWriter which will write the data in the string attached to oss.
* SDMDataObjectWriter sdmdow(&oss, "uid://X1/X2/X3", "ALMA Binary Data");
*
* // Here produce the binary data by using one the sequences detailed below.
* .
* .
* // done with sdmdow.
* sdmdow.done();
*
* // Do whatever you want with oss.
* .
* .
* // And perhaps a good thing to erase the content of oss.
* oss.str("");
* .
* .
* @endcode
*
* We detail now the different valid sequences for writing binary data depending on their kind.
* @subsection how-to-tpData How to write Total Power data.
* @subsubsection One single call to the tpData() method.
* @code
* sdmdow.tpData(123450000, // startTime
* "uid://X123/X4/X5", // execBlockUID
* 1, // execBlockNum
* 10, // scanNum
* 3, // subscanNum
* 100, // number of integrations
* 2, // number of antennas
* basebands, // vector of basebands.
* 171450000, // time
* 96000000, // interval
* axis, // names of axis
* autoData); // total power data values.
* @endcode
* One may also consider to use in that order the methods tpDataHeader and addTPSubscan.
*
* @subsection how-to-wvrData How to write WVR data.
* One single call to the wvrData() method.
* @code
* sdmdow.wvrData("uid://X123/X4/X5", // execBlockUID,
* 1, // execBlockNum,
* 10, // scanNum,
* 3, // subscanNum,
* 100, // number of time stamps (i.e. size along the TIM axis),
* 8, // number of antennas,
* 4, // number of channels,
* DSB, // NetSideband characteristic,
* 171450000, // time,
* 96000000, // interval,
* wvrData, // the WVR data values,
* flags); // flags associated to the WVR data.
*
* @endcode
*
* @subsection how-to-intData How to write integrations.
* One single call to corrDataHeader() followed by one or more calls to addIntegration().
* @code
* // Write the global header.
* sdmdow.corrDataHeader(123450000, // startTime
* "uid://X123/X4/X5", // execBlockUID
* 1, // execBlockNum
* 10, // scanNum
* 3, // subscanNum
* 2, // numAntenna
* correlationMode, // the correlation mode.
* spectralResolution, // the spectral resolution.
* correlatorType, // the processor (correlator) type.
* dataStruct); // the description of the structure of the binary data.
*
* // And write the integrations (3 in that example).
* for (uint32_t i = 0; i < 3; i++) {
* .
* .
* .
* sdmdow.addIntegration(i+1, // integration's index.
* time, // midpoint
* interval, // time interval
* flags, // flags binary data
* actualTimes, // actual times binary data
* actualDurations, // actual durations binary data
* zeroLags, // zero lags binary data
* shortCrossData, // cross data (can be short or int)
* autoData); // single dish data.
* .
* .
* .
* }
* @endcode
* @subsection how-to-subintData How to write subintegrations.
* One single call to corrDataHeader() followed by one or more calls to addSubintegration().
* @code
* // Write the global header.
* sdmdow.corrDataHeader(123450000, // startTime
* "uid://X123/X4/X5", // execBlockUID
* 1, // execBlockNum
* 10, // scanNum
* 3, // subscanNum
* 2, // numAntenna
* correlationMode, // the correlation mode.
* spectralResolution, // the spectral resolution.
* processorType, // the processor type.
* dataStruct); // the description of the structure of the binary data.
*
* // And write the subintegrations (6 in that example).
* for (uint32_t i = 0; i < 3; i++) {
* for (uint32_t j = 0; j < 2; j++) {
* .
* .
* .
* sdmdow.addSubintegration(i+1, // integration's index.
* j+1, // subintegration's index
* time, // midpoint
* interval, // time interval
* flags, // flags binary data
* actualTimes, // actual times binary data
* actualDurations,// actual durations binary data
* zeroLags, // zero lags binary data
* shortCrossData, // cross data (can be short or int)
* autoData); // single dish data.
* .
* .
* .
* }
* }
* @endcode
* @subsection valid-calls Valid calls sequences.
* The table below summarizes the valid call sequences when using an SDMDataObjectWriter. Any deviation from these
* rules will result in an SDMDataObjectWriterException thrown.
* <table>
* <caption> Valid sequences of methods calls </caption>
* <tr>
* <th> Total Power data </th> <th> WVR data </th> <th> Integration </th> <th> subIntegration </th>
* </tr>
* <tr>
* <td> ctor, tpData, done </td>
* <td rowspan=2> ctor, wvrData, done </td>
* <td rowspan=2> ctor, corrDataHeader, addIntegration (one or more times), done </td>
* <td rowspan=2> ctor, corrDataHeader, addSubintegration (one or more times), done </td>
* </tr>
* <tr>
* <td> ctor, tpDataHeader, addTPSubscan, done </td>
* </tr>
* </table>
*
*/
class SDMDataObjectWriter {
public:
/**
* A constructor to write on standard output.
* The MIME message will be written to the standard output.
* @param uid a string containing the ALMA uid of the MIME message.
* @param title a string defining the title for the binary data to be written.
*/
SDMDataObjectWriter(const string& uid="uid://X0/X0/X0", const string& title="ALMA Binary Data");
/**
* A constructor to write in a file.
* The MIME message will be written into the file attached to the ofstream argument.
* @param ofs an pointer to an ofstream object.
* @param uid a string containing the ALMA uid of the MIME message.
* @param title a string defining the title for the binary data to be written.
*/
SDMDataObjectWriter(ofstream* ofs, const string& uid="uid://X0/X0/X0", const string& title="ALMA Binary Data");
/**
* A constructor to write in memory.
* The MIME message will be written in an ostringstream.
* @param oss a pointer to an ostringstream.
* @param uid a string containing the ALMA uid of the MIME message.
* @param title a string defining the title for the binary data to be written.
* @note *oss will be systematically cleared before the first write operation.
*/
SDMDataObjectWriter(ostringstream* oss, const string& uid="uid://X0/X0/X0", const string& title="ALMA Binary Data");
/**
* The destructor.
*
*/
virtual ~SDMDataObjectWriter();
/**
* This method must be called to conclude the activity of this SDMDataObjectWriter.
* It completes the MIME message.
* @note Do not forget to call it when you have finished to write your binary data !
* @note It <b>does not</b> close the file attached to the output stream if any, this operation is left to the user.
*/
void done();
/* /\** */
/* * Writes a data subset of Total Power binary data. */
/* * @param time time of the subscan. */
/* * @param interval duration of the subscan. */
/* * @param flags the values of flags (see note). */
/* * @param actualTimes the values of actualTimes (see note). */
/* * @param actualDurations the values of actualDurations (see note). */
/* * @param autoData the values of autoData. */
/* * */
/* * @throws SDMDataObjectWriterException */
/* * */
/* * @note */
/* * This method must called only once after a call to tpDataHeader. */
/* **\/ */
/* void addTPSubscan(uint64_t time, */
/* uint64_t interval, */
/* const vector<FLAGSTYPE>& flags, */
/* const vector<ACTUALTIMESTYPE>& actualTimes, */
/* const vector<ACTUALDURATIONSTYPE>& actualDurations, */
/* const vector<AUTODATATYPE>& autoData); */
/**
* Writes the full content of Total Power data in their respective attachments (global XML header, local XML header and binary attachments)
* on the MIME message stream.
* @param startTime start time.
* @param execBlockUID the UID of the exec block.
* @param execBlockNum the index of the exec block.
* @param scanNum the index of the scan.
* @param subscanNum the index of the subscan.
* @param numOfIntegrations the number of integrations in that Subscan.
* @param numAntenna the number of antenna.
* @param basebands a vector of Baseband describing the structure of the binary data.
* @param time.
* @param interval.
* @param flags the values of flags (see note).
* @param actualTimes the values of actualTimes (see note).
* @param actualDurations the values of actualDurations (see note).
* @param autoDataAxes the ordered set of axes names for autoData.
* @param autoData the values of autoData.
* @param autoDataNormalized
*
* @throws SDMDataObjectWriterException
*
* @note
* A vector with a null size can be passed when the (optional) attachment is absent.
*
* @note this method allows to write Total Power data in a "one-call" way. An alternate solution consists
* in calling tpDataHeader and then addTPSubscan.
*/
void tpData(uint64_t startTime,
const string& execBlockUID,
uint32_t execBlockNum,
uint32_t scanNum,
uint32_t subscanNum,
uint32_t numOfIntegrations,
uint32_t numAntenna,
const vector<SDMDataObject::Baseband>& basebands,
uint64_t time,
uint64_t interval,
const vector<AxisName>& flagsAxes,
const vector<FLAGSTYPE>& flags,
const vector<AxisName>& actualTimesAxes,
const vector<ACTUALTIMESTYPE>& actualTimes,
const vector<AxisName>& actualDurationsAxes,
const vector<ACTUALDURATIONSTYPE>& actualDurations,
const vector<AxisName>& autoDataAxes,
const vector<AUTODATATYPE>& autoData);
/**
* Writes the full content of Total Power data in their respective attachments (global XML header, local XML header and binary attachments)
* on the MIME message stream.
* @param startTime start time.
* @param execBlockUID the UID of the exec block.
* @param execBlockNum the index of the exec block.
* @param scanNum the index of the scan.
* @param subscanNum the index of the subscan.
* @param numOfIntegrations the number of integrations in that Subscan.
* @param numAntenna the number of antenna.
* @param basebands a vector of Baseband describing the structure of the binary data.
* @param time
* @param interval
* @param autoDataAxes the ordered set of axes names for autoData.
* @param autoData the values of autoData.
*
* @throws SDMDataObjectWriterException
*
* @note
* This method is kept for backward compatibility reasons. It's recommanded to use the "long" version of tpData which
* gives a full control of the optional attachments to be written.
*/
void tpData(uint64_t startTime,
const string& execBlockUID,
uint32_t execBlockNum,
uint32_t scanNum,
uint32_t subscanNum,
uint32_t numOfIntegrations,
uint32_t numAntenna,
const vector<SDMDataObject::Baseband>& basebands,
uint64_t time,
uint64_t interval,
const vector<AxisName>& autoDataAxes,
const vector<AUTODATATYPE>& autoData);
/**
* Writes the XML global header on the MIME message stream, when binary data are Total Power data and will be written
* in successive steps with calls to tpAddIntegration.
*
* @param startime start time.
* @param execBlockUID the UID of the exec block.
* @param execBlockNum the index of the exec block.
* @param scanNum the index of the scan.
* @param subscanNum the index of the subscan.
* @param numAntenna the number of antenna.
* @param dataStruct the description of the binary data structure.
*
* @throws SDMDataObjectWriterException
*/
void tpDataHeader(uint64_t startTime,
const string& execBlockUID,
uint32_t execBlockNum,
uint32_t scanNum,
uint32_t subscanNum,
uint32_t numAntenna,
SDMDataObject::DataStruct& dataStruct);
/**
* Writes one integration (local header + binary attachment) of total power data on the MIME message stream.
*
* @param integrationNum the index (1 based) of the integration.
* @param time time of the integration.
* @param interval interval of the integration.
* @param flags the values of flags.
* @param actualTimes the values of actualTimes.
* @param actualDurations the values of actualDurations.
* @param autoData the values of autoData.
*
* @throws SDMDataObjectWriterException
*
* @note To be used repeatedly after one call to tpDataHeader until all the integrations of Total Power data have been acquired.
*
*/
void tpAddIntegration(uint32_t integrationNum,
uint64_t time,
uint64_t interval,
const vector<FLAGSTYPE>& flags,
const vector<ACTUALTIMESTYPE>& actualTimes,
const vector<ACTUALDURATIONSTYPE>& actualDurations,
const vector<AUTODATATYPE>& autoData);
/**
* Writes water vapour radiometer (WVR) data in a MIME message conform
* with the BDF V2 format.
*
* @param execBlockUID the archive uid of the exec Block,
* @param execBlockNum the index of the exec Block,
* @param scanNum the number of the scan,
* @param subscanNum the number of the subscan,
* @param numTimes the number of time stamps (i.e. size along the TIM axis),
* @param numAntennas the number of antennas producing WVR data,
* @param numChannels the number of channels in WVR data,
* @param netSideband the NetSideband characteristic attached to WVR data,
* @param time the mid-point of the time range containing all the WVR data,
* @param interval the duration of the time range containing all the WVR data,
* @param wvrData the WVR data,
* @param flags the flags associated to the WVR data.
*
* @throws SDMDataObjectWriterException
*
* @note
*
* <ul>
* <li>see the constructor of the class and the done method for opening the
* output stream where the MIME message is actually written (file, memory...)
* and for closing it</li>
* <li>the "startTime" element of the global header in the resulting MIME document
* will be filled with a value equal to 'time' - 'interval'/2, </li>
* <li> 'time' and 'interval' express a number of nanoseconds. 'time' is an MJD, </li>
* <li> 'wvrData' and 'flags' are both 1D arrays. Nonetheless they are expected to
* be the linearized versions of multi dimensional arrays whose axes are defined
* by the sequence TIM ANT SPP for the WVR data and TIM ANT for their flags,
* (SPP varying before ANT varying itself before TIM),</li>
* <li> a vector of null size for the argument 'flags' will be interpreted as 'flags not available'.</li>
* <li> a null value in at least one of the arguments 'numTimes', 'numAntennas' or 'numChannels'
* will trigger an SDMDataObjectWriterException. </li>
* <li> a argument 'wvrData' with a size different from 'numTimes' * 'numAntennas' * 'numChannels'
* will trigger an SDMDataObjectWriterException. </li>
* <li> an argument 'flags' with a size different from 0 and different from 'numTimes' * 'numAntennas'
* will trigger an SDMDataObjectWriterException. </li>
* </ul>
*
*/
void wvrData (const string & execBlockUID,
uint32_t execBlockNum,
uint32_t scanNum,
uint32_t subscanNum,
uint32_t numTimes,
uint32_t numAntennas,
uint32_t numChannels,
NetSideband netSideband,
uint64_t time,
uint64_t interval,
const vector<AUTODATATYPE>& wvrData,
const vector<FLAGSTYPE>& flags);
/**
* Writes the XML global header on the MIME message stream, when binary data are (sub)integrations
* produced by the correlator.
* @param startime start time.
* @param execBlockUID the UID of the exec block.
* @param execBlockNum the index of the exec block.
* @param scanNum the index of the scan.
* @param subscanNum the index of the subscan.
* @param numAntenna the number of antenna.
* @param correlationMode the correlation mode code.
* @param spectralResolution the spectral resolution code.
* @param dataStruct the description of the binary data structure.
*
* @throws SDMDataObjectWriterException
*/
void corrDataHeader(uint64_t startime,
const string& execBlockUID,
uint32_t execBlockNum,
uint32_t scanNum,
uint32_t subscanNum,
uint32_t numAntenna,
CorrelationMode correlationMode,
const OptionalSpectralResolutionType& spectralResolutionType,
SDMDataObject::DataStruct& dataStruct);
/**
* Writes one integration (local header + binary attachment) of correlator data on the MIME message stream.
* @param integrationNum the index (1 based) of the integration.
* @param time time of the integration.
* @param interval interval of the integration.
* @param flags the values of flags.
* @param actualTimes the values of actualTimes.
* @param actualDurations the values of actualDurations.
* @param zeroLags the values of zeroLags.
* @param crossData the values of crossData (encoded in int).
* @param autoData the values of autoData.
*
* @throws SDMDataObjectWriterException
*
* @note
* This method is to be used when cross data are coded with "int" values.
*
* @par
* If this integration contains only cross data (CROSS_ONLY) , the autoData
* parameter is ignored. A empty vector can be passed as an actual parameter.
*
*/
void addIntegration(uint32_t integrationNum,
uint64_t time,
uint64_t interval,
const vector<FLAGSTYPE>& flags,
const vector<ACTUALTIMESTYPE>& actualTimes,
const vector<ACTUALDURATIONSTYPE>& actualDurations,
const vector<ZEROLAGSTYPE>& zeroLags,
const vector<INTCROSSDATATYPE>& crossData,
const vector<AUTODATATYPE>& autoData);
/**
* Writes an integration (local header + binary attachment) on the MIME message stream.
* @param integrationNum the index (1 based) of the integration.
* @param time time of the integration.
* @param interval interval of the integration.
* @param flags the values of flags.
* @param actualTimes the values of actualTimes.
* @param actualDurations the values of actualDurations.
* @param zeroLags the values of zeroLags.
* @param crossData the values of crossData (encoded in short).
* @param autoData the values of autoData.
*
* @throws SDMDataObjectWriterException
*
* @note
* This method is to be used when cross data are coded with "short" values.
*
* @par
* If this integration contains only cross data (CROSS_ONLY) , the autoData
* parameter is ignored. A empty vector can be passed as an actual parameter.
*
*/
void addIntegration(uint32_t integrationNum,
uint64_t time,
uint64_t interval,
const vector<FLAGSTYPE>& flags,
const vector<ACTUALTIMESTYPE>& actualTimes,
const vector<ACTUALDURATIONSTYPE>& actualDurations,
const vector<ZEROLAGSTYPE>& zeroLags,
const vector<SHORTCROSSDATATYPE>& crossData,
const vector<AUTODATATYPE>& autoData);
/**
* Writes an integration (local header + binary attachment) on the MIME message stream.
* @param integrationNum the index (1 based) of the integration.
* @param time time of the integration.
* @param interval interval of the integration.
* @param flags the values of flags.
* @param actualTimes the values of actualTimes.
* @param actualDurations the values of actualDurations.
* @param zeroLags the values of zeroLags.
* @param crossData the values of crossData (encoded in float).
* @param autoData the values of autoData.
*
* @throws SDMDataObjectWriterException
*
* @note
* This method is to be used when cross data are coded with "float" values.
*
* @par
* If this integration contains only cross data (CROSS_ONLY) , the autoData
* parameter is ignored. A empty vector can be passed as an actual parameter.
*
*/
void addIntegration(uint32_t integrationNum,
uint64_t time,
uint64_t interval,
const vector<FLAGSTYPE>& flags,
const vector<ACTUALTIMESTYPE>& actualTimes,
const vector<ACTUALDURATIONSTYPE>& actualDurations,
const vector<ZEROLAGSTYPE>& zeroLags,
const vector<FLOATCROSSDATATYPE>& crossData,
const vector<AUTODATATYPE>& autoData);
/**
* Writes an subintegration (local header + binary attachment) on the MIME message stream.
* @param integrationNum the index (1 based) of the integration.
* @param subintegrationNum the index(1 based) of the subintegration.
* @param time time of the integration.
* @param interval interval of the integration.
* @param flags the values of flags.
* @param actualTimes the values of actualTimes.
* @param actualDurations the values of actualDurations.
* @param zeroLags the values of zeroLags.
* @param crossData the values of crossData (encoded in int).
* @param autoData the values of autoData.
*
* @throws SDMDataObjectWriterException
*
* @note
* This method is to be used when cross data are coded with "int" values.
*
* @par
* If this integration contains only cross data (CROSS_ONLY) , the autoData
* parameter is ignored. A empty vector can be passed as an actual parameter.
*
*/
void addSubintegration(uint32_t integrationNum,
uint32_t subintegrationNum,
uint64_t time,
uint64_t interval,
const vector<FLAGSTYPE>& flags,
const vector<ACTUALTIMESTYPE>& actualTimes,
const vector<ACTUALDURATIONSTYPE>& actualDurations,
const vector<ZEROLAGSTYPE>& zeroLags,
const vector<INTCROSSDATATYPE>& crossData,
const vector<AUTODATATYPE>& autoData);
/**
* Writes an subintegration (local header + binary attachment) on the MIME message stream.
* @param integrationNum the index (1 based) of the integration.
* @param subintegrationNum the index(1 based) of the subintegration.
* @param time time of the integration.
* @param interval interval of the integration.
* @param flags the values of flags.
* @param actualTimes the values of actualTimes.
* @param actualDurations the values of actualDurations.
* @param zeroLags the values of zeroLags.
* @param crossData the values of crossData (encoded in short).
* @param autoData the values of autoData.
*
* @throws SDMDataObjectWriterException
*
* @note
* This method is to be used when cross data are coded with "short" values.
*
* @par
* If this integration contains only cross data (CROSS_ONLY) , the autoData
* parameter is ignored. A empty vector can be passed as an actual parameter.
*
*/
void addSubintegration(uint32_t integrationNum,
uint32_t subintegrationNum,
uint64_t time,
uint64_t interval,
const vector<FLAGSTYPE>& flags,
const vector<ACTUALTIMESTYPE>& actualTimes,
const vector<ACTUALDURATIONSTYPE>& actualDurations,
const vector<ZEROLAGSTYPE>& zeroLags,
const vector<SHORTCROSSDATATYPE>& crossData,
const vector<AUTODATATYPE>& autoData);
/**
* Writes an subintegration (local header + binary attachment) on the MIME message stream.
* @param integrationNum the index (1 based) of the integration.
* @param subintegrationNum the index(1 based) of the subintegration.
* @param time time of the integration.
* @param interval interval of the integration.
* @param flags the values of flags.
* @param actualTimes the values of actualTimes.
* @param actualDurations the values of actualDurations.
* @param zeroLags the values of zeroLags.
* @param crossData the values of crossData (encoded in float).
* @param autoData the values of autoData.
*
* @throws SDMDataObjectWriterException
*
* @note
* This method is to be used when cross data are coded with "float" values.
*
* @par
* If this integration contains only cross data (CROSS_ONLY) , the autoData
* parameter is ignored. A empty vector can be passed as an actual parameter.
*
*/
void addSubintegration(uint32_t integrationNum,
uint32_t subintegrationNum,
uint64_t time,
uint64_t interval,
const vector<FLAGSTYPE>& flags,
const vector<ACTUALTIMESTYPE>& actualTimes,
const vector<ACTUALDURATIONSTYPE>& actualDurations,
const vector<ZEROLAGSTYPE>& zeroLags,
const vector<FLOATCROSSDATATYPE>& crossData,
const vector<AUTODATATYPE>& autoData);
/**
* Returns the number of bytes written so far.
* This method can be used at any time during the life of an instance of SDMDataObjectWriter.
* It returns the number of bytes emitted on the output (memory, standard output, disk file...)
* as the methods of this class, except done, are called.
* <ul>
* <li>This number is set to 0 at the creation of an SDMDataObjectWriter,</li>
* <li>it is incremented accordingly with the number of bytes emitted by the different methods, except done, </li>
* <li>it is reset to 0 by a call to the method done.</li>
* </ul>
*
* @return an uint64_t.
*/
uint64_t numBytes();
void output (const string& s);
void outputln (const string& s);
void output (const float* data, uint32_t numData);
void outputln (const float* data, uint32_t numData);
void outputln (const long long* data, uint32_t numData);
template <class T> void output(const vector<T>& data) {
numBytes_ += data.size()*sizeof(T);
switch (otype_) {
case STDOUT:
cout.write((const char*)&data.at(0), data.size()*sizeof(T));
break;
case MEMORY:
oss_->write((const char*)&data.at(0), data.size()*sizeof(T));
break;
case FILE:
ofs_->write((const char*)&data.at(0), data.size()*sizeof(T));
break;
}
}
template <class T> void outputln (const vector<T>& data) {
output<T>(data);
outputln();
}
void outputln ();
void outputlnLocation(const string& name, const SDMDataSubset& sdmDataSubset);
private:
enum OUTDEST {STDOUT, MEMORY, FILE};
OUTDEST otype_;
ofstream* ofs_;
ostringstream* oss_;
// The ALMA uid of the MIME message.
string uid_;
// The title of the binary data.
string title_;
// The subscan path.
string subscanPath_;
// An SDMDataObject
SDMDataObject sdmDataObject_;
// The number of the SDMDataSubset being written
uint32_t sdmDataSubsetNum_;
// Two strings used as MIME boundaries
static const string MIMEBOUNDARY_1;
static const string MIMEBOUNDARY_2;
// Class initialization stuff
static const bool initClass_;
static bool initClass();
// The axes names definitions for WVR data and their related flags.
static vector<AxisName> WVRDATAAXES, WVRDATAFLAGSAXES;
// A utility to fill a vector of <Enum> from a an array of c-strings.
template <class Enum, class EnumHelper> static vector<Enum> enumvec(const string& strliterals) {
vector<Enum> result;
string strliteral;
stringstream ss(strliterals);
vector<string> tokens;
while (ss >> strliteral)
result.push_back(EnumHelper::literal(strliteral));
return result;
}
// Writes the very first part of the MIME message.
void preamble();
// Write the very end of the MIME message.
void postamble();
void addData(uint32_t integrationNum,
uint32_t subintegrationNum,
uint64_t time,
uint64_t interval,
const vector<FLAGSTYPE>& flags,
const vector<ACTUALTIMESTYPE>& actualTimes,
const vector<ACTUALDURATIONSTYPE>& actualDurations,
const vector<ZEROLAGSTYPE>& zeroLags,
const vector<INTCROSSDATATYPE>& intCrossData,
const vector<SHORTCROSSDATATYPE>& shortCrossData,
const vector<FLOATCROSSDATATYPE>& floatCrossData,
const vector<AUTODATATYPE>& autoData);
// Are we done with this ?
bool done_;
// The number of bytes written so far.
uint64_t numBytes_;
// A small finite state automaton to control the usage of SDMDataObjectWriter.
enum States {START, S_TPDATA, S_TPDATAHEADER, S_ADDTPSUBSCAN, S_ADDTPINTEGRATION, S_WVRDATA, S_CORRDATAHEADER, S_ADDINTEGRATION, S_ADDSUBINTEGRATION, END};
enum Transitions {T_TPDATA, T_TPDATAHEADER, T_ADDTPSUBSCAN, T_ADDTPINTEGRATION, T_WVRDATA, T_CORRDATAHEADER, T_ADDINTEGRATION, T_ADDSUBINTEGRATION, T_DONE};
States currentState_;
void checkState(Transitions t, const string& methodName);
};
} // namespace asdmbinaries
#endif // SDMDataObjectWriter_CLASS
| true |
fc8289b37183f7896b924b3bdfe33d79e0540bb2 | C++ | PedroMalho/POO | /fichapython1_6.cpp | UTF-8 | 413 | 3.359375 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;
main()
{
int segundos;
cout << "Insira os segundos: ";
cin >> segundos;
float dias = segundos / 86400.00;
float horas = dias - floor(dias);
float minutos = horas * 60.00;
float segundo = minutos * 60.00;
cout << "dias: " << floor(dias) << " | horas: " << horas << " | mins: " << minutos << " | segs: " << segundo;
}
| true |
a3f99507c7b2370869d3c2e19b245cdb487be2a8 | C++ | seqan/iGenVar | /src/modules/clustering/hierarchical_clustering_method.cpp | UTF-8 | 10,701 | 2.59375 | 3 | [
"BSD-3-Clause"
] | permissive | #include "modules/clustering/hierarchical_clustering_method.hpp"
#include <limits> // for std::numeric_limits
#include <random> // for std::mt19937
#include <seqan3/core/debug_stream.hpp>
#include "iGenVar.hpp" // for global variable gVerbose
#include "fastcluster.h" // for hclust_fast
std::vector<std::vector<Junction>> partition_junctions(std::vector<Junction> const & junctions,
int32_t const partition_max_distance)
{
// Partition based on mate 1
std::vector<Junction> current_partition{};
std::vector<std::vector<Junction>> current_partition_splitted;
std::vector<std::vector<Junction>> final_partitions{};
for (Junction const & junction : junctions)
{
if (current_partition.empty())
{
current_partition.push_back(junction);
}
else
{
if (junction.get_mate1().seq_name != current_partition.back().get_mate1().seq_name ||
junction.get_mate1().orientation != current_partition.back().get_mate1().orientation ||
std::abs(junction.get_mate1().position - current_partition.back().get_mate1().position)
> partition_max_distance)
{
// Partition based on mate 2
std::sort(current_partition.begin(), current_partition.end(), [](Junction const & a, Junction const & b) {
return a.get_mate2() < b.get_mate2();
});
current_partition_splitted = split_partition_based_on_mate2(current_partition, partition_max_distance);
for (std::vector<Junction> partition : current_partition_splitted)
{
final_partitions.push_back(partition);
}
current_partition.clear();
}
current_partition.push_back(junction);
}
}
if (!current_partition.empty())
{
std::sort(current_partition.begin(), current_partition.end(), [](Junction a, Junction b) {
return a.get_mate2() < b.get_mate2();
});
current_partition_splitted = split_partition_based_on_mate2(current_partition, partition_max_distance);
for (std::vector<Junction> partition : current_partition_splitted)
{
final_partitions.push_back(partition);
}
}
return final_partitions;
}
std::vector<std::vector<Junction>> split_partition_based_on_mate2(std::vector<Junction> const & partition,
int32_t const partition_max_distance)
{
std::vector<Junction> current_partition{};
std::vector<std::vector<Junction>> splitted_partition{};
for (Junction const & junction : partition)
{
if (current_partition.empty())
{
current_partition.push_back(junction);
}
else
{
if (junction.get_mate2().seq_name != current_partition.back().get_mate2().seq_name ||
junction.get_mate2().orientation != current_partition.back().get_mate2().orientation ||
std::abs(junction.get_mate2().position - current_partition.back().get_mate2().position)
> partition_max_distance)
{
std::sort(current_partition.begin(), current_partition.end());
splitted_partition.push_back(current_partition);
current_partition.clear();
}
current_partition.push_back(junction);
}
}
if (!current_partition.empty())
{
std::sort(current_partition.begin(), current_partition.end());
splitted_partition.push_back(current_partition);
}
return splitted_partition;
}
double junction_distance(Junction const & lhs, Junction const & rhs)
{
// lhs and rhs connect the same chromosomes with the same orientations
if ((lhs.get_mate1().seq_name == rhs.get_mate1().seq_name) &&
(lhs.get_mate1().orientation == rhs.get_mate1().orientation) &&
(lhs.get_mate2().seq_name == rhs.get_mate2().seq_name) &&
(lhs.get_mate2().orientation == rhs.get_mate2().orientation))
{
// lhs and rhs are intra-chromosomal adjacencies
if (lhs.get_mate1().seq_name == lhs.get_mate2().seq_name)
{
// the directed size is the directed distance between both mates
// the directed size is positive for insertions and negative for deletions
int32_t lhs_directed_size = lhs.get_inserted_sequence().size() +
lhs.get_mate1().position -
lhs.get_mate2().position;
int32_t rhs_directed_size = rhs.get_inserted_sequence().size() +
rhs.get_mate1().position -
rhs.get_mate2().position;
// lhs and rhs have the same type (either deletion/inversion or insertion)
if ((lhs_directed_size < 0 && rhs_directed_size < 0) ||
(lhs_directed_size > 0 && rhs_directed_size > 0))
{
double position_distance = std::abs(lhs.get_mate1().position - rhs.get_mate1().position) / 1000.0;
// TODO (irallia 01.09.2021): std::abs((int)(lhs.get_tandem_dup_count() - rhs.get_tandem_dup_count()))
double size_distance = ((double)(std::max(std::abs(lhs_directed_size), std::abs(rhs_directed_size))) /
(double)(std::min(std::abs(lhs_directed_size), std::abs(rhs_directed_size)))) - 1.0;
return position_distance + size_distance;
}
// lhs and rhs have different types
else
{
return std::numeric_limits<double>::max();
}
}
// lhs and rhs are inter-chromosomal adjacencies
else
{
double position_distance1 = std::abs(lhs.get_mate1().position - rhs.get_mate1().position) / 1000.0;
double position_distance2 = std::abs(lhs.get_mate2().position - rhs.get_mate2().position) / 1000.0;
// TODO (irallia 01.09.2021): std::abs((int)(lhs.get_tandem_dup_count() - rhs.get_tandem_dup_count()))
double size_distance = std::abs((double)(lhs.get_inserted_sequence().size() - rhs.get_inserted_sequence().size())) / 1000.0;
return position_distance1 + position_distance2 + size_distance;
}
}
else
{
return std::numeric_limits<double>::max();
}
}
inline std::vector<Junction> subsample_partition(std::vector<Junction> const & partition, uint16_t const sample_size)
{
assert(partition.size() >= sample_size);
std::vector<Junction> subsample{};
std::sample(partition.begin(), partition.end(), std::back_inserter(subsample),
sample_size, std::mt19937{}); // use default seed for deterministic results
return subsample;
}
std::vector<Cluster> hierarchical_clustering_method(std::vector<Junction> const & junctions,
int32_t const partition_max_distance,
double clustering_cutoff)
{
auto partitions = partition_junctions(junctions, partition_max_distance);
std::vector<Cluster> clusters{};
// Set the maximum partition size that is still feasible to cluster in reasonable time
// A trade-off between reducing runtime and keeping as many junctions as possible has to be made
const size_t max_partition_size = 200;
for (std::vector<Junction> & partition : partitions)
{
size_t partition_size = partition.size();
if (partition_size < 2)
{
clusters.emplace_back(std::move(partition));
continue;
}
if (partition_size > max_partition_size)
{
if (gVerbose)
{
seqan3::debug_stream << "A partition exceeds the maximum size ("
<< partition_size
<< ">"
<< max_partition_size
<< ") and has to be subsampled. Representative partition member:\n["
<< partition[0].get_mate1()
<< "] -> ["
<< partition[0].get_mate2()
<< "]\n";
}
partition = subsample_partition(partition, max_partition_size);
partition_size = max_partition_size;
}
// Compute condensed distance matrix (upper triangle of the full distance matrix)
std::vector<double> distmat ((partition_size * (partition_size - 1)) / 2);
size_t k, i, j;
for (i = k = 0; i < partition_size; ++i) {
for (j = i + 1; j< partition_size; ++j) {
// Compute distance between junctions i and j
distmat[k] = junction_distance(partition[i], partition[j]);
++k;
}
}
// Perform hierarchical clustering
// `height` is filled with cluster distance for each step
// `merge` contains dendrogram
std::vector<int> merge (2 * (partition_size - 1));
std::vector<double> height (partition_size - 1);
hclust_fast(partition_size, distmat.data(), HCLUST_METHOD_AVERAGE, merge.data(), height.data());
// Fill labels[i] with cluster label of junction i.
// Clustering is stopped at step with cluster distance >= clustering_cutoff
std::vector<int> labels (partition_size);
cutree_cdist(partition_size, merge.data(), height.data(), clustering_cutoff, labels.data());
std::unordered_map<int, std::vector<Junction>> label_to_junctions{};
for (size_t i = 0; i < partition_size; ++i)
{
if (label_to_junctions.find(labels[i]) != label_to_junctions.end())
{
label_to_junctions[labels[i]].push_back(std::move(partition[i]));
}
else{
label_to_junctions.emplace(labels[i], std::vector{std::move(partition[i])});
}
}
// Add new clusters: junctions with the same label belong to one cluster
for (auto & [lab, jun] : label_to_junctions )
{
(void) lab;
std::sort(jun.begin(), jun.end());
clusters.emplace_back(jun);
}
}
std::sort(clusters.begin(), clusters.end());
return clusters;
}
| true |
9a33b62bfa312e29931c8a19e06775fcc17f160d | C++ | vivekverma123/OSLab | /Threads/producer_consumer.cpp | UTF-8 | 1,124 | 3.578125 | 4 | [] | no_license | #include<iostream>
#include<thread>
using namespace std;
int mutex = 1,empty = 0,full = 0,n;
void wait(int *ptr)
{
while(*ptr <= 0);
(*ptr)--;
}
void signal(int *ptr)
{
*ptr += 1;
}
void consume()
{
int i = 0;
do
{
wait(&full);
wait(&mutex);
printf("Item %d removed from buffer.\n",i);
/* this region is the critical section as only consumer has the access to the buffer */
signal(&mutex);
signal(&empty);
printf("Item %d consumed from buffer.\n",i);
i += 1;
if(i==n)
{
break;
}
}while(1);
}
void produce()
{
int i = 0;
do
{
printf("Item %d produced.\n",i);
wait(&empty);
wait(&mutex);
printf("Item %d added to the buffer.\n",i);
/* this region is the critical section as only producer has the access to the buffer */
signal(&mutex);
signal(&full);
i += 1;
if(i==n)
{
break;
}
}while(1);
}
int main()
{
thread prod,cons;
printf("Enter the number of items to be produced: ");
scanf("%d",&n);
empty = n;
prod = thread(produce);
cons = thread(consume);
prod.join();
cons.join();
pthread_exit(NULL);
return 0;
}
| true |
97aefc6834142f96679431aa22aa5258580be9dc | C++ | liukang92/hiho | /week43$/week43.cpp | UTF-8 | 1,385 | 2.640625 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
#define int64 long long
#define MOD 12357
const int N = (1 << 7) + 5;
int k;
int64 n;
int t[N][N];
void dfs(int x, int y, int col, int **a){
if(col == k){
a[y][x] = 1;
return;
}
dfs(x << 1, (y << 1) + 1, col + 1, a);
dfs((x << 1) + 1, y << 1, col + 1, a);
if(col + 2 <= k){
dfs((x << 2) + 3, (y << 2) + 3, col + 2, a);
}
}
void p(int **a, int **b, int **c, int dim){
int sum = 0;
for(int i = 0; i < dim; i++){
for(int j = 0; j < dim; j++){
sum = 0;
for(int k = 0; k < dim; k++){
sum += a[i][k] * b[k][j];
}
t[i][j] = sum % MOD;
}
}
for(int i = 0; i < dim; i++){
for(int j = 0; j < dim; j++){
c[i][j] = t[i][j];
}
}
}
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
scanf("%d %d", &k, &n);
int dim = 1 << k;
int **r = new int*[dim];
int **a = new int*[dim];
for(int i = 0; i < dim; i++){
r[i] = new int[dim];
a[i] = new int[dim];
memset(r[i], 0, dim * sizeof(int));
memset(a[i], 0, dim * sizeof(int));
r[i][i] = 1;
}
dfs(0, 0, 0, a);
while(n){
if(n & 1){
p(r, a, r, dim);
}
p(a, a, a, dim);
n >>= 1;
}
printf("%d\n", r[dim - 1][dim - 1]);
for(int i = 0; i < dim; i++){
delete[] r[i], a[i];
}
delete[] r, a;
return 0;
#ifndef ONLINE_JUDGE
fclose(stdin);
// fclose(stdout);
#endif
}
| true |
54a432a2f728a7bc2b739b25fbabf7bbe21ddc7e | C++ | TrojanOlx/AI | /Face_Dlib_C#/Dlib/DlibDotNet.Native/dlib/matrix/matrix_math_functions.h | UTF-8 | 2,623 | 2.609375 | 3 | [
"MIT"
] | permissive | #ifndef _CPP_MATRIX_MATH_FUNCTIONS_H_
#define _CPP_MATRIX_MATH_FUNCTIONS_H_
#include "../export.h"
#include <dlib/matrix.h>
#include <dlib/matrix/matrix_math_functions.h>
#include <dlib/geometry/rectangle.h>
#include <dlib/geometry/vector.h>
#include "../shared.h"
using namespace dlib;
using namespace std;
#pragma region template
#define matrix_round_template_sub(__TYPE__, __ROWS__, __COLUMNS__, error, matrix, ret) \
dlib::matrix<__TYPE__, __ROWS__, __COLUMNS__>& mat = *static_cast<dlib::matrix<__TYPE__, __ROWS__, __COLUMNS__>*>(matrix);\
dlib::matrix<__TYPE__, __ROWS__, __COLUMNS__> m = dlib::round(mat);\
*ret = new dlib::matrix<__TYPE__, __ROWS__, __COLUMNS__>(m);\
#define matrix_round_template(__TYPE__, __ROWS__, __COLUMNS__, error, matrix, ret) \
do {\
matrix_template_size_arg2_template(__TYPE__, __ROWS__, __COLUMNS__, matrix_round_template_sub, error, matrix, ret);\
} while (0)
#pragma endregion template
DLLEXPORT int matrix_round(matrix_element_type type, void* matrix, int templateRows, int templateColumns, void** ret)
{
int error = ERR_OK;
switch(type)
{
case matrix_element_type::UInt8:
matrix_round_template(uint8_t, templateRows, templateColumns, error, matrix, ret);
break;
case matrix_element_type::UInt16:
matrix_round_template(uint16_t, templateRows, templateColumns, error, matrix, ret);
break;
case matrix_element_type::UInt32:
matrix_round_template(uint32_t, templateRows, templateColumns, error, matrix, ret);
break;
case matrix_element_type::Int8:
matrix_round_template(int8_t, templateRows, templateColumns, error, matrix, ret);
break;
case matrix_element_type::Int16:
matrix_round_template(int16_t, templateRows, templateColumns, error, matrix, ret);
break;
case matrix_element_type::Int32:
matrix_round_template(int32_t, templateRows, templateColumns, error, matrix, ret);
break;
case matrix_element_type::Float:
matrix_round_template(float, templateRows, templateColumns, error, matrix, ret);
break;
case matrix_element_type::Double:
matrix_round_template(double, templateRows, templateColumns, error, matrix, ret);
break;
case matrix_element_type::RgbPixel:
case matrix_element_type::HsiPixel:
case matrix_element_type::RgbAlphaPixel:
default:
error = ERR_MATRIX_ELEMENT_TYPE_NOT_SUPPORT;
break;
}
return error;
}
#endif | true |
38152792e76e2939b9a86257c710485947dffc4d | C++ | mhcoderwl/leetcode | /4.1.3.cpp | UTF-8 | 739 | 3.734375 | 4 | [] | no_license | /*给一个数组代表一个直方图,找到最大面积的矩形
* 思路:用一个栈,如果当前高度小于栈顶,则处理掉所有比他大的元素然后入栈*/
#include<iostream>
#include<stack>
#include<vector>
#include<algorithm>
using namespace std;
class Solution{
public:
int LargestRectangleArea(vector<int>& height){
stack<int> s;
height.push_back(0);
int result=0;
for(int i=0;i<height.size();){
if(s.empty()||height[s.top()]<height[i])
s.push(i++);
else{
int tmp=s.top();
s.pop();
result=max(result,height[tmp]*(s.empty()?i:i-s.top()-1));
}
}
return result;
}
};
int main(){
Solution s;
vector<int> height={2,1,5,6,2,3};
cout<<s.LargestRectangleArea(height);
cout<<endl;
}
| true |
53cd36e31b0a34623f29cd65e855e2df98658105 | C++ | ry0u/SRM | /SRM500/MafiaGame.cpp | UTF-8 | 2,922 | 2.84375 | 3 | [] | no_license | // BEGIN CUT HERE
// END CUT HERE
#line 5 "MafiaGame.cpp"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <cstring>
#include <queue>
#include <set>
#include <map>
#define REP(i,k,n) for(int i=k;i<n;i++)
#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;
typedef long long ll;
class MafiaGame {
public:
double probabilityToLose(int N, vector <int> decisions) {
vector<int> v(decisions.begin(),decisions.end());
int cnt[505];
memset(cnt,0,sizeof(cnt));
rep(i,v.size()) {
cnt[v[i]]++;
}
int vmax = 0;
rep(i,N) {
vmax = max(vmax,cnt[i]);
}
if(vmax == 1) return 0.0;
int c = 0;
rep(i,N) {
if(cnt[i] == vmax) c++;
}
if(c == 1) return 1.0;
double ans = 1.0/c;
while(c != 1) {
if(N%c == 0) return 0.0;
c = N%c;
}
return ans;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const double &Expected, const double &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arg0 = 3; int Arr1[] = {1, 1, 1}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 1.0; verify_case(0, Arg2, probabilityToLose(Arg0, Arg1)); }
void test_case_1() { int Arg0 = 5; int Arr1[] = {1, 2, 3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 0.0; verify_case(1, Arg2, probabilityToLose(Arg0, Arg1)); }
void test_case_2() { int Arg0 = 20; int Arr1[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 18, 19, 0}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 0.0; verify_case(2, Arg2, probabilityToLose(Arg0, Arg1)); }
void test_case_3() { int Arg0 = 23; int Arr1[] = {17, 10, 3, 14, 22, 5, 11, 10, 22, 3, 14, 5, 11, 17}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 0.14285714285714285; verify_case(3, Arg2, probabilityToLose(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
MafiaGame ___test;
___test.run_test(-1);
int n = 11;
vector<int> v(1);
cout << ___test.probabilityToLose(n,v) << endl;
}
// END CUT HERE
| true |
2af9bf531fe499d5c1894c2db369612279662f5c | C++ | zhangzhiming1017/design_pattern | /抽象工厂模式.cpp | UTF-8 | 3,912 | 3.421875 | 3 | [] | no_license | #include <iostream>
//水果产品
class fruit {
public:
virtual void show() = 0;
};
class banana : public fruit {
public:
void show() override {
std::cout << "banana" << std::endl;
}
};
class apple : public fruit {
public:
void show() override {
std::cout << "apple" << std::endl;
}
};
class orange : public fruit {
public:
void show() override {
std::cout << "orange" << std::endl;
}
};
//果汁产品
class fruitJuice {
public:
virtual void show() = 0;
};
class bananaJuice : public fruitJuice {
public:
void show() override {
std::cout << "bananaJuice" << std::endl;
}
};
class appleJuice : public fruitJuice {
public:
void show() override {
std::cout << "appleJuice" << std::endl;
}
};
class orangeJuice : public fruitJuice {
public:
void show() override {
std::cout << "orangeJuice" << std::endl;
}
};
enum class fruitType :int { BANANA = 0, APPLE = 1, ORANGE = 2 };
enum class fruitJuiceType :int { BANANAJUICE = 0, APPLEJUICE = 1, ORANGEJUICE = 2 };
//抽象工厂
class abstractFactory {
public:
virtual fruit* createFruit(fruitType e) = 0;
virtual fruitJuice* createFruitJuice(fruitJuiceType e) = 0;
};
class factoryCreateA : public abstractFactory {
public:
virtual fruit* createFruit(fruitType e) override {
std::cout << "factoryCreateA create!" << std::endl;
switch (e)
{
case fruitType::BANANA:
return new banana();
break;
case fruitType::APPLE:
return new apple();
break;
case fruitType::ORANGE:
return new orange();
break;
default:
break;
}
return NULL;
};
virtual fruitJuice* createFruitJuice(fruitJuiceType e) override {
std::cout << "factoryCreateA create!" << std::endl;
switch (e)
{
case fruitJuiceType::BANANAJUICE:
return new bananaJuice();
break;
case fruitJuiceType::APPLEJUICE:
return new appleJuice();
break;
case fruitJuiceType::ORANGEJUICE:
return new orangeJuice();
break;
default:
break;
}
return NULL;
};
};
class factoryCreateB :public abstractFactory {
public:
virtual fruit* createFruit(fruitType e) override {
std::cout << "factoryCreateB create!" << std::endl;
switch (e)
{
case fruitType::BANANA:
return new banana();
break;
case fruitType::APPLE:
return new apple();
break;
case fruitType::ORANGE:
return new orange();
break;
default:
break;
}
return NULL;
};
virtual fruitJuice* createFruitJuice(fruitJuiceType e) override {
std::cout << "factoryCreateB create!" << std::endl;
switch (e)
{
case fruitJuiceType::BANANAJUICE:
return new bananaJuice();
break;
case fruitJuiceType::APPLEJUICE:
return new appleJuice();
break;
case fruitJuiceType::ORANGEJUICE:
return new orangeJuice();
break;
default:
break;
}
return NULL;
};
};
int main() {
factoryCreateA* A = new factoryCreateA();
factoryCreateB* B = new factoryCreateB();
fruit* Abanana = A->createFruit(fruitType::BANANA);
Abanana->show();
fruit* Aapple = A->createFruit(fruitType::APPLE);
Aapple->show();
fruit* Aorange = A->createFruit(fruitType::ORANGE);
Aorange->show();
fruitJuice* AbananaJuice = A->createFruitJuice(fruitJuiceType::BANANAJUICE);
AbananaJuice->show();
fruitJuice* AappleJuice = A->createFruitJuice(fruitJuiceType::APPLEJUICE);
AappleJuice->show();
fruitJuice* AorangeJuice = A->createFruitJuice(fruitJuiceType::ORANGEJUICE);
AorangeJuice->show();
fruit* Bbanana = B->createFruit(fruitType::BANANA);
Bbanana->show();
fruit* Bapple = B->createFruit(fruitType::APPLE);
Bapple->show();
fruit* Borange = B->createFruit(fruitType::ORANGE);
Borange->show();
fruitJuice* BbananaJuice = B->createFruitJuice(fruitJuiceType::BANANAJUICE);
BbananaJuice->show();
fruitJuice* BappleJuice = B->createFruitJuice(fruitJuiceType::APPLEJUICE);
BappleJuice->show();
fruitJuice* BorangeJuice = B->createFruitJuice(fruitJuiceType::ORANGEJUICE);
BorangeJuice->show();
return 0;
}
| true |
be6e9bc92603b96c6314be8b261004d68f0241da | C++ | CavaniNicolas/CppZZ2_TPs | /TP7/pile/src/Main.cpp | UTF-8 | 167 | 2.546875 | 3 | [] | no_license |
#include "PileGen.hpp"
int main(int, char const **)
{
PileGen<int> p(10);
p.push(2);
p.push(3);
std::cout << p.top() << std::endl;
return 0;
}
| true |
32e1c2b3a464b3dcb15db99023c7f7906d5d144a | C++ | 7kia/Theory-programming | /Project/Enemy.cpp | WINDOWS-1251 | 4,453 | 2.671875 | 3 | [] | no_license | #include "Enemy.h"
#include "Items.h"
#include "UnlifeObject.h"
#include "EntityVar.h"
void initializeEntitys(TypesEnemy *typesEnemy, std::vector<Enemy> &enemy, int countEnemy,
Item &emptyItem, UnlifeObject &emptyObject)//
{
srand(time(0)); //
//////////////////////////////////////////////////////////////
//
Enemy* addEnemy = new Enemy();
TypeEnemy* typeEnemy = &typesEnemy->typesEnemy[idEnemy::wolfEnemy];
int xPos;
int yPos;
int levelFloor;
for (size_t i = 0; i < 1; i++) {
countEnemy++;
if (countEnemy > AMOUNT_ENTITY) {
break;
}
int xPos = 9 + rand() % 5;
int yPos = 9 + rand() % 5;
int levelFloor = 0;
addEnemy->EnemyInit(*typeEnemy, emptyItem, emptyObject, xPos, yPos, levelFloor);
enemy.push_back(*addEnemy);
}
//////////////////////////////////////////////////////////////
//
typeEnemy = &typesEnemy->typesEnemy[idEnemy::skeletEnemy];
for (size_t i = 0; i < 0; i++) {
countEnemy++;
if (countEnemy > AMOUNT_ENTITY) {
break;
}
xPos = 9 + rand() % 5;
yPos = 9 + rand() % 5;
levelFloor = 0;
addEnemy->EnemyInit(*typeEnemy, emptyItem, emptyObject, xPos, yPos, levelFloor);
enemy.push_back(*addEnemy);
}
//////////////////////////////////////////////////////////////
delete addEnemy;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
void Enemy::EnemyInit(TypeEnemy &typesEnemy, Item &emptyItem, UnlifeObject &emptyObject,
int xPos, int yPos, int level)
{
spriteEntity = new Sprite;
type = &typesEnemy;
width = type->width;
height = type->height;
//
radiusUse = 1;
currenMode = idEntityMode::walk;
//
stepFirst = SPEED_ENTITY;
stepCurrent = SPEED_ENTITY;
//
spriteEntity->setTexture(*type->textureEntity);
spriteEntity->setTextureRect(IntRect(0, 0, type->width, type->height));
//
soundsEntity[idSoundEntity::stepGrass] = type->soundsEntity[idSoundEntity::stepGrass];
soundsEntity[idSoundEntity::stepStone] = type->soundsEntity[idSoundEntity::stepStone];
findItem = new Item;
findObject = new UnlifeObject;
//
this->emptyObject = &emptyObject;
this->emptyItem = &emptyItem;
idSelectItem = 0;
//
currentLevelFloor = level;
currenMode = idEntityMode::walk;
spriteEntity->setOrigin(type->width / 2, type->height / 2);
spriteEntity->setPosition(xPos * SIZE_BLOCK - SIZE_BLOCK / 2, yPos * SIZE_BLOCK - SIZE_BLOCK / 2);
timeAnimation = 0.f;
timeFightAnimation = 0.f;
direction = NONE_DIRECTION;
directionLook = DOWN;
////////////////////////////////////////////////////////////////////////
//
timeWalk = minTimeWalk + rand() % (int(maxTimeWalk - minTimeWalk));
currentTime = 0;
int randomDirection = 1 + rand() % Direction::AMOUNT_DIRECTION;
direction = Direction(randomDirection);
////////////////////////////////////////////////////////////////////////
//
maxHealth = type->maxHealth;
currentHealth = maxHealth;
maxStamina = type->maxStamina;
currentStamina = maxStamina;
maxMana = type->maxMana;
currentMana = maxMana;
currentThirst = maxThirst;
currentHungry = maxHungry;
protectionCut = type->protectionCut;
protectionCrash = type->protectionCrash;
timeOutputDamage = type->timeOutputDamage;
currentTimeOutputDamage = 0.f;
timeInputDamage = 0.f;
cuttingDamage = type->cuttingDamage;
crushingDamage = type->crushingDamage;
damageMultiplirer = 1.f;
}
Enemy::~Enemy()
{
}
void Enemy::randomWalk(const Time &deltaTime) {
if (currenMode == idEntityMode::walk) {
if (currentTime < timeWalk && direction != Direction::NONE_DIRECTION) {
currentTime += deltaTime.asSeconds();
} else {
currentTime = 0;
timeWalk = minTimeWalk + rand() % (int(maxTimeWalk - minTimeWalk));
int randomDirection = 1 + rand() % Direction::AMOUNT_DIRECTION;
direction = Direction(randomDirection);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// | true |
305d3f4744a6c58188812d4437a174537b5982f4 | C++ | chrisantus0816/yap | /Algorithm/Greedy_Dijkstra2.cpp | UTF-8 | 3,470 | 3.6875 | 4 | [] | no_license | #include <iostream>
#include <list>
#include <set>
#include <vector>
//Program to find Dijkstra's shortest path using STL set
using namespace std;
//This class represents a directed graph using
//adjacency list representation
#define INF 0x3f3f3f3f
class Graph
{
int V; //Number of vertices
//In a weighted graph, we need to store vertex
//and weight pair for every edge
list <pair <int,int>> *adj;
public:
Graph(int V); //Constructor
//function to add an edge to graph
void addEdge(int u,int v,int w);
//prints shortest path from s
void shortestPath(int s);
};
//Allocates memory for adjacency list
Graph::Graph(int V)
{
this->V=V;
adj=new list<pair<int,int>>[V];
}
void Graph::addEdge(int u,int v, int w)
{
adj[u].push_back(make_pair(v,w));
adj[v].push_back(make_pair(u,w));
}
//Prints shortest paths from src to all other vertices
void Graph::shortestPath(int src)
{
//Create a set to store vertices that are being
//preprocessed
set<pair<int,int>> setds;
//Create a vector for distances and initialize all distances as infinite(INF)
vector<int> dist(V,INF);
//Insert source itself in Set and initialize its distance as 0
setds.insert(make_pair(0,src));
dist[src]=0;
/*
Looping till all shortest distance are finalized then setds will become empty
*/
while(!setds.empty())
{
//The first vertex in Set is the minimum distance
//vertex, extract it from set
pair<int,int> tmp= *(setds.begin());
setds.erase(setds.begin());
//vertex label is stored in second of pair
//(it has to be done this way to keep the vertices
//sorted distance (distance must be first item in pair)
int u=tmp.second;
// 'i' is used to get all adjacent vertices of a vertex
list<pair<int,int>> :: iterator i;
for(i=adj[u].begin();i!=adj[u].end();++i){
//Get vertex label and weight of current adjacent of u
int v=(*i).first;
int weight=(*i).second;
//If there is shorter path to v through u.
if(dist[v]>dist[u]+weight)
{
/*
If distance of v is not INF then it must be in our set,
so removing it and inserting again with updated less distance
Note : We extract only those vertices from Set for which distance
is finalized. So for them, we would never reach here.
*/
if(dist[v]!=INF)
setds.erase(setds.find(make_pair(dist[v],v)));
//Updating distance of v
dist[v]=dist[u]+weight;
setds.insert(make_pair(dist[v],v));
}
}
}
//print shortest distances stored in dist[]
printf("Vertex Distance from Source \n");
for(int i=0;i<V;++i)
printf("%d \t\t %d\n",i,dist[i]);
}
int main()
{
int V=9;
Graph g(V);
g.addEdge(0, 1, 4);
g.addEdge(0, 7, 8);
g.addEdge(1, 2, 8);
g.addEdge(1, 7, 11);
g.addEdge(2, 3, 7);
g.addEdge(2, 8, 2);
g.addEdge(2, 5, 4);
g.addEdge(3, 4, 9);
g.addEdge(3, 5, 14);
g.addEdge(4, 5, 10);
g.addEdge(5, 6, 2);
g.addEdge(6, 7, 1);
g.addEdge(6, 8, 6);
g.addEdge(7, 8, 7);
g.shortestPath(0);
return 0;
}
| true |
4d9ea45e611c3c408d6a28949d81a9c8a0cf6427 | C++ | ThanasisSt/Cpp_Example_Code | /Example4.cpp | UTF-8 | 1,505 | 3.296875 | 3 | [] | no_license | // Example 4
//
#include "stdafx.h"
#include <iostream>
#include "time.h"
using namespace std;
struct Point{
double x;
double y;
double z;
};
struct Sphere{
Point center;
double radius;
};
struct Grid{
Point *ptogrid;
int sizex;
int sizey;
int sizez;
};
Point SetPoint(double a,double b,double c);
void ViewPoint(Point p);
int _tmain(int argc, _TCHAR* argv[])
{
srand(time(0));
Grid EleNaCl;
cout<<"Give the NaCl lattice dimensions sizex,sizey,sizez : ";
cin>>EleNaCl.sizex>>EleNaCl.sizey>>EleNaCl.sizez;
int npoints=EleNaCl.sizex*EleNaCl.sizey*EleNaCl.sizez;
EleNaCl.ptogrid=new Point [npoints];
for(int i=0;i<npoints;i++){
EleNaCl.ptogrid[i]=SetPoint(rand()%2,rand()%2,rand()%2);
}
cout<<"--------- Random Grid (0 or 1) ---------"<<endl;
for(int i=0;i<npoints;i++){
cout<<"Shmeio "<<i+1<<" ";ViewPoint(EleNaCl.ptogrid[i]);cout<<endl;
}
int m=0;
for(int i=0;i<EleNaCl.sizex;i++){
for(int j=0;j<EleNaCl.sizey;j++){
for(int k=0;k<EleNaCl.sizez;k++){
EleNaCl.ptogrid[m]=SetPoint(i,j,k);
m++;
}
}
}
cout<<"--------- Indexed Grid ---------"<<endl;
for(int i=0;i<npoints;i++){
cout<<"Shmeio "<<i+1<<" ";ViewPoint(EleNaCl.ptogrid[i]);cout<<endl;
}
delete [] EleNaCl.ptogrid;
return 0;
}
Point SetPoint(double x,double y,double z){
Point temp;
temp.x=x;
temp.y=y;
temp.z=z;
return temp;
}
void ViewPoint(Point p){
cout<<"("<<p.x<<","<<p.y<<","<<p.z<<")";
return;
}
| true |
46096018a084eacaa78789b5d64e0459294c3311 | C++ | KeiHasegawa/ISO_IEC_14882 | /14_Templates/0_Templates/test392.cpp | UTF-8 | 245 | 2.703125 | 3 | [] | no_license | #include <stdio.h>
template<class C1> struct S {
static const int ci = 123;
};
template<class C2> const int S<C2>::ci;
double ci;
int main()
{
printf("S<double>::ci = %d\n", S<double>::ci);
printf("ci = %f\n", ci = 456);
return 0;
}
| true |
bc3b0c5c0c6fa79b16dbb89d90d41063aee9ff14 | C++ | igor-anferov/messenger2017 | /shared/include/crypto_pki.h | UTF-8 | 1,864 | 2.53125 | 3 | [] | no_license | #include <string>
#include <functional>
#include <memory>
#include <openssl/rsa.h>
#include "crypto_common.h"
#include "crypto_hash.h"
namespace m2
{
namespace crypto
{
namespace common
{
class IAsymmetricCryptoProvider : public common::ICryptoProvider {
virtual boost::uuids::uuid fingerprint() const = 0;
virtual std::string str_key() const = 0;
};
class OpenSSL_RSA_CryptoProvider final : public IAsymmetricCryptoProvider {
public:
using KeyContainer = std::unique_ptr<RSA, decltype(&RSA_free)>;
using CryptoFunction = std::function<void(const size_t, const unsigned char *, void *, unsigned char *)>;
OpenSSL_RSA_CryptoProvider(const std::string &key, bool is_public);
OpenSSL_RSA_CryptoProvider(KeyContainer &&key, bool is_public);
std::string encrypt(const std::string &string) const override;
std::string decrypt(const std::string &string) const override;
std::string encrypt_to_b64(const std::string &string) const override;
std::string decrypt_from_b64(const std::string &string) const override;
std::unique_ptr<OpenSSL_RSA_CryptoProvider> get_public();
bool is_public() const;
bool is_private() const;
static KeyContainer from_string(const std::string &key, bool is_public);
static std::pair<std::unique_ptr<OpenSSL_RSA_CryptoProvider>, std::unique_ptr<OpenSSL_RSA_CryptoProvider>>
make(int bit_size);
static std::unique_ptr<OpenSSL_RSA_CryptoProvider> make_private(int bit_size);
boost::uuids::uuid fingerprint() const override;
std::string str_key() const override;
protected:
KeyContainer key_;
bool public_;
std::string actor_(bool encryption, const std::string &string) const;
int get_padding(bool encryption) const;
};
}
}
}
| true |
e7d54a6d154c9da6c30710fe129576e5cd9abc78 | C++ | KKyang/Image-Processing | /libsources/sharememory.cpp | UTF-8 | 2,512 | 2.796875 | 3 | [] | no_license | #include "sharememory.h"
shareMemory::shareMemory()
{
}
bool shareMemory::addToSharedMemory(cv::Mat &img)
{
if(img.empty())
return false;
if (sharedMemory.isAttached())
sharedMemory.detach();
cv::Mat tmp;
if(img.type() == CV_8UC1)
{
myCV::myCvtColor(img, tmp, myCV::GRAY2GBR);
}
else
{
tmp = img.clone();
}
QImage image = QImage(tmp.data, tmp.cols, tmp.rows, tmp.step, QImage::Format_RGB888);
QBuffer buffer;
buffer.open(QBuffer::WriteOnly);
QDataStream out(&buffer);
out << image;
int size = buffer.size();
sharedMemory.setKey("0");
if (!sharedMemory.create(size)) {
std::cout << "Unable to create shared memory segment." << std::endl;
return false;
}
sharedMemory.lock();
char *to = (char*)sharedMemory.data();
const char *from = buffer.data().data();
memcpy(to, from, qMin(sharedMemory.size(), size));
sharedMemory.unlock();
return true;
}
bool shareMemory::readFromSharedMemory(cv::Mat &img, const int imageType)
{
sharedMemory.setKey("0");
if (!sharedMemory.attach()) {
std::cout << "Unable to attach to shared memory segment." <<std::endl;
//ui.label->setText(tr("Unable to attach to shared memory segment.\n" \
// "Load an image first."));
return false;
}
QBuffer buffer;
QDataStream in(&buffer);
QImage image;
sharedMemory.lock();
buffer.setData((char*)sharedMemory.constData(), sharedMemory.size());
buffer.open(QBuffer::ReadOnly);
in >> image;
sharedMemory.unlock();
sharedMemory.detach();
image = image.rgbSwapped();
cv::Mat temp(image.height(), image.width(), CV_8UC4, image.bits(), image.bytesPerLine());
img.release();
img = cv::Mat(image.height(), image.width(), imageType).clone();
if(imageType == CV_8UC3)
for(int j = 0; j < img.rows; j++)
{
for(int i = 0; i < img.cols; i++)
{
for(int k = 0; k < 3; k++)
img.at<cv::Vec3b>(j,i)[k] = temp.at<cv::Vec4b>(j,i)[k];
}
}
else if(imageType == CV_8UC1)
{
for(int j = 0; j < img.rows; j++)
{
for(int i = 0; i < img.cols; i++)
{
img.at<uchar>(j,i) = temp.at<cv::Vec4b>(j,i)[0];
}
}
}
}
void shareMemory::requestDetach()
{
if(sharedMemory.isAttached())
sharedMemory.detach();
}
| true |
5a093775417affc3dd405614dba6eb915e8d8d23 | C++ | ansharpless90/C-Exercises | /Program1.2.cpp | UTF-8 | 267 | 2.796875 | 3 | [] | no_license | //Author Adrian Sharpless
//Last modification date: 5/4/2017
//Program outputs two lines of text
#include<iosstream>
using namespace std;
int main()
{
cout << " Computers, computers everywhere";
cout << " \n as far as I can C"; // /n sets output to a new line
return 0;
}
| true |
796d70c1dee872c5592fbbe7ba9c31e7090aedcb | C++ | KristiyanGergov/DataStructuresAndAlgorithms | /Week 02 - Sorting Algorithms/SortingAlgorithms/SortingAlgorithms/main.cpp | UTF-8 | 2,395 | 3.640625 | 4 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
void print(int* arr, int len) {
cout << "[";
for (int i = 0; i < len; i++)
{
if (i == len - 1)
{
cout << " " << arr[i] << " ]" << endl;
break;
}
cout << " " << arr[i] << ",";
}
}
// Bubble
void bubbleSort(int* arr, int len) {
for (int i = 0; i < len; i++)
{
bool flag = false;
for (int j = 0; j < len - i - 1; j++)
{
int current = arr[j];
int next = arr[j + 1];
if (current > next)
{
swap(arr[j], arr[j + 1]);
flag = true;
}
}
if (!flag)
break;
}
}
// Bubble
//Selection
void selectionSort(int* arr, int len) {
for (int i = 0; i < len; i++)
{
int minIndex = i;
for (int j = i + 1; j < len; j++)
{
int current = arr[j];
int min = arr[minIndex];
if (current < min)
minIndex = j;
}
swap(arr[minIndex], arr[i]);
}
}
//Selection
//Insertion
void insertionSort(int* arr, int len) {
for (int i = 1; i < len; i++)
{
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
//Insertion
//Merge
void merge(int* arr, int l, int m, int r) {
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int* L = new int[n1];
int* R = new int[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
delete[] L;
delete[] R;
}
void mergeSort(int* arr, int l, int r) {
if (l < r)
{
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
//Merge
//Quick
int partition(int* arr, int low, int high) {
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j < high; j++)
{
if (arr[j] <= pivot)
{
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[high]);
return (i + 1);
}
void quicksort(int* arr, int low, int high) {
if (low < high)
{
int pi = partition(arr, low, high);
quicksort(arr, low, pi - 1);
quicksort(arr, pi + 1, high);
}
}
//Quick
int main() {
int arr[] = { 10, 30, 40, 50, 80, 90, 20 };
quicksort(arr, 0, 6);
print(arr, 6);
return 0;
} | true |
c4c6d280cf7faf909ecc8444388a403811519792 | C++ | ohlionel/codebase | /13307130195/assignment6/2.cpp | UTF-8 | 838 | 2.609375 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <cstdlib>
using namespace std;
int a[110000];
void msort(int i, int j)
{
int l = i, r = j, m = abs(a[(i+j)/2]);
while (i<=j)
{
while (abs(a[i]) < m) i++;
while (abs(a[j]) > m) j--;
if (i <= j)
{
swap(a[i], a[j]);
i++;
j--;
}
}
if (i < r) msort(i,r);
if (j > l) msort(l,j);
}
int main()
{
// freopen("a.in", "r", stdin);
int n, t;
cin >> t>> n;
for (int i = 0; i < n; i++) cin>>a[i];
msort(0, n-1);
int ans = 0, pre = 0, p = 0;
while (t > 0)
{
if (t < abs(a[p] - pre)) break;
t-= abs(a[p] - pre);
ans++;
pre = a[p++];
}
cout<<ans<<endl;
} | true |
68286ec7a0c8194f4d383a7dce9f03d8ee569bd1 | C++ | CPSC-4377-UALR/CPSC.4377.Code.Examples | /L03.3.TinyXMLDemoAdvanced/main.cpp | UTF-8 | 5,976 | 2.78125 | 3 | [] | no_license | /*
* Example code taken from: http://www.grinninglizard.com/tinyxmldocs/tutorial0.html
*/
#include "tinyxml2.h"
#include <list>
#include <string>
#include <map>
using namespace std;
typedef std::map<std::string,std::string> MessageMap;
// a basic window abstraction - demo purposes only
class WindowSettings{
public:
int x,y,w,h;
string name;
WindowSettings(): x(0), y(0), w(100), h(100), name("Untitled"){}
WindowSettings(int x, int y, int w, int h, const string& name){
this->x=x;
this->y=y;
this->w=w;
this->h=h;
this->name=name;
}
};
class ConnectionSettings{
public:
string ip;
double timeout;
};
class AppSettings{
public:
string m_name;
MessageMap m_messages;
list<WindowSettings> m_windows;
ConnectionSettings m_connection;
AppSettings() {}
void save(const char* pFilename);
void load(const char* pFilename);
// just to show how to do it
void setDemoValues()
{
m_name="MyApp";
m_messages.clear();
m_messages["Welcome"]="Welcome to "+m_name;
m_messages["Farewell"]="Thank you for using "+m_name;
m_windows.clear();
m_windows.push_back(WindowSettings(15,15,400,250,"Main"));
m_connection.ip="Unknown";
m_connection.timeout=123.456;
}
};
int main(void){
// block: customise and save settings
{
AppSettings settings;
settings.m_name="HitchHikerApp";
settings.m_messages["Welcome"]="Don't Panic";
settings.m_messages["Farewell"]="Thanks for all the fish";
settings.m_windows.push_back(WindowSettings(15,25,300,250,"BookFrame"));
settings.m_windows.push_back(WindowSettings(-15,225,111,7,"OtherFrame"));
settings.m_connection.ip="192.168.0.77";
settings.m_connection.timeout=42.0;
settings.save("appsettings2.xml");
}
// block: load settings
{
AppSettings settings;
settings.load("appsettings2.xml");
printf("%s: %s\n", settings.m_name.c_str(), settings.m_messages["Welcome"].c_str());
WindowSettings & w=settings.m_windows.front();
printf("%s: Show window '%s' at %d,%d (%d x %d)\n",
settings.m_name.c_str(), w.name.c_str(), w.x, w.y, w.w, w.h);
printf("%s: %s\n", settings.m_name.c_str(), settings.m_messages["Farewell"].c_str());
}
system("PAUSE");
}
void AppSettings::save(const char* pFilename)
{
tinyxml2::XMLDocument doc;
tinyxml2::XMLElement* msg;
tinyxml2::XMLComment * comment;
string s;
doc.InsertFirstChild(doc.NewDeclaration());
tinyxml2::XMLElement * root = doc.NewElement(m_name.c_str());
doc.InsertEndChild( root );
s = " Settings for " + m_name + " ";
comment = doc.NewComment(s.c_str());
root->LinkEndChild( comment );
// block: messages
{
MessageMap::iterator iter;
tinyxml2::XMLElement * msgs = doc.NewElement( "Messages" );
root->LinkEndChild( msgs );
for (iter=m_messages.begin(); iter != m_messages.end(); iter++)
{
const string & key=(*iter).first;
const string & value=(*iter).second;
msg = doc.NewElement(key.c_str());
msg->LinkEndChild( doc.NewText(value.c_str()));
msgs->LinkEndChild( msg );
}
}
// block: windows
{
tinyxml2::XMLElement * windowsNode = doc.NewElement( "Windows" );
root->LinkEndChild( windowsNode );
list<WindowSettings>::iterator iter;
for (iter=m_windows.begin(); iter != m_windows.end(); iter++)
{
const WindowSettings& w=*iter;
tinyxml2::XMLElement * window;
window = doc.NewElement("Window" );
windowsNode->LinkEndChild( window );
window->SetAttribute("name", w.name.c_str());
window->SetAttribute("x", w.x);
window->SetAttribute("y", w.y);
window->SetAttribute("w", w.w);
window->SetAttribute("h", w.h);
}
}
// block: connection
{
tinyxml2::XMLElement * cxn = doc.NewElement( "Connection" );
root->LinkEndChild( cxn );
cxn->SetAttribute("ip", m_connection.ip.c_str());
cxn->SetAttribute("timeout", m_connection.timeout);
}
doc.SaveFile(pFilename);
}
//Running this with the modified main produces this file:
//
//<?xml version="1.0" ?>
//<HitchHikerApp>
// <!-- Settings for HitchHikerApp -->
// <Messages>
// <Farewell>Thanks for all the fish</Farewell>
// <Welcome>Don't Panic</Welcome>
// </Messages>
// <Windows>
// <Window name="BookFrame" x="15" y="25" w="300" h="250" />
// </Windows>
// <Connection ip="192.168.0.77" timeout="42.000000" />
//</HitchHikerApp>
void AppSettings::load(const char* pFilename)
{
tinyxml2::XMLDocument doc;
if (doc.LoadFile(pFilename) != tinyxml2::XML_SUCCESS)
{
printf("Bad File Path");
exit(1);
}
tinyxml2::XMLHandle hDoc(&doc);
tinyxml2::XMLElement* pElem;
tinyxml2::XMLHandle hRoot(0);
// block: name
{
pElem=hDoc.FirstChildElement().ToElement();
// should always have a valid root but handle gracefully if it does
if (!pElem) return;
m_name=pElem->Value();
// save this for later
hRoot=tinyxml2::XMLHandle(pElem);
}
// block: string table
{
m_messages.clear(); // trash existing table
pElem=hRoot.FirstChild().FirstChild().ToElement();
for( pElem; pElem; pElem=pElem->NextSiblingElement())
{
const char *pKey=pElem->Value();
const char *pText=pElem->GetText();
if (pKey && pText)
{
m_messages[pKey]=pText;
}
}
}
// block: windows
{
m_windows.clear(); // trash existing list
tinyxml2::XMLElement* pWindowNode=hRoot.FirstChild( ).FirstChild().ToElement();
for( pWindowNode; pWindowNode; pWindowNode=pWindowNode->NextSiblingElement())
{
WindowSettings w;
const char *pName=pWindowNode->Attribute("name");
if (pName) w.name=pName;
pWindowNode->QueryIntAttribute("x", &w.x); // If this fails, original value is left as-is
pWindowNode->QueryIntAttribute("y", &w.y);
pWindowNode->QueryIntAttribute("w", &w.w);
pWindowNode->QueryIntAttribute("hh", &w.h);
m_windows.push_back(w);
}
}
// block: connection
{
pElem=hRoot.FirstChild().ToElement();
if (pElem)
{
m_connection.ip=pElem->Attribute("ip");
pElem->QueryDoubleAttribute("timeout",&m_connection.timeout);
}
}
}
| true |
09e55765cdc385ea4f9ba2c86db81d694551e42b | C++ | layshua/Shock-or-Entropy-Interaction | /main.cpp | UTF-8 | 1,186 | 2.53125 | 3 | [] | no_license | /**
* main.cpp
* the main procedure to use c++ get the data and use matlab to plot the image
* Shock/Entropy Wave Interaction
*
* Created by David Wang on 16/11/5.
*
*/
#include "solver.hpp"
int main(int argc, const char * argv[]) {
solver solver;
// 对比有无MUSCL Limiter
solver.setLimiter(0);
solver.solve();
solver.output("nonMuscl.txt");
solver.setLimiter(1);
solver.solve();
solver.output("hasMuscl.txt");
// 对比Kappa值
solver.setKappa(-1.0);
solver.solve();
solver.output("kappa-1.txt");
solver.setKappa(0.0);
solver.solve();
solver.output("kappa0.txt");
solver.setKappa(1.0/3.0);
solver.solve();
solver.output("kappa13.txt");
solver.setKappa(1.0);
solver.solve();
solver.output("kappa1.txt");
// 对比Limiter类型
solver.setLimiter(1);
solver.solve();
solver.output("vanLeer.txt");
solver.setLimiter(2);
solver.solve();
solver.output("vanAlbada.txt");
solver.setLimiter(3);
solver.solve();
solver.output("minmod.txt");
solver.setLimiter(4);
solver.solve();
solver.output("superbee.txt");
return 0;
}
| true |
3e0590b8369be1099a10bfa7192b0c4fd862371a | C++ | Kawser-nerd/CLCDSA | /Source Codes/CodeJamData/08/72/3.cc | UTF-8 | 1,245 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int mod(int a) {
a %= 10007;
if (a < 0) a += 10007;
return a;
}
int main()
{
int tests;
cin >> tests;
for (int test = 1; test <= tests; ++test) {
int n;
cin >> n;
vector<int> v(n);
for (int i = 0; i < n; ++i)
cin >> v[i];
while (v.size() > 2) {
bool a0 = true, a1 = true;
for (int i = 2; i + 1 < v.size(); i += 2)
a0 = a0 && mod(v[i+1] - v[i]) == mod(v[1] - v[0]);
for (int i = 3; i + 1 < v.size(); i += 2)
a1 = a1 && mod(v[i+1] - v[i]) == mod(v[2] - v[1]);
vector<int> w;
if (a0 && a1) {
break;
} else if (a0) {
if (v.size() % 2 == 1) {
cout << "Case #" << test << ": " << mod(v[v.size() - 1] + v[1] - v[0]) << endl;
goto next;
}
for (int i = 0; i < v.size(); i += 2)
w.push_back(v[i]);
} else if (a1) {
if (v.size() % 2 == 0) {
cout << "Case #" << test << ": " << mod(v[v.size() - 1] + v[2] - v[1]) << endl;
goto next;
}
for (int i = 1; i < v.size(); i += 2)
w.push_back(v[i]);
} else {
cout << "Case #" << test << ": " << "IMPOSSIBLE!" << endl;
goto next;
}
v.swap(w);
}
cout << "Case #" << test << ": " << "UNKNOWN" << endl;
next:
;
}
}
| true |
bb1a52269687bd55108f8285c62bb27f6631b29a | C++ | swapnilhota/interviewBit | /DP/Best Time to Buy and Sell Stocks I.cpp | UTF-8 | 577 | 3.578125 | 4 | [] | no_license | /*
Problem Description
Say you have an array, A, for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Return the maximum possible profit.
*/
int Solution::maxProfit(const vector<int> &A) {
int ans = 0;
if(A.size()==0) return ans;
int minTerm = A[0];
for(int i=1; i<A.size(); i++)
{
ans = max(ans, A[i]-minTerm);
minTerm = min(minTerm, A[i]);
}
return ans;
}
| true |
c71123776651b85cc9bf96bb45b3d5621852eb2e | C++ | MarkBennett12/OpenGL-River_Valley | /RiverValley/RiverValley/DiamondSquare.cpp | UTF-8 | 6,351 | 3.34375 | 3 | [] | no_license | /*
* DiamondSquare.cpp
*
* Implements the diamond square algorithm for procedural terrain generation.
* Created on: 30 Nov 2013
* Author: Mark Bennett
*/
#include <iostream>
#include "DiamondSquare.h"
namespace Generators
{
/*
Constructs the DiamondSquare object and provied the mesh and parameters for the algorithm
Display::TerrainMesh* mesh : The mesh to be built
Parameters* params : Parameters to control the algorithm
int size : The size of each side of the mesh
*/
DiamondSquare::DiamondSquare(Geometry::TerrainMesh* mesh, Parameters* params, int size):
normalDistribution(0.0, 1.0),
generator(rng, normalDistribution)
{
// TODO Auto-generated constructor stub
terrainSize = size;
this->params = params;
this->mesh = mesh;
}
DiamondSquare::~DiamondSquare()
{
// TODO Auto-generated destructor stub
}
/*
Initialise the algorithm by creating the mesh at baseheight and raising the four corners of the mesh by a random amount
*/
void DiamondSquare::Init()
{
// Generate the terrain mesh at the set size and at the base height
for(int i = 0; i < terrainSize; i++)
{
for(int j = 0; j < terrainSize; j++)
mesh->AddQuad((GLfloat)j, params->baseHeight, (GLfloat)i, (GLfloat)j + 1, params->baseHeight, (GLfloat)i, (GLfloat)j + 1, params->baseHeight, (GLfloat)i + 1, (GLfloat)j, params->baseHeight, (GLfloat)i + 1);
}
// Lift each corner by a random amount
// As this is the first step we don't modify the random number generated, hence 1.0 being passed to the Displace method
mesh->SetHeightAt((GLfloat)0, (GLfloat)0, (GLfloat)fabs(Displace(1.0)));
mesh->SetHeightAt((GLfloat)terrainSize, (GLfloat)0, (GLfloat)fabs(Displace(1.0)));
mesh->SetHeightAt((GLfloat)terrainSize, (GLfloat)terrainSize, (GLfloat)fabs(Displace(1.0)));
mesh->SetHeightAt((GLfloat)0, (GLfloat)terrainSize, (GLfloat)fabs(Displace(1.0)));
}
/*
Generate a random number offset from the base height and modified by the roughness parameter
This is used to control the random amount as the interations proceed
The function uses the Boost library random generator to get a standard distribution
of random numbers
parameter: double modifier - modulate the random number by multiplying it by this value
return: A random number with a standard distribution offset from the base height of modulated by the modifier parameter
*/
double DiamondSquare::Displace(double modifier)
{
return (generator() + params->baseHeight + 1.0) * modifier;
}
/*
The square step gets the hieght of each corner of the mesh, calculates the average of those heights
and uses that average to add an offset to the random number generated. The random value is used to lift the
centre point of each side of the square
int x : the left corner of the square to process
int z: the 'top' - far corner of the square to process
int size: The size of the square to process
double roughness: scale the amount of random change
*/
void DiamondSquare::SquareStep(int x, int z, int size, double roughness)
{
int midpoint = size / 2;
GLfloat averageHeight = 0.0;
// Get the average height of the endpoints of the left side of the square
averageHeight = mesh->GetHeightAt((GLfloat)x, (GLfloat)z);
averageHeight += mesh->GetHeightAt((GLfloat)x + size, (GLfloat)z);
averageHeight /= 2;
// Set a new random height to the midpoint of the square side based on the average and roughness parameter
mesh->SetHeightAt((GLfloat)x, (GLfloat)midpoint, (GLfloat)Displace(roughness) + averageHeight);
// The same for the top (far) side of the square
averageHeight = mesh->GetHeightAt((GLfloat)x + size, (GLfloat)z);
averageHeight += mesh->GetHeightAt((GLfloat)x + size, (GLfloat)z + size);
averageHeight /= 2;
mesh->SetHeightAt((GLfloat)x + size, (GLfloat)z + midpoint, (GLfloat)Displace(roughness) + averageHeight);
// The same for the right side of the square
averageHeight = mesh->GetHeightAt((GLfloat)x + size, (GLfloat)z + size);
averageHeight += mesh->GetHeightAt((GLfloat)x, (GLfloat)z + size);
averageHeight /= 2;
mesh->SetHeightAt((GLfloat)x + midpoint, (GLfloat)z + size, (GLfloat)Displace(roughness) + averageHeight);
// The same for the bottom (near) side of the square
averageHeight = mesh->GetHeightAt((GLfloat)x, (GLfloat)z + size);
averageHeight += mesh->GetHeightAt((GLfloat)x, (GLfloat)z);
averageHeight /= 2;
mesh->SetHeightAt((GLfloat)x, (GLfloat)z + midpoint, (GLfloat)Displace(roughness) + averageHeight);
}
/*
The diamond step takes the midpoint of each side of the square and uses the average height of the points to calculate
a new random height for the centre of the square
int x : the left corner of the square to process
int z: the 'top' - far corner of the square to process
int size: The size of the square to process
double roughness: scale the amount of random change
*/
void DiamondSquare::DiamondStep(int x, int z, int size, double roughness)
{
int midpoint = size / 2;
GLfloat averageHeight = 0.0;
// Get the average hieght of the midpoints of each side of the square
averageHeight = mesh->GetHeightAt((GLfloat)x, (GLfloat)z);
averageHeight += mesh->GetHeightAt((GLfloat)x + size, (GLfloat)z);
averageHeight += mesh->GetHeightAt((GLfloat)x + size, (GLfloat)z + size);
averageHeight += mesh->GetHeightAt((GLfloat)x, (GLfloat)z + size);
averageHeight /= 4;
// Lift the centre point of the square by a random amount based on the average height and the roughness parameter
mesh->SetHeightAt((GLfloat)midpoint, (GLfloat)midpoint, (GLfloat)Displace(roughness) + averageHeight);
}
/*
Iterates through the terrain mesh applying the diamond sqare algorithm until all the squares have been
processed
*/
void DiamondSquare::Generate()
{
int stepSize = (int)terrainSize;
// Starting with the whole mesh, apply the diamond square then cut the mesh in half and repeat
// until there are no more subsquares to process
while(stepSize > 0)
{
// Apply diamond square algorithm to each sub sqaure
for(int i = 0; i < terrainSize; i += stepSize)
{
for(int j = 0; j < terrainSize; j += stepSize)
{
DiamondStep(i, j, stepSize, params->roughness);
SquareStep(i, j, stepSize, params->roughness);
}
}
// Reduce the amount of roughness as the sqaures get smaller to prevent very spiky terrain
params->roughness *= params->roughnessDecrement;
// cut the mesh in half
stepSize /= 2;
}
}
} /* namespace Generators */
| true |
71c56dfc5b83deb7f9fa78ea1fc94998b3f07a96 | C++ | ron-kap/university-projects | /C++/Assignment1/Item.h | UTF-8 | 1,446 | 3.390625 | 3 | [] | no_license | #ifndef ITEM_H
#define ITEM_H
#include <iostream>
using std::ostream;
using std::ostream;
using std::cout;
#include <string>
using std::string;
#include <cmath>
using std::pow;
using std::cos;
using std::sin;
using std::atan2;
// TODO: your code goes here
class Item {
protected:
double latitude;
double longitude;
string ID;
int time;
public:
Item(double latitudeC, double longitudeC, string IDC, int timeC) : latitude(latitudeC), longitude(longitudeC), ID(IDC), time(timeC) {
}
// getters
double getLat() {
return latitude;
}
double getLon() {
return longitude;
}
string getID() {
return ID;
}
int getTime() {
return time;
}
double distanceTo(Item item2) {
double pi = 3.1415926535897; // could have used M_PI
longitude = (longitude * pi) / 180;
latitude = (latitude * pi) / 180;
item2.longitude = (item2.longitude * pi) / 180;
item2.latitude = (item2.latitude * pi) / 180;
double dlon = item2.longitude - longitude;
double dlat = item2.latitude - latitude;
double a = pow((sin(dlat / 2)), 2) + cos(latitude) * cos(item2.latitude) * pow((sin(dlon / 2)), 2);
double c = 2 * atan2(sqrt(a), sqrt(1 - a));
double distance = 6373000 * c;
return distance;
}
};
ostream& operator<<(ostream& os, Item& item) {
os << "{" << item.getLat() << ", " << item.getLon() << ", \"" << item.getID() << "\", " << item.getTime() << "}";
return os;
}
// don't write any code below this line
#endif
| true |