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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
650997f919e507d4e030362e35977fe9f2190f59 | C++ | adarshkumar8225/practice_c- | /remove_loop.cpp | UTF-8 | 1,985 | 3.734375 | 4 | [] | no_license | //removal of loop present in linked list in O(N) complexity.........................
//detect loop using two pointer one incremented by one position and other by two position
//count the number of nodes in the loop by keeping one pointer at meeting point and other incrementing
//now take a pointer pointing to node and other point to s node ahead where s = no of nodes in loop
//increment both pointer parallely they will meet at junction
// now move the pointer s node ahead and put NULL now the loop is removed
//**********************************************************************************************************
void removeLoop(Node* head)
{
// code here
// just remove the loop without losing any nodes
Node *trav1,*trav2;
trav1=head;
trav2=head;
int flag=0,count=1;
//way to detect loop using two pointer.............
while(trav2!=NULL && trav2->next!=NULL)
{
trav1=trav1->next;
trav2=trav2->next->next;
if(trav1==trav2)
{
flag=1;
break;
}
}
//loop is present in the linked list*************************
if(flag==1)
{
trav1=trav1->next;
//count number of elements in the loop...............
while(trav1!=trav2)
{
trav1=trav1->next;
count++;
}
//set both pointer pointing to head......
trav1=head;
trav2=head;
int c=count;
//make trav2 to point count position ahead..........
while(count)
{
trav2=trav2->next;
count--;
}
//now find intersection point of both pointer it will meet at junction
while(trav1!=trav2)
{
trav1=trav1->next;
trav2=trav2->next;
}
//move count position ahead and insert NULL to remove the loop
while(c>1)
{
trav1=trav1->next;
c--;
}
trav1->next=NULL;
}
}
| true |
d9f663882f144c465d74342686d8ebeb46a70552 | C++ | chen8913w/my-acm-solutions | /algo/sort/quicksort.hpp | UTF-8 | 3,101 | 3.5625 | 4 | [] | no_license | /**
* QuickSort
*
* Divide:
* Partition (rearrange) the array A[p..r] into two (possibly empty)
* subarrays A[p..q-1] and A[q+1..r] such that each element of A[p..q-1]
* is less than or equal to A[q] which is, in turn, less than or equal to
* each elemen of A[q+1..r]. Compute the index q as part of this partitioning
* procedure.
* Conquer:
* Sort the two subarrays A[p..q-1] and A[q+1..r] by recursive calls to quicksort.
*
* QUICKSORT(A, p r)
* if p < r
* q = PARTITION(A, p, r)
* QUICKSORT(A, p, q - 1)
* QUICKSORT(A, p + 1, q)
*
* PARTITION(A, p, r)
* x = A[r]
* i = p-1
* for j from i to r-1
* if A[j] <= x
* i= i + 1
* swap(A[i], A[j)
* swap(A[i+1], A[r])
* return i + 1
*
*/
template<typename T>
inline void swap(T& lhs, T& rhs) {
T tmp = lhs;
lhs = rhs;
rhs = tmp;
}
template<typename T, typename Compare>
inline const T& median(const T& a, const T& b, const T& c, Compare compare) {
if (compare(a, b)) {
if (compare(b, c)) {
return b;
} else if (compare(a, c)) {
return c;
} else {
return a;
}
} else if (compare(a, c)) {
return a;
} else if (compare(b, c)) {
return c;
} else {
return b;
}
}
/**
* PARTITION(A, p, r)
* x = A[r]
* i = p-1
* for j from i to r-1
* if A[j] <= x
* i= i + 1
* swap(A[i], A[j)
* swap(A[i+1], A[r])
* return i + 1
*/
template<typename RandomIterator, typename T, typename Compare>
RandomIterator unguarded_partition(RandomIterator first, RandomIterator last,
T& pivot, Compare compare) {
for (;;) {
for (; compare(*first, pivot); ++first)
;
for (--last; compare(pivot, *last); --last)
;
if (!(first < last)) {
return first;
}
swap(*first, *last);
++first;
}
}
// the maximum depth of recursion if possible
inline int log(int n) {
int k;
for (k = 0; n > 1; n >>= 1) {
++k;
}
return k;
}
// an auxilary function for sort
template<typename RandomIterator, typename Compare>
void introsort_loop(RandomIterator first, RandomIterator last, int depth_limit,
Compare compare) {
while (last - first > 16) {
if (0 == depth_limit) {
partial_sort(first, last, last, compare);
return;
}
--depth_limit;
RandomIterator cut = unguarded_partition(first, last,
median(*first, *(first + ((last - first) >> 1)), *(last - 1),
compare), compare);
introsort_loop(cut, last, depth_limit, compare);
last = cut;
}
}
// quick sort -- SGI STL version
template<typename RandomIterator, typename Compare>
inline void sort(RandomIterator first, RandomIterator last, Compare compare) {
if (last - first > 16) {
introsort_loop(first, last, log(static_cast<int>(last - first)) << 1,
compare);
}
final_insertion_sort(first, last, compare);
}
| true |
e9c440dcdef5487ba9f628b7900d52b08ec98de5 | C++ | davidad/kokompe-old | /engine/gui_console.h | UTF-8 | 1,265 | 2.75 | 3 | [] | no_license | #pragma once
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
#include <list>
class gui_console
{
private:
std::vector< std::string > screen_buffer;
std::string command_buffer;
int cursor_position;
std::vector< std::string > command_history;
int command_history_index;
int display_start;
int scroll_offset;
int w, h;
bool is_hidden;
bool is_active;
int current_raster_line;
const std::string prompt;
void render_text_line(const std::string& line);
public:
gui_console();
~gui_console();
bool get_is_hidden();
void set_is_hidden(bool new_val);
bool get_is_active();
void set_is_active(bool new_val);
void set_dimensions(int w, int h);
void render();
void handle_key(char key);
void print(unsigned char c);
void print(const std::string& str);
void scroll(int rows);
void scroll_abs(int row);
void last_command();
void next_command();
void cursor_left();
void cursor_right();
void cursor_home();
void cursor_end();
template<typename T> gui_console& operator<<(const T& t)
{
std::stringstream text;
std::cerr << t;
std::cerr.flush();
text << t;
print(text.str());
return (*this);
}
};
| true |
9d972596e8dffcf4db42ad149eb2b748978d4d41 | C++ | schick/TrafficSim | /scenario_ref/include/model/Lane.h | UTF-8 | 1,228 | 2.96875 | 3 | [] | no_license | //
// Created by oke on 07.12.18.
//
#ifndef PROJECT_LANE_H
#define PROJECT_LANE_H
#include <vector>
#include <inttypes.h>
#include <iostream>
#include <algorithm>
#include <mutex>
#include "TrafficLight.h"
class Car;
class Road;
class Lane {
public:
void sortCars();
std::vector<Car *> const &getCars() const {
return mCars;
}
/**
* stores neighboring objects on a lane based on a given position on lane.
*/
struct NeighboringObjects {
NeighboringObjects() : front(nullptr), back(nullptr) {};
TrafficObject *front = nullptr;
Car *back = nullptr;
};
Lane(int lane, Road &road, double length) : lane(lane), road(road), mCars(), length(length), trafficLight(this) {}
/**
* Copy Constructor
*/
Lane(const Lane &source): road(source.road), lane(0), length(0), trafficLight(source.trafficLight) {}
Lane::NeighboringObjects getNeighboringObjects(Car *trafficObject);
/**
* properties
*/
int lane;
Road &road;
double length;
TrafficLight trafficLight;
private:
friend class Car;
std::mutex laneLock;
std::vector<Car *> mCars;
bool isSorted = false;
};
#endif //PROJECT_LANE_H
| true |
6b957ad35a1a37196fd7126825cb02fb75736632 | C++ | NGPONG/code | /cpp/CPP-Study-01/TEST/TEST_14/main.cpp | UTF-8 | 1,378 | 3.515625 | 4 | [] | no_license | #include <iostream>
using namespace std;
#include <string.h>
class BASE {
friend ostream &operator<<(ostream &out, BASE _base) {
for (size_t i = 0; i < _base.m_capacity; i++) {
cout << _base.m_container[i] << "\t";
}
return out;
};
public:
BASE(int _capactiy) {
cout << "BASE CONSTRUCTOR" << endl;
this->m_container = new int[_capactiy];
this->m_capacity = _capactiy;
_init();
};
BASE(const BASE &_base) {
cout << "BASE COPY CONSTRUCTOR" << endl;
this->m_capacity = _base.m_capacity;
this->m_container = new int[this->m_capacity];
memcpy(this->m_container, _base.m_container, sizeof(int) * _base.m_capacity); /* copy data */
}
~BASE() {
if (this->m_container) {
delete[] this->m_container;
}
cout << "DESTRUCTOR:" << this << endl;
}
public:
int &operator[](int _index) {
return this->m_container[_index];
};
private:
void _init(void) {
if (this->m_container == nullptr) { return; }
for (size_t i = 0; i < this->m_capacity; i++) {
this->m_container[i] = i + 1;
}
}
private:
int *m_container;
size_t m_capacity;
};
void operator+(BASE _base,int _plus) {
cout << _base << endl;
cout << "OK!" << endl;
}
int main(void) {
BASE base(10);
cout << base << endl;
cout << base[8] << endl;
base + 1;
system("pause");
return EXIT_SUCCESS;
} | true |
ef4d0b83391099acde9d2325804ce5f4303166c4 | C++ | liyupi/poj | /easy/3672.cpp | UTF-8 | 784 | 2.515625 | 3 | [] | no_license | // http://poj.org/problem?id=3672
#include <iostream>
using namespace std;
const int MAXN = 100001;
int M, T, U, F, D;
char c[MAXN];
int main() {
while (~scanf("%d%d%d%d%d", &M, &T, &U, &F, &D)) {
int res = 0;
int sum = 0;
for (int i = 0; i < T; ++i) {
scanf("\n%c", &c[i]);
}
for (int i = 0; i < T; ++i) {
switch (c[i]) {
case 'u':
sum += U + D;
break;
case 'f':
sum += 2 * F;
break;
default:
sum += U + D;
}
if (sum > M) {
break;
}
res++;
}
printf("%d\n", res);
}
return 0;
} | true |
a8ab67b9662aec94c6e59662a975d8c93e139991 | C++ | king1224/Cheng_Kung_University | /data_structure/hw/hw3/資結Hw3_1.cpp | BIG5 | 1,834 | 3.15625 | 3 | [] | no_license | #include <stdio.h>
#include <math.h>
int main()
{
int i,j,n,k,pos=1,rec=0,temp=0,count_word=1,opr[100]={0};
//oprϤBl B⤸ count_wordΨxs@XչB⤸+Bl
//recΨӼȦsUչB⤸ tempΨxsչB⤸Xb@_ɪ
//posbBɹm
int a[100]={0}; //sinput
int b[100]={0}; //BȦs
printf("Please input a prefix expression.\n");
i=1;
do{ //rJ0
a[0]=getchar()-'0';
if(0<=a[0]&&a[0]<=9) //Ʀr@Ӧs@s
{
a[i]=a[0];
i++;
rec++;
}
else if(a[0]==-16) //YJŮ NŮe@ռƦrsP@
{
for(j=i-1;j>=i-rec;j--)
{
n=rec-j+count_word-1;
temp=temp+a[j]*pow(10,n); //pӦ Q ʦ....
}
count_word++;
i=count_word;
a[j+1]=temp;
rec=0;
temp=0;
}
else if(a[0]!=-38) //ƦrΪŮH~ SD YBl s
{
a[i]=a[0]+'0';
opr[i]++; //欰Bl
i++;
}
else
{
for(j=i-1;j>=i-rec;j--)
{ n=rec-j+count_word-1;
temp=temp+a[j]*pow(10,n);
}
a[j+1]=temp;
}
}while(a[0] != (10-48));
for(i=count_word;i>=1;i--)
{
if(opr[i]==0) //opr==0NOB⤸
{
b[pos]=a[i];
pos++;
}
else //BlB
{
switch(a[i])
{
case '+':
b[pos-2]=b[pos-1]+b[pos-2];
pos=pos-1;
break;
case '-':
b[pos-2]=b[pos-1]-b[pos-2];
pos=pos-1;
break;
case '*':
b[pos-2]=b[pos-1]*b[pos-2];
pos=pos-1;
break;
case '/':
b[pos-2]=b[pos-1]/b[pos-2];
pos=pos-1;
break;
case '%':
b[pos-2]=b[pos-1]%b[pos-2];
pos=pos-1;
break;
}
}
}
printf("answer=%d ",b[1]); //צsbb[1]
return 0;
}
| true |
d5547ba2908ca1d73d05729728d3bd7b84abe67a | C++ | GABRIELMUTTI/utl | /include/utl/memory/Handle.hpp | UTF-8 | 789 | 3.0625 | 3 | [] | no_license | #pragma once
#include "IPool.hpp"
namespace utl
{
using uint = unsigned int;
template<class T>
class Handle
{
protected:
IPool<T>* pool;
uint index;
bool validity;
public:
Handle() :
pool(nullptr),
index(0),
validity(false)
{
}
Handle(IPool<T>& pool, uint index, bool validity) :
pool(&pool),
index(index),
validity(validity)
{
}
bool isValid() const
{
return validity;
}
inline bool operator ==(const Handle<T>& other) const
{
return (index == other.index) && (validity == other.validity);
}
inline bool operator >(const Handle<T>& other) const
{
return index > other.index;
}
inline bool operator <(const Handle<T>& other) const
{
return index < other.index;
}
};
}
| true |
5d6949bba07a4d361209bf1fdb14340fae09c567 | C++ | qsphan/the-omega-project | /basic/include/basic/Collection.h | UTF-8 | 1,315 | 3.09375 | 3 | [
"BSD-2-Clause"
] | permissive | #if !defined Already_Included_Collection
#define Already_Included_Collection
//#include <basic/enter_Iterator.h>
//#include <basic/enter_Collection.h>
namespace omega {
template<class T> class Iterator;
template<class T> class Any_Iterator;
/*
* protocol for any kind of collection
*/
template<class T> class Collection {
public:
Collection() {}
virtual ~Collection() {}
virtual Iterator<T> *new_iterator() = 0;
virtual Any_Iterator<T> any_iterator() { return Any_Iterator<T>(new_iterator()); }
virtual int size() const = 0;
};
/*
* protocol for collections whose elements are ordered
* by the way they are entered into the collection, and
* whose elements can be accessed by "index"
*
* note that the implementation need not be a linked list
*/
template<class T> class Sequence : public Collection<T> {
public:
Sequence() {}
virtual ~Sequence() {}
virtual const T &operator[](int) const = 0;
virtual T &operator[](int) = 0;
virtual int index(const T &) const = 0; // Y in X --> X[X.index(Y)] == Y
};
#define instantiate_Collection(T) template class Collection<T>; \
instantiate_Any_Iterator(T)
#define instantiate_Sequence(T) template class Sequence<T>; \
instantiate_Collection(T)
} // end of namespace omega
#endif
| true |
eaa67ab4976f15033016747ccd20a301cce40b65 | C++ | patentfox/PPPCpp | /ch6/ex2.cpp | UTF-8 | 3,302 | 3.5625 | 4 | [] | no_license | #include "std_lib_facilities.h"
class Token
{
public:
char kind;
double value; // only relevant if kind is '8'
Token() { }
Token (char ch): kind(ch) { }
Token (char ch, double val): kind(ch), value(val) { }
};
//-------------------------------------------------------
class Token_stream
{
public:
Token_stream();
Token get();
void putback(Token t);
private:
Token bufTok;
bool isFull;
};
Token_stream ts; // global
Token_stream::Token_stream()
{
isFull = false;
}
void Token_stream::putback(Token t)
{
//cout << "Putting back " << t.kind << endl;
if(isFull)
error("Trying to push more than 1 token to token_stream");
bufTok = t;
isFull = true;
}
Token Token_stream::get()
{
if(isFull)
{
isFull = false;
return bufTok;
}
char ch;
cin >> ch;
switch(ch)
{
case ';': case 'q':
case '+': case '-': case '*': case '/':
case '(': case ')': case '{': case '}':
return Token{ch};
case '.':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
{
cin.putback(ch);
double d;
cin >> d;
return Token{'8', d};
}
default:
error("Bad token, can't recognize");
}
cerr << "Should never reach here";
return Token();
}
//---------------------------------------------------------
double term();
double primary();
double expression()
{
double left = term();
Token t = ts.get(); // Token stream
while(true)
{
switch(t.kind)
{
case '+':
left += term();
t = ts.get();
break;
case '-':
left -= term();
t = ts.get();
break;
default:
ts.putback(t);
return left;
}
}
}
double term()
{
double left = primary();
Token t = ts.get();
while(true)
{
switch(t.kind)
{
case '*':
left *= primary();
t = ts.get();
break;
case '/':
{
double right = primary();
if(right == 0)
error("Division by 0 error");
left /= right;
t = ts.get();
}
break;
default:
ts.putback(t);
return left;
}
}
}
double primary()
{
Token t = ts.get();
if(t.kind == '(')
{
double val = expression();
t = ts.get();
if (t.kind != ')')
error ("Closing parenthesis expected, but not found");
return val;
}
else if(t.kind == '{')
{
double val = expression();
t = ts.get();
if(t.kind != '}')
error ("Closing brace expected, but not found");
return val;
}
else if (t.kind == '8')
return t.value;
error("Primary expected, but found something else");
// can never reach here
cerr << "Should never reach here" << endl;
return 0;
}
//----------------------------------------------------------
int main()
{
try
{
double result = 0;
while (cin)
{
Token t = ts.get();
//cout << "Token: " << t.kind << endl;
if(t.kind == 'q') {
break;
}
if(t.kind == ';') {
cout << "= " << result << endl;
continue;
}
ts.putback(t);
result = expression();
}
}
catch (exception &ex) {
cerr << ex.what() << endl;
return 1;
}
catch (...) {
cerr << "Some exception occurred" << endl;
return 2;
}
} | true |
0b812bf902c9044b1366c5ddb2ad71ed0fddf910 | C++ | Binyamin-Brion/L-System-Visualizer | /GUI/Output/L_System/ScriptOutputEntry.h | UTF-8 | 2,260 | 2.59375 | 3 | [] | no_license | //
// Created by binybrion on 5/8/20.
//
#ifndef VOXEL_L_SYSTEM_SCRIPTOUTPUTENTRY_H
#define VOXEL_L_SYSTEM_SCRIPTOUTPUTENTRY_H
#include <QtWidgets/QWidget>
namespace Ui
{
class ScriptOutputEntry;
}
namespace GUI
{
namespace Output
{
namespace L_System
{
/**
* Represents a depth result from executing a script.
*/
class ScriptOutputEntry : public QWidget
{
public:
/**
* Initializes the widget with the parent that has ownership over this object.
*
* @param parent that owns this object
*/
explicit ScriptOutputEntry(QWidget *parent = nullptr);
/**
* Appends the output for the depth that this entry represents to the visual output.
*
* @param text to append to the visual output
*/
void appendResultText(const QString &text);
/**
* Sets the depth that this entry represents.
*
* @param depthResult depth level being represented by this widget
*/
void setDepthResult(unsigned int depthResult);
/**
* Shows the error message the dedicated area for the error message for a given depth level.
*
* @param errorMessage for the depth level result this entry represents and display
*/
void setErrorMessage(const QString &errorMessage);
/**
* Shows or hides the error message associated with the output this entry displays depending on the input argument.
*
* @param visible true if the error message should be shown; false otherwise
*/
void showError(bool visible);
private:
Ui::ScriptOutputEntry *ui = nullptr;
};
}
}
}
#endif //VOXEL_L_SYSTEM_SCRIPTOUTPUTENTRY_H
| true |
fc05a7580dc2755286c4a69bae8cb30cc3851cc5 | C++ | tajirhas9/Problem-Solving-and-Programming-Practice | /Codeforces/867-A.cpp | UTF-8 | 547 | 2.8125 | 3 | [] | no_license | #include <bits/stdc++.h>
#include <cstring>
using namespace std;
int main()
{
int n,fromFransisco=0,fromSeatle=0;
char s[200],now;
scanf("%d %s",&n,s);
now = s[0];
for(int i=1;i<n;i++)
{
if(s[i] != now)
{
if(now == 'S')
{
fromSeatle++;
//cout << "Flew from Seatle on day " << i << endl;
now = 'F';
}
else
{
fromFransisco++;
//cout << "Flew from Fransisco on day " << i << endl;
now = 'S';
}
}
}
if(fromSeatle > fromFransisco) cout << "YES" << endl;
else cout << "NO" << endl;
return 0;
}
| true |
53910e70417d87fa896c89f634539fc159601b07 | C++ | DevMomo/Diffie-Hellman-Arduino | /Diffie_Helman.ino | UTF-8 | 5,202 | 3.0625 | 3 | [] | no_license | /* CMPUT 296/114 - Assignment 1 Part 2 - Due 2012-10-03
Version 1.2 2012-10-01
By: Monir Imamverdi
Michael Nicholson
This assignment has been done under the full collaboration model,
and any extra resources are cited in the code below.
Note on wiring:
grnd->grnd
digital 10 -> digital 11
digitall 11-> digital 10
tx1 -> rx1
rx1 -> tx1
Also, you may need to press the reset button once after opening the serial monitor in
order to sync the arduinos due to compilation speed inconsistencies between the two pcs.
*/
//public variable representing the shared secret key.
//note that a uint32_t size key is suceptable to brute force attacks, consider a different data type of at least 1024 bits
uint32_t k;
//prime number
const uint32_t prime = 2147483647;
//generator
const uint32_t generator = 16807;
//generates our 8 bit private secret 'a'.
uint32_t keyGen(){
//Seed the random number generator with a reading from an unconnected pin, I think this on analog pin 2
randomSeed(analogRead(2));
//return a random number between 1 and our prime .
return random(1,prime);
}
//code to compute the remainder of two numbers multiplied together.
uint32_t mul_mod(uint32_t a, uint32_t b, uint32_t m){
uint32_t result = 0; //variable to store the result
uint32_t runningCount = b % m; //holds the value of b*2^i
for(int i = 0 ; i < 32 ; i++){
if(i > 0) runningCount = (runningCount << 1) % m;
if(bitRead(a,i)){
result = (result%m + runningCount%m) % m;
}
}
return result;
}
//The pow_mod function to compute (b^e) % m that was given in the class files
uint32_t pow_mod(uint32_t b, uint32_t e, uint32_t m)
{
uint32_t r; // result of this function
uint32_t pow;
uint32_t e_i = e;
// current bit position being processed of e, not used except for debugging
uint8_t i;
// if b = 0 or m = 0 then result is always 0
if ( b == 0 || m == 0 ) {
return 0;
}
// if e = 0 then result is 1
if ( e == 0 ) {
return 1;
}
// reduce b mod m
b = b % m;
// initialize pow, it satisfies
// pow = (b ** (2 ** i)) % m
pow = b;
r = 1;
// stop the moment no bits left in e to be processed
while ( e_i ) {
// At this point pow = (b ** (2 ** i)) % m
// and we need to ensure that r = (b ** e_[i..0] ) % m
// is the current bit of e set?
if ( e_i & 1 ) {
// this will overflow if numbits(b) + numbits(pow) > 32
r= mul_mod(r,pow,m);//(r * pow) % m;
}
// now square and move to next bit of e
// this will overflow if 2 * numbits(pow) > 32
pow = mul_mod(pow,pow,m);//(pow * pow) % m;
e_i = e_i >> 1;
i++;
}
// at this point r = (b ** e) % m, provided no overflow occurred
return r;
}
void setup(){
//Initialize the serial ports that will be in communication
Serial.begin(9600);
Serial1.begin(9600);
//Serial port for the random number generator
Serial2.begin(9600);
//When the arduino is reset everything is set to low.
//initialize pins
pinMode(11, OUTPUT); //sets pin 11 to output
pinMode(10, INPUT); //sets pin 10 to input
//turn on pin to signal that we are online
digitalWrite(11, HIGH);
//wait for other arduino to come online
while(digitalRead(10)==LOW){
}
//This is our secret key
uint32_t a = keyGen();
//This is our shared index 'A'
uint32_t A = pow_mod(generator, a, prime);
Serial.print("Shared index is: ");
Serial.println(A);
uint8_t tempBits = 0;
uint32_t receivedBits;
uint32_t B = 0;
digitalWrite(11,LOW);
for(int i = 0 ; i < 4 ; i++){
//WAIT FOR THE OTHER HERE
digitalWrite(11,HIGH);
while(digitalRead(10)==LOW){
}
//shifting from the end to the beggining
tempBits = A >> 8*(3-i); //shift by one byte at a time
tempBits = tempBits & 0xff;
Serial1.write(tempBits);
receivedBits = 0;
while(Serial1.available() == 0){
} //wait until the there are bits in the serial
receivedBits = Serial1.read();
receivedBits = receivedBits<<8*(3-i);
B=B | receivedBits;
digitalWrite(11,LOW);
}
Serial.print("Received shared index is: ");
Serial.println(B);
//This is our shared secret encryption key.
k = pow_mod(B, a, prime);
//reseed the random number generator with the shared secret key k
randomSeed(k);
}
//Now lets send characters back and forth. This is encrypted with our secret key 'k' in conjuction with the xor function.
//This was taken from the "Multi Serial Mega" Arduino example and modifified with the XOR function.
void loop(){
// read from serial port 1, and send to serial monitor on port 0
if (Serial1.available()) {
// returns one byte of unsigned serial data, or -1 if none available
int16_t inByte = Serial1.read(); //mask out lower 8 bits from k
Serial.write(inByte^(random(256)));
if(inByte = '\n')
randomSeed(k);
}
// read from serial monitor on port 0, and send to port 1
if (Serial.available()) {
// returns one byte of unsigned serial data, or -1 if none available
int16_t inByte = Serial.read(); //mask out lower 8 bits from k
Serial1.write(inByte^(random(256)));
if(inByte ='\n')
randomSeed(k);
}
}
| true |
c5a12bea16ce802633bf48ba2a5cd1ca8de5bca4 | C++ | abhinashjain/codes | /codechef/Unionset.cpp | UTF-8 | 2,160 | 3.03125 | 3 | [] | no_license | #include "vector"
#include "iostream"
#include "algorithm"
#define FOR(i,begin,end) for(i=begin;i<end;i++)
#define dontsync() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
using namespace std;
int main()
{
dontsync()
int t,n,k,i,j,x,len,tmp,cnt;
cin >> t;
FOR(i,0,t)
{
cin >> n >> k;
vector<int> vect[n];
FOR(j,0,n)
{
cin >> len;
FOR(x,0,len)
{
cin >> tmp;
vect[j].push_back(tmp);
}
sort(vect[j].begin(),vect[j].end());
}
cnt=0;
FOR(j,0,n)
{
vector<int> res(k+5);
vector<int>::iterator iter;
FOR(x,j+1,n)
{
iter=set_union(vect[j].begin(), vect[j].end(), vect[x].begin(), vect[x].end(), res.begin());
res.resize(iter - res.begin());
if(res.size()==k)
{
cnt++;
}
}
}
cout << cnt << "\n";
}
return 0;
}
/*
There are N sets of integers from 1 to K both inclusive. Find out number of pairs of sets whose union contains all the K elements.
Input
The first line contains an integer T denotes number of test cases.
The first line of each test case contains two space separated integers N, K.
The each of the next line first contains an integer leni denoting number of elements in the i-th set, followed by leni space separated integers in the range [1, K] denoting the
elements in the set.
Output
For each test case, output a single integer corresponding to the answer.
Constraints
1 ≤ T ≤ 10
1 ≤ N, K ≤ 2500
1 ≤ leni ≤ K
Note that a set can't contain repeated elements.
1 ≤ len1 + len2 + .. + lenN ≤ 10000
Subtasks
Subtask #1 (40 points)
1 ≤ T ≤ 10
1 ≤ N, K ≤ 250
1 ≤ len1 + len2 + .. + lenN ≤ 1000
Subtask #2 (60 points)
original constraints.
Example
Input
3
2 2
1 1
1 1
3 2
2 1 2
2 1 2
2 1 2
3 4
3 1 2 3
4 1 2 3 4
3 2 3 4
Output
0
3
3
Explanation
Example 1. No pair of sets is there with its union = 2.
For example 2 and 3, all the pairs are valid.
*/
| true |
2bc6f3df3fe3e0f087c2fac061179ccc1b6d8c5a | C++ | jbaldwin/libwingmysql | /src/Row.cpp | UTF-8 | 645 | 2.6875 | 3 | [
"Apache-2.0"
] | permissive | #include "wing/Row.hpp"
#include <cstring>
namespace wing {
Row::Row(
MYSQL_ROW mysql_row,
size_t field_count,
unsigned long* lengths)
: m_column_count(field_count)
{
m_values.reserve(field_count);
for (size_t i = 0; i < field_count; ++i) {
auto* mysql_value = mysql_row[i];
std::optional<std::string_view> data;
if (mysql_value != nullptr) {
auto length = (lengths != nullptr) ? lengths[i] : std::strlen(mysql_value);
data = std::string_view(mysql_value, length);
}
Value value(std::move(data));
m_values.emplace_back(value);
}
}
} // wing
| true |
f6672dcd107d8fa4afab615de1b1ee2c8c93bc1a | C++ | wzit/Srl | /src/tests/Misc.cpp | UTF-8 | 9,795 | 2.671875 | 3 | [
"MIT"
] | permissive | #include "Tests.h"
#include "BasicStruct.h"
#include <list>
#include <memory>
using namespace std;
using namespace Srl;
using namespace Tests;
bool test_node_api()
{
string SCOPE = "Api test";
print_log("\tNode api...");
try {
Tree tree;
auto& root = tree.root();
root.insert("field0", 0, "field1", 1, "field2", 2);
root.insert("node0", root);
root.insert("node1", root.node("node0"));
root.node("node0").insert("node1", root.node("node0"));
root.node("node0").insert("field3", 3);
bool recursive = true;
size_t n_nodes = 3;
size_t n_values = (n_nodes + 1) * 3 + 1;
auto all_nodes = root.all_nodes(recursive);
TEST(all_nodes.size() == n_nodes)
auto all_values = root.all_values(recursive);
TEST(all_values.size() == n_values)
auto nodes_w_name = root.find_nodes("node1", recursive);
TEST(nodes_w_name.size() == 2)
auto values_w_name = root.find_values("field0", recursive);
TEST(values_w_name.size() == (n_nodes + 1))
values_w_name = root.find_values("field3", recursive);
TEST(values_w_name.size() == 1)
size_t counted_nodes = 0;
root.foreach_node([&counted_nodes](Node&) { counted_nodes++; }, recursive);
TEST(counted_nodes == n_nodes)
size_t counted_values = 0;
root.foreach_value([&counted_values](Value&) { counted_values++; }, recursive);
TEST(counted_values == n_values)
auto before = root.num_nodes();
root.remove_node("node0");
TEST(root.num_nodes() == (before - 1))
before = root.num_values();
root.remove_value("field0");
TEST(root.num_values() == (before - 1))
root.foreach_node([](Node& node) {
auto values = node.all_values();
for(auto* v : values) {
node.remove_value(v->name());
}
}, recursive);
counted_values = 0;
root.foreach_value([&counted_values](...) { counted_values++; }, recursive);
TEST(counted_values == root.num_values())
} catch(Srl::Exception& ex) {
print_log(string(ex.what()) + "\n");
return false;
}
print_log("ok.\n");
return true;
}
bool test_string_escaping()
{
string SCOPE = "String escaping";
try {
string str = "\"quotes\" & ampersand gr > ls < ap ' \n\b\t\r\f/ backslash \\";
Tree tree;
tree.root().insert("str", str);
print_log("\tString escaping xml...");
tree.load_source(tree.to_source(PXml()), PXml());
TEST(str == tree.root().unwrap_field<string>("str"));
print_log("ok.\n");
print_log("\tString escaping json...");
tree.load_source(tree.to_source(PJson()), PJson());
TEST(str == tree.root().unwrap_field<string>("str"));
print_log("ok.\n");
} catch(Srl::Exception& ex) {
print_log(string(ex.what()) + "\n");
return false;
}
return true;
}
bool test_document_building()
{
string SCOPE = "Document building";
try {
print_log("\tDocument building...");
Tree tree;
tree.root().insert(
"string", "string",
"int", 5,
"nested_node", Node(tree).insert(
"string", U"string",
"vector", vector<int> {
5, 7, 8
},
"list", list<list<string>> {
{ "a", "b", "c" },
{ "d", "e", "f" }
},
"nested_node", Node(tree).insert(
"int", 10
)
),
"double", 10.0
);
auto source = tree.to_source(PJson());
tree.load_source(tree.to_source(PJson()), PJson());
auto& node = tree.root();
auto& value = node.value("int");
auto some_int = value.unwrap<int>();
TEST(some_int == 5)
value = node.value("string");
auto some_string = value.unwrap<string>();
TEST(some_string == "string")
node.node("nested_node").paste_field("string", some_string);
TEST(some_string == "string");
auto nodes = node.find_nodes("nested_node", true);
TEST(nodes.size() == 2)
auto vec = nodes.front()->unwrap_field<vector<int>>("vector");
vector<int> vec_n { 5, 7, 8 };
TEST(vec == vec_n)
auto lst = node.node("nested_node").unwrap_field<list<list<string>>>("list");
list<list<string>> lst_n { list<string> { "a", "b", "c" }, list<string> { "d", "e", "f" } };
TEST(lst == lst_n)
double some_double;
node.paste_field("double", some_double);
TEST(some_double == 10.0)
Tree g_basic;
BasicStruct s_basic;
s_basic.shuffle();
s_basic.insert(g_basic);
BasicStruct r_basic;
r_basic.paste(g_basic);
s_basic.test(r_basic);
print_log("ok.\n");
return true;
} catch(Srl::Exception& ex) {
print_log(string(ex.what()) + "\n");
return false;
}
}
bool test_xml_attributes()
{
const string SCOPE = "Xml attribute parsing";
try {
print_log("\tXml attribute extraction...");
string xml = "<node attribute1 = \" 12 \" attribute2=\"value\" attribute3 = \" -10\"/>";
Tree tree;
tree.load_source(xml.c_str(), xml.size(), PXml());
double attribute1 = 0;
string attribute2 = "";
int attribute3 = 0;
tree.root().paste_field("attribute1", attribute1);
tree.root().paste_field("attribute2", attribute2);
tree.root().paste_field("attribute3", attribute3);
TEST(tree.root().name() == "node");
TEST(attribute1 == 12.0)
TEST(attribute2 == "value")
TEST(attribute3 == -10)
print_log("ok.\n");
return true;
} catch (Srl::Exception& ex) {
print_log(string(ex.what()) + "\n");
return false;
}
}
struct Base {
virtual int get() = 0;
virtual const Srl::TypeID& srl_type_id() = 0;
virtual void srl_resolve(Context& ctx) = 0;
virtual ~Base() { }
};
struct Root : Base {
int m = 0;
int get() override { return m; }
const Srl::TypeID& srl_type_id() override;
virtual void srl_resolve(Context& ctx) override
{
ctx ("root_field", m);
}
virtual ~Root() { }
};
const auto reg_root = Srl::register_type<Root>("Root");
const Srl::TypeID& Root::srl_type_id() { return reg_root; }
struct DerivedA : Root {
DerivedA(int i = 1) : a(i) { }
int a;
int get() override { return a; }
const Srl::TypeID& srl_type_id() override;
void srl_resolve(Context& ctx) override
{
Root::srl_resolve(ctx);
ctx ("a_field", a);
}
};
const auto reg_a = Srl::register_type<DerivedA>("DerivedA");
const Srl::TypeID& DerivedA::srl_type_id() { return reg_a; }
class DerivedB : public Root {
friend struct Srl::Ctor<DerivedB>;
public:
DerivedB(int i) : b(i) { }
int get() override { return b; }
const Srl::TypeID& srl_type_id() override;
void srl_resolve(Context& ctx) override
{
Root::srl_resolve(ctx);
ctx ("b_field", b);
}
private:
int b;
DerivedB() :b(0) { }
};
const auto reg_b = Srl::register_type<DerivedB>("DerivedB");
const Srl::TypeID& DerivedB::srl_type_id() { return reg_b; }
struct TestClass {
unique_ptr<Base> one;
unique_ptr<Base> two;
TestClass(Base* one_ = nullptr, Base* two_ = nullptr) : one(one_), two(two_) { }
void srl_resolve(Context& ctx)
{
ctx ("one", one) ("two", two);
}
};
bool test_polymorphic_classes()
{
const string SCOPE = "Serializing polymorphic classes";
print_log("\t" + SCOPE + "...");
try {
TestClass cl(new DerivedB(12), new DerivedA(6));
cl = Tree().restore<TestClass, PJson>(Tree().store<PJson>(cl));
TEST(strcmp(cl.one->srl_type_id().name(), "DerivedB") == 0);
TEST(strcmp(cl.two->srl_type_id().name(), "DerivedA") == 0);
TEST(cl.one->get() == 12);
TEST(cl.two->get() == 6);
} catch(Exception& ex) {
print_log(string(ex.what()) + "\n");
return false;
}
print_log("ok.\n");
return true;
}
struct Shared {
shared_ptr<Base> base0;
weak_ptr<Base> base1;
void srl_resolve(Context& ctx)
{
ctx("base0", base0) ("base1", base1);
}
};
bool test_shared_references()
{
const string SCOPE = "Serializing shared references";
print_log("\t" + SCOPE + "...");
shared_ptr<Base> res0;
shared_ptr<Base> res1;
weak_ptr<Base> res2;
try {
{
auto s0 = shared_ptr<Base>(new DerivedA());
weak_ptr<Base> s1 = s0;
Shared shared { s0, s1 };
auto bytes = Tree().store<PJson>(shared);
Tree tree;
tree.load_source(bytes, PJson());
res0 = tree.root().node("base0").unwrap<shared_ptr<Base>>();
res1 = tree.root().node("base1").unwrap<shared_ptr<Base>>();
res2 = tree.root().node("base1").unwrap<weak_ptr<Base>>();
}
TEST(res0.get() == res1.get())
TEST(res0.get() == res2.lock().get())
} catch(Exception& ex) {
print_log(string(ex.what()) + "\n");
return false;
}
print_log("ok.\n");
return true;
}
bool Tests::test_misc()
{
print_log("\nTest misc\n");
bool success = test_xml_attributes();
success &= test_document_building();
success &= test_string_escaping();
success &= test_node_api();
success &= test_polymorphic_classes();
success &= test_shared_references();
return success;
}
| true |
7c8ed788e46600ee1eafedc738c06c3e27241b34 | C++ | ianCSMajor/lab3 | /op_test.hpp | UTF-8 | 730 | 2.859375 | 3 | [] | no_license | #ifndef __OP_TEST_HPP__
#define __OP_TEST_HPP__
#include "gtest/gtest.h"
#include "op.hpp"
TEST(OpTest, OpEvaluateNonZero) {
Op* test = new Op(8);
EXPECT_EQ(test->evaluate(), 8);
}
TEST(OpTest, OpPrintNonZero) {
Base* test = new Op(8);
EXPECT_EQ(test->stringify(), "8.000000");
}
TEST(OpTest, OpEvaluateSix) {
Base* test = new Op(6);
EXPECT_EQ(test->evaluate(), 6.0);
}
TEST(OpTest, OpPrintSix) {
Base* test = new Op(6);
EXPECT_EQ(test->stringify(), "6.000000");
}
TEST(OpTest, OpEvaluateZero) {
Base* test = new Op(0);
EXPECT_EQ(test->evaluate(), 0);
}
TEST(OpTest, OpPrintZero) {
Base* test = new Op(0);
EXPECT_EQ(test->stringify(), "0.000000");
}
#endif //__OP_TEST_HPP__
| true |
419e6ba40e0dd8557f3948e540ffc034f7336991 | C++ | Stiffstream/habrhabr_article_2_ru | /dev/common/io_agent.hpp | UTF-8 | 3,374 | 2.8125 | 3 | [] | no_license | #pragma once
#include <common/stuff.hpp>
//
// Сообщения, которые необходимы для взаимодействия IO-агента с внешним миром.
//
// Запрос на загрузку содержимого файла.
struct load_email_request
{
// Имя файла для загрузки.
string email_file_;
// Куда нужно прислать результат.
mbox_t reply_to_;
};
// Успешный результат загрузки файла.
struct load_email_succeed
{
// Содержимое файла.
string content_;
};
// Неудачный результат загрузки файла.
struct load_email_failed
{
// Описание причины неудачи.
string what_;
};
//
// Сам IO-агент.
//
// Реальный IO-агент наверняка будет использовать асинхронный IO, но для
// целей демонстрации используем простую схему имитации асинхронного IO:
// на каждый запрос отсылаем ответ с некоторой задержкой. Это позволит
// нам имитировать паузы в загрузки содержимого файла, но сам IO-агент
// сможет работать на дефолтном диспетчере не приостанавливая рабочую
// нить этого диспетчера.
//
// Так же этот агент имитирует различные нештатные ситуации:
// - каждый 7-й запрос будет завершаться неудачным результатом
// (т.е. отсылкой load_email_failed);
// - на каждый 15-й запрос ответ не будет отсылаться вовсе.
//
class io_agent final : public agent_t {
public :
io_agent( context_t ctx ) : agent_t( ctx ) {
// Для взаимодействия с внешним миром IO-агент будет использовать
// именованный mbox.
so_subscribe( so_environment().create_mbox( "io_agent" ) )
.event( &io_agent::on_request );
}
private :
// Этот счетчик нужен для определения того, как среагировать
// на очередной запрос.
int counter_{ 0 };
void on_request( const load_email_request & msg ) {
++counter_;
if( 0 == (counter_ % 15) )
{} // Вообще ничего не отсылаем, как будто запрос потерялся
// где-то по дороге.
else {
// Для имитации задержки в выполнении запроса.
const auto pause = chrono::milliseconds( msg.email_file_.length() * 10 );
if( 0 == (counter_ % 7) )
// Пришло время отослать отрицательный результат.
send_delayed< load_email_failed >( so_environment(),
msg.reply_to_, pause, "IO-operation failed" );
else
send_delayed< load_email_succeed >( so_environment(),
msg.reply_to_, pause, string() );
}
}
};
void make_io_agent( environment_t & env ) {
env.introduce_coop( []( coop_t & coop ) {
coop.make_agent< io_agent >();
} );
}
| true |
329656643a711b405066b0d57155e7bd5901d516 | C++ | matt-barron/lab_review | /test.cpp | UTF-8 | 512 | 2.734375 | 3 | [] | no_license | #include <iostream>
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "funcs.h"
#include "doctest.h"
// Write test cases here
TEST_CASE("Task A"){
REQUIRE(removeLeadingSpaces(" int x = 1; ") == "int x = 1; ");
REQUIRE(removeLeadingSpaces(" hello .") == "hello .");
REQUIRE(removeLeadingSpaces(" world;") == "world;");
}
TEST_CASE("Task B"){
REQUIRE(countChar("int main(){{}}", '{') == 2);
REQUIRE(countChar("while(){}}}", '}') == 3);
REQUIRE(countChar("hellohey hhh", 'h') == 5 );
}
| true |
89eced553798f6b7a88ddbc5ae2d451331722e90 | C++ | Debashish-hub/100-Days-Of-Coding | /Day 70/check if string is rotated by 2 places.cpp | UTF-8 | 1,261 | 3.90625 | 4 | [] | no_license | // Check if string is rotated by two places
// Given two strings a and b. The task is to find if the string 'b' can be obtained by rotating another
// string 'a' by exactly 2 places.
// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
//Function to check if a string can be obtained by rotating
//another string by exactly 2 places.
bool isRotated(string str1, string str2)
{
// Your code here
if(str1.size() != str2.size())
{
return false;
}
int n = str1.size();
if(n == 1)
{
if(str1[0] == str2[0])
{
return true;
}
return false;
}
if(str1[0] == str2[n - 2] and str1[1] == str2[n - 1])
{
return true;
}
if(str2[0] == str1[n - 2] and str2[1] == str1[n - 1])
{
return true;
}
return false;
}
};
// { Driver Code Starts.
int main() {
int t;
cin>>t;
while(t--)
{
string s;
string b;
cin>>s>>b;
Solution obj;
cout<<obj.isRotated(s,b)<<endl;
}
return 0;
}
// } Driver Code Ends | true |
629491f67c158c71f7be2c34daf37e2bdf35805a | C++ | JustLikeTT/DarkChess | /DarkChess/main.cpp | UTF-8 | 2,338 | 2.59375 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include "KAI.h"
#include <iostream>
using namespace std;
// commands enumerate
enum COMMANDS {
PROTOCOL_VERSION = 0, // 0
NAME, // 1
VERSION, // 2
KNOWN_COMMAND, // 3
LIST_COMMANDS, // 4
QUIT, // 5
BOARDSIZE, // 6
RESET_BOARD, // 7
NUM_REPETITION, // 8
NUM_MOVES_TO_DRAW, // 9
MOVE, // 10
FLIP, // 11
GENMOVE, // 12
GAME_OVER, // 13
READY, // 14
TIME_SETTINGS, // 15
TIME_LEFT, // 16
SHOWBOARD // 17
};
// function pointer array
static bool (KAI::* functions[])(const char* [], char*) = {
&KAI::protocol_version,
&KAI::name,
&KAI::version,
&KAI::known_command,
&KAI::list_commands,
&KAI::quit,
&KAI::boardsize,
&KAI::reset_board,
&KAI::num_repetition,
&KAI::num_moves_to_draw,
&KAI::move,
&KAI::flip,
&KAI::genmove,
&KAI::game_over,
&KAI::ready,
&KAI::time_settings,
&KAI::time_left,
&KAI::showboard
};
int main() {
char read[1024], write[1024], output[1024], * token;
const char* data[10];
int id;
bool isFailed;
KAI kai;
do {
// read command
fgets(read, 1024, stdin);
fprintf(stderr, "%s", read);
// remove newline(\n)
read[strlen(read) - 1] = '\0';
// get command id
token = strtok(read, " ");
sscanf(token, "%d", &id);
// get command name
token = strtok(NULL, " ");
// get command data
int i = 0;
while ((token = strtok(NULL, " ")) != NULL) {
data[i++] = token;
}
write[0] = '\0'; // empty the char array
isFailed = (kai.*functions[id])(data, write);
if (strlen(write) > 0) {
if (isFailed) {
sprintf(output, "?%d %s\n", id, write);
}
else {
sprintf(output, "=%d %s\n", id, write);
}
}
else {
if (isFailed) {
sprintf(output, "?%d\n", id);
}
else {
sprintf(output, "=%d\n", id);
}
}
fprintf(stdout, "%s", output);
fprintf(stderr, "%s", output);
// important, do not delete
fflush(stdout);
fflush(stderr);
} while (id != QUIT);
return 0;
} | true |
0d23185d5c67a3c48c1bb3a93528c8d29f86228e | C++ | Wanna-SSJ/Coding-Interviews | /ZY - Coding-Interviews Of Order/面试题24:反转链表/ReverseList.cpp | GB18030 | 1,315 | 3.953125 | 4 | [] | no_license | // 24ת
// Ŀһһͷ㣬תת
// ͷ㡣
#include<stdio.h>
#include<stdlib.h>
#include "LinkList.h"
BNode* ReverseList(BNode* pHead)
{
if (pHead == NULL)
{
return NULL;
}
BNode *pReversedHead = NULL;
BNode *pNode = pHead;
BNode *pPrev = NULL;
while (pNode != NULL)
{
BNode *pNext = pNode->next;
if (pNext == NULL)
{
pReversedHead = pNode;
}
pNode->next = pPrev;
pPrev = pNode;
pNode = pNext;
}
return pReversedHead;
}
// ====================Դ====================
BNode* Test(BNode* pHead)
{
printf("The original list is: \n");
Show(pHead);
BNode* pReversedHead = ReverseList(pHead);
printf("The reversed list is: \n");
Show(pReversedHead);
return pReversedHead;
}
// ж
void Test1()
{
BTlist N;
InitList(&N);
Insert_tail(&N,1);
Insert_tail(&N,2);
Insert_tail(&N,3);
Insert_tail(&N,4);
Insert_tail(&N,5);
Test(N);
}
// ֻһ
void Test2()
{
BTlist N;
InitList(&N);
Insert_tail(&N,1);
Test(N);
}
//
void Test3()
{
BTlist N;
InitList(&N);
Test(N);
}
int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
return 0;
}
| true |
0a4ce6958c92b1245c3bbeef52abcaae9843ed52 | C++ | jonathan-mcmillan/csci4650_lab2 | /Part_2/part_2.cpp | UTF-8 | 10,862 | 2.875 | 3 | [] | no_license | // Oliver Grassmann & Jonathan McMillan
// 1 Nov 2019
// CSCI 4650 - Computer Security
// Programming Assignment 2 - Part 2
/*
1. Take the filenames of the plaintext message, the encrypted session key, the third-party public key, and your private key as command-line parameters.
2. Use the third-party public key to decrypt the session key.
3. Save the plaintext session key to a text file.
4. Use the DES session key to encrypt the plaintext.
5. Use your private key to sign the encrypted message. 6. Save the ciphertext and signature to an output file (or separate output files).
*/
#include <iostream>
#include <fstream>
#include <string>
#include <cstdio>
#include <cerrno>
#include <stdio.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/crypto.h>
#include <openssl/engine.h>
#include <openssl/des.h>
#include <openssl/conf.h>
#include <openssl/err.h>
using namespace std;
int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key, unsigned char *iv, unsigned char *ciphertext);
//Encrypts a plaintext buffer in a buffer using DES
int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key, unsigned char *iv, unsigned char *plaintext);
//Decrypts a ciphertext buffer using DES
int pem_passwd_cb(char *buf, int size, int rwflag, void *password);
//Need this because a function needs a function pointer
void handleErrors(void);
//Prints errors to stdout
string readFile(string fileName);
//Takes a string fileName indicating the location of a file to be read and returns a string of the contents
int main(int argc, char *argv[]) {
//start of 1
string plaintextMessageFN, encryptedSessionKeyFN, thirdPartyPublicKeyFN, yourPrivateKeyFN;
if(argc != 5) {
cout << "Usage: part2 <plaintext_message.txt> <encrypted_session.key> <third-party_public_key.pem> <your_private_key.pem>" << endl << "Incorrect number of parameters entered, using default file name values instead." << endl;
plaintextMessageFN = "plaintext_message.txt";
encryptedSessionKeyFN = "encrypted_session.key";
thirdPartyPublicKeyFN = "pubkey.pem";
yourPrivateKeyFN = "jon_private.pem";
} else {
plaintextMessageFN = argv[1];
encryptedSessionKeyFN = argv[2];
thirdPartyPublicKeyFN = argv[3];
yourPrivateKeyFN = argv[4];
}
string plaintextMessage = readFile(plaintextMessageFN);
cout << "Plaintext Message: " << endl << plaintextMessage << endl;
string encryptedSessionKey = readFile(encryptedSessionKeyFN);
cout << "Encrypted Session Key: " << endl << encryptedSessionKey << endl;
string thirdPartyPublicKey = readFile(thirdPartyPublicKeyFN);
cout << "Third-Party Public Key: " << endl << thirdPartyPublicKey << endl;
string yourPrivateKey = readFile(yourPrivateKeyFN);
cout << "Your Private Key: " << endl << yourPrivateKey << endl;
//start of 2 - https://wiki.openssl.org/index.php/EVP_Asymmetric_Encryption_and_Decryption_of_an_Envelope
//there is a section called opening and envelope which should help with this
//https://www.openssl.org/docs/man1.0.2/man3/EVP_PKEY_encrypt.html
ENGINE *eng = ENGINE_get_default_RSA();
unsigned char *out, *in;
size_t outlen, inlen;
//read public key
cout << "pub key" << endl;
FILE *pub = fopen(thirdPartyPublicKeyFN.c_str(), "rb");
EVP_PKEY *pub_key = PEM_read_PUBKEY(pub, NULL, NULL, NULL);
if(pub_key == NULL){
throw(errno);
}
EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(pub_key, eng);
if(!ctx){
throw(errno);
}
if(EVP_PKEY_encrypt_init(ctx) <= 0){
throw(errno);
}
if(EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING) <= 0){
throw(errno);
}
in =(unsigned char *) encryptedSessionKey.c_str();
inlen = strlen(encryptedSessionKey.c_str());
if(EVP_PKEY_encrypt_init(ctx) <= 0){
throw(errno);
}
//find buffer length
if(EVP_PKEY_encrypt(ctx, NULL, &outlen, in, inlen) <= 0){
throw(errno);
}
out = (unsigned char*) OPENSSL_malloc(outlen);
if(!out){
throw(errno);
}
if (EVP_PKEY_encrypt(ctx, out, &outlen, in, inlen) <= 0){
//throw(errno);
cout << "unable to decrypt session key..." << endl << &out << endl << out << endl;
}
//at this point decrypted data is in buffer -- assume this is right for now
//end of 2
string de_ses((char *) out);
cout << hex << de_ses << endl;
//start of 3
//write buffer to a file
//http://www.cplusplus.com/reference/cstdio/fwrite/
ofstream out_f("decrypted_session.txt");
out_f << de_ses;
out_f.close();
// 4. Use DES session key to encrypt the plaintext
unsigned char *iv = (unsigned char *) "0123456789012345";
unsigned char ciphertext[outlen];
int ciphertext_len;
ciphertext_len = encrypt((unsigned char *) plaintextMessage.c_str(), strlen ((char *) plaintextMessage.c_str()), out, iv, ciphertext);
if(ciphertext_len <= 0){
throw(errno);
}
cout << "Ciphertext Length: " << ciphertext_len << endl;
cout << "Ciphertext: " << endl << ciphertext << endl;
cout << "Ciphertext (HEX): " << endl;
BIO_dump_fp (stdout, (const char *)ciphertext, ciphertext_len);
ofstream ciphertext_f("cipher_text.txt");
ciphertext_f << ciphertext;
ciphertext_f.close();
// Decrypt the ciphertext to make sure we did it right
unsigned char decryptedText[outlen];
int decryptedText_len;
decryptedText_len = decrypt(ciphertext, ciphertext_len, out, iv, decryptedText);
if(decryptedText_len <= 0){
throw(errno);
}
decryptedText[decryptedText_len] = '\0';
cout << "Decrypted Text Length: " << decryptedText_len << endl;
cout << "Decrypted Text: " << endl << decryptedText << endl;
// 5. Use private key to sign the encrypted message
//https://wiki.openssl.org/index.php/EVP_Signing_and_Verifying
EVP_MD_CTX *mdctx = NULL;
size_t *slen;
unsigned char *sig;
/* Create the Message Digest Context */
if(!(mdctx = EVP_MD_CTX_create())) handleErrors();
/* Open the private key */
cout << endl << "Opening Private Key: " << endl;
char* password = (char *) "password";
char* pwd_buf[8];
//int ppc = pem_password_cb(pwd_buf, 8, 1, password);
FILE *priv = fopen(yourPrivateKeyFN.c_str(), "rb");
EVP_PKEY *priv_key = PEM_read_PrivateKey(priv, NULL, NULL, NULL);
if(pub_key == NULL){
throw(errno);
}
cout << readFile(yourPrivateKeyFN) << endl;
/* Initialise the DigestSign operation - SHA-256 has been selected as the message digest function in this example */
cout << "Initializing DigestSign..." << endl;
if(1 != EVP_DigestSignInit(mdctx, NULL, EVP_sha256(), NULL, priv_key)) handleErrors();;
/* Call update with the message */
cout << "Adding message to cipher context..." << endl;
if(1 != EVP_DigestSignUpdate(mdctx, ciphertext, ciphertext_len)) handleErrors();;
/* Finalise the DigestSign operation */
/* First call EVP_DigestSignFinal with a NULL sig parameter to obtain the length of the * signature. Length is returned in slen */
cout << "Finding signature length..." << endl;
if(1 != EVP_DigestSignFinal(mdctx, NULL, slen)) handleErrors();;
/* Allocate memory for the signature based on size in slen */
cout << "Allocating memory for signature..." << endl;
if(!(sig = (unsigned char *) OPENSSL_malloc(sizeof(unsigned char) * (*slen)))) handleErrors();;
/* Obtain the signature */
cout << "Finalizing DigestSign and storing signature into memory..." << endl;
if(1 != EVP_DigestSignFinal(mdctx, sig, slen)) handleErrors();;
// 6. Save signature into output file
cout << "Saving Signature: " << endl;
std::ofstream ofs;
ofs.open ("signature.txt", std::ofstream::out | std::ofstream::app);
ofs << (char*) sig;
ofs.close();
cout << (char*) sig << endl;
/* Clean up */
if(sig) OPENSSL_free(sig);
if(mdctx) EVP_MD_CTX_destroy(mdctx);
return 0;
}
//https://wiki.openssl.org/index.php/EVP_Symmetric_Encryption_and_Decryption
int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key,
unsigned char *iv, unsigned char *ciphertext)
{
EVP_CIPHER_CTX *ctx;
int len;
int ciphertext_len;
/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new()))
handleErrors();
/*
* Initialise the encryption operation. IMPORTANT - ensure you use a key
* and IV size appropriate for your cipher
* In this example we are using 256 bit AES (i.e. a 256 bit key). The
* IV size for *most* modes is the same as the block size. For AES this
* is 128 bits
*/
if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
handleErrors();
/*
* Provide the message to be encrypted, and obtain the encrypted output.
* EVP_EncryptUpdate can be called multiple times if necessary
*/
if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
handleErrors();
ciphertext_len = len;
/*
* Finalise the encryption. Further ciphertext bytes may be written at
* this stage.
*/
if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len))
handleErrors();
ciphertext_len += len;
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
return ciphertext_len;
}
int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key,
unsigned char *iv, unsigned char *plaintext)
{
EVP_CIPHER_CTX *ctx;
int len;
int plaintext_len;
/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new()))
handleErrors();
/*
* Initialise the decryption operation. IMPORTANT - ensure you use a key
* and IV size appropriate for your cipher
* In this example we are using 256 bit AES (i.e. a 256 bit key). The
* IV size for *most* modes is the same as the block size. For AES this
* is 128 bits
*/
if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
handleErrors();
/*
* Provide the message to be decrypted, and obtain the plaintext output.
* EVP_DecryptUpdate can be called multiple times if necessary.
*/
if(1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
handleErrors();
plaintext_len = len;
/*
* Finalise the decryption. Further plaintext bytes may be written at
* this stage.
*/
if(1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len))
handleErrors();
plaintext_len += len;
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
return plaintext_len;
}
void handleErrors(void)
{
ERR_print_errors_fp(stdout);
abort();
}
string readFile(string fileName) {
//file reading https://insanecoding.blogspot.com/2011/11/how-to-read-in-file-in-c.html
const char *filename = fileName.c_str();
FILE *file = fopen(filename, "rb");
if(file){
string contents;
fseek(file, 0, SEEK_END);
contents.resize(ftell(file));
rewind(file);
fread(&contents[0], 1, contents.size(), file);
fclose(file);
return(contents);
}
throw(errno);
}
| true |
9b38e4fcfd4ddee96ff73d9bd2cb36cbd8094c84 | C++ | yycccccccc/Leetcode | /061.Rotate List.cpp | UTF-8 | 2,100 | 3.796875 | 4 | [] | no_license | 题意:
根据指定值n旋转链表n次。
思路:
1.设置一个dummy头结点便于最后返回操作,p指针指向当前结点,pre指向p之前的结点
2.依次循环,当p不存在的时候把pre指向NULL,p->next = 头结点,注意是头结点不是head,因为head没有根据旋转同步更新
3.直到k=0的时候输出dummy->next
4.因为k值有可能非常大,因此需要首先计算出链表的长度,用k对链表的长度取余,即最小旋转次数。
计算链表长度的时候需要从1开始计数。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(!head) return head;
ListNode* dummy = new ListNode(-1);
ListNode* cur = dummy;
cur -> next = head;
ListNode* p = head;
ListNode* pre = cur;
pre -> next = p;
int len = 1;
while(p->next){
++len;
p = p -> next;
}
p = head;
k = k%len;
while(k>0){
while(p->next != NULL){
pre = pre -> next;
p = p->next;
}
pre->next = NULL;
p -> next = cur -> next;
cur ->next = p;
pre = cur;
--k;
}
return dummy -> next;
}
};
优化:
还有一种思路是首先把链表连接成一个环,从头结点开始向后移动(链表长度-k%链表长度)个单位到达一个新结点,再断开链表即可。
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if (!head) return NULL;
int n = 1;
ListNode *cur = head;
while (cur->next) {
++n;
cur = cur->next;
}
cur->next = head;
int m = n - k % n;
for (int i = 0; i < m; ++i) {
cur = cur->next;
}
ListNode *newhead = cur->next;
cur->next = NULL;
return newhead;
}
}; | true |
1ad725e17c6133c32af5e464c4351caaf35b493d | C++ | bdobrzycki/NAVEX | /dualQuat.h | UTF-8 | 3,223 | 2.953125 | 3 | [] | no_license | #ifndef __DUAL_QUATERNION_H__
#define __DUAL_QUATERNION_H__
#include <assert.h>
#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
#include "quat.h"
//#include "vector3.h"
//#include "vector4.h"
namespace GrapheneMath
{
template <typename Scalar>
class DualQuaternion
{
private:
Quaternion<Scalar> q0;
Quaternion<Scalar> qe;
public:
// Default ctor creates identity quaternions.
DualQuaternion()
: q0( Scalar(1.0), Vector3<Scalar>( 0.0, 0.0, 0.0 ) ), //< identity quaternion
qe( Scalar(1.0), Vector3<Scalar>( 0.0, 0.0, 0.0 ) ) //< identity quaternion
{}
inline const Quaternion<Scalar> GetQ0() const { return q0; }
inline const Quaternion<Scalar> GetQe() const { return qe; }
/*DualQuaternion( const Quaternion& _q0, const Quaternion& _qe )
: q0( _q0 ), qe( _qe )
{}
// Function creates dual quaternion form unit axis, angle (in radians) and translation.
inline void FromAxisAngleTranslation(
const Vector3& axis,
double angle,
const Vector3& translation )
{
//assert( abs (1.0 - axis.Magnitude() ) < MathTools::UNIT_TOLERANCE );
q0.FromAxisAngle( axis, angle );
qe.FromRealPartVector( 0.0, translation * 0.5 );
qe = qe * q0;
}
// Dual quaternion - dual quaternionMultiplication operator
// ( non-optimal implementation )
// @ - dual unit, @^2 = 0
// d - dual quaternion
// dq * dp = (q0 + @qe)(p0 + @pe) = q0p0 + @q0pe + @qep0 + @^2qepe
// = q0p0 + @(q0pe + qep0) + 0
// = q0p0 + @(q0pe + qep0)
inline const DualQuaternion operator*( const DualQuaternion& dp ) const
{
return DualQuaternion( q0 * dp.q0, q0 * dp.qe + qe * dp.q0 );
}
// Dual quaternion - quaternion multiplication operator
// ( non-potimal implementation )
// @ - dual unit, @^2 = 0
// dq * p = (q0 + @qe)p = q0p + @qep
inline const DualQuaternion operator*( const Quaternion& p ) const
{
return DualQuaternion( q0 * p, qe * p );
}
// Transform - rotates and translates input vector v using this dual quaternion.
Vector3 Transform( const Vector3& v )
{
// Convert vertex to dual quaternion.
const DualQuaternion dv( Quaternion( 1.0, Vector3( 0.0, 0.0, 0.0 ) ), // q0
Quaternion( 0.0, v ) ); // qe
const DualQuaternion dq = *this;
DualQuaternion dqCDC( dq );
dqCDC = dqCDC.Conjugate();
dqCDC = dqCDC.DualConjugate();
return ( dq * ( dv * dqCDC ) ).qe.v;
}
// Conjugation.
inline const DualQuaternion Conjugate( void ) const
{
return DualQuaternion( ~q0, ~qe );
}
// Dual conjugation.
inline const DualQuaternion DualConjugate( void ) const
{
return DualQuaternion( q0, Quaternion( qe.GetRealPart() * ( -1.0 ),
qe.GetVectorPart() * ( -1.0 ) ) );
}
*/
};
} //< End of namespace GrapheneMath
#endif //__DUAL_QUATERNION_H__
| true |
910b42e5d0467a68f63144a754d0476b92e0da55 | C++ | FoolBit/ssA | /Section4/1.cpp | UTF-8 | 1,169 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <cstring>
#include <string>
#include <set>
using namespace std;
struct Pattern
{
int size;
set<int> p[51];
void init(string s)
{
size = 0;
int len = s.length();
int i=0;
for( ; i<len; ++i)
{
if(s[i]!='[')
{
p[size++].insert(tolower(s[i]));
continue;
}
++i;
while(s[i]!=']')
p[size].insert(tolower(s[i])), ++i;
++size;
}
}
bool check(string s)
{
int len = s.length();
if(len != size)
return 0;
for(int i=0; i<len; ++i)
if(p[i].find(tolower(s[i]))==p[i].end())
return 0;
return 1;
}
};
int N;
Pattern pattern;
string str[53];
void init()
{
ios::sync_with_stdio(0);
cin >> N;
for(int i=0; i<N; ++i)
cin >> str[i];
cin >> str[N];
pattern.init(str[N]);
}
void process()
{
for(int i=0; i<N; ++i)
{
if(pattern.check(str[i]))
cout << i+1 << ' ' << str[i] << endl;
}
}
int main()
{
init();
process();
} | true |
38267cd5c4c01230e034a40323d5e9e40b9501f6 | C++ | katlegoEnoch/AntiPede | /game-source-code/GameController.cpp | UTF-8 | 8,530 | 3 | 3 | [] | no_license | //File_name: GameController.cpp
//Author: Stax The Engipreneur
//Date: 31 August 2018
//Details:
#include "GameController.h"
#include <iostream>
using namespace std;
/*Ran into scope issues and window was only open in the function in which the renderWindow function is called*/
//window dimensions
//function of constructor is to initialize the state of its data members
GameController::GameController() : gameIsRunning_(false)
{
//ensure that ant starts at centre of bottom row
//initialize field
field_ = make_shared<Field>(fieldWidth,fieldHeight);
//initialize Ant, when Ant constructor is called, gun is automatically created
//Ant has handle to its gun
auto ant_size = 20;
auto ant_x = static_cast<int>((fieldWidth/2)-20);
auto ant_y = fieldHeight - (ant_size+10);
ant_ = make_shared<Ant>(ant_x,ant_y,ant_size);
//
//construct Centipede with 10 segments
auto numberOfSegments = 15;
centipede_ = make_shared<Centipede>(numberOfSegments);
//Centipede always starts at top left of field
auto seg_x = 11;//11
auto seg_y = 10;//fieldHeight -(ant_size+60);//10;
//add segments to Centipede
for(size_t cent_elmnt = 0; cent_elmnt < centipede_->numberOfSegments();cent_elmnt++){
if(cent_elmnt != 0){
//create segment
auto segment = make_shared<Segment>(seg_x+((cent_elmnt)*20),seg_y,10.f,Direction::EAST);
//add segment to Centipeded
centipede_->addSegmentToCentipede(segment);
}//end if
else{
auto segment = make_shared<Segment>(seg_x,seg_y,10.f,Direction::EAST);
//add segment to Centipeded
centipede_->addSegmentToCentipede(segment);
}//end else
}//end loop
//create a window
appWindow_ = make_shared<Window>(300,300);
//create resource
resource_ = make_shared<Resource>();
//create a renderer and initialize its window
renderer_ = make_shared<Renderer>(appWindow_);
//create event handler
event_ = make_shared<EventsHandler>();
}
void GameController::openApplicationWindow()
{
//Attach a window to Controller's appWindow pointer
//synchronize frame-rate to monitor's frame rate
appWindow_->syncWindowToMonitor();
//clear the window
appWindow_->clearWindow(Colour::BLACK_);
//return controller to caller
return;
}
void GameController::displaySplashScreen()
{
//create ScreenSplasher object and pass window
ScreenSplasher splasher(appWindow_,resource_);
//command object to display splash screen
splasher.displaySplashScreen();
}
void GameController::playGame()
{
//while the window is open
while(appWindow_->windowIsOpen())
{
//fire from here
if(!bullets_.empty()){
fireBullet();
}
//for all the segments in the centipede
for(size_t centLoc = 0; centLoc < centipede_->numberOfSegments();centLoc++){
//inner loop - for all the bullets
for(size_t bulloc = 0; bulloc < bullets_.size();bulloc++){
//calculate size of region surrounding bullet
auto bul_reg = bullets_.at(bulloc).computeBulletRegion();
//calculate region of region surrounding segment
auto seg_reg = centipede_->getSegmentAt(centLoc).computeSegmentRegion();
//compute a mactch between the two regions, if there's a match
if(!bullets_.empty()){
//compare the heights
if(computeMatch(seg_reg,bul_reg)){
//if the heights also match
if(bullets_.at(bulloc).getBulletHeight() == centipede_->getSegmentAt(centLoc).getSegmentHeight()){
//change the current segment's state to false
centipede_->getSegmentAt(centLoc).setSegmentState(false);
//change current bullet's state to false as well;
bullets_.at(bulloc).setBulletState(true);
}//end if
}//end if
}//end if
}//end inner loop
}//end outer for loop
//move segment by pixel to right each time we loop, that's too fast, the screen is too small.
if(gameIsRunning_){
//move Centipede
centipede_->moveCentipede(0);
}
while(appWindow_->queryEvent(*(event_->getEvent()))){
//update objects based on inputs
updateGameObjects();
}//end event monitoring loop
//decide on action based on status of game, running or not
if(gameIsRunning_){
drawGameObjects();
}
}//main window closed
}
void GameController::drawGameObjects()
{
//clear the window
appWindow_->clearWindow(Colour::M_GREEN_);
//Draw Field
renderer_->drawField(field_);
//draw Ant
renderer_->drawAntOnField(ant_);
//draw Gun
//Gun is accessed through Ant
renderer_->drawGun(ant_->getGun());
//draw Centipede
renderer_->drawCentipede(centipede_);
//draw Bullet, accessed through its owner ant
renderer_->drawBullets(bullets_);
appWindow_->showContents();
}
void GameController::updateGameObjects()
{
//process event
switch(event_->processEvent()){
case KeyCode::CLOSE_WINDOW:
//close window
if(gameIsRunning_){
//window not closing properly
}
break;
case KeyCode::START_GAME:
//start_game
if(!gameIsRunning_){
gameIsRunning_ = true;
}
break;
case KeyCode::END_GAME:
//close window
appWindow_->shutDownWindow();
break;
case KeyCode::MOVE_ANT_LEFT:
//move ant left
ant_->moveAnt(-10,0);
break;
case KeyCode::MOVE_ANT_RIGHT:
//move ant right
ant_->moveAnt(10,0);
break;
case KeyCode::FIRE_BULLET:
//create bullet object
ant_->setBullet(ant_->releaseBullet());
//add bullet to Controller's memory
addBulletToController(ant_->releaseBullet());
break;
case KeyCode::IGNORE_INPUT:
//
gameIsRunning_ = false;
default:
//do nothing
gameIsRunning_ = true;
break;
}//end switch
}
void GameController::addBulletToController(const Bullet& bullet)
{
bullets_.push_back(bullet);
}
//how about implementing the fire bullet function on the controller and not the ant?
//if that was the case then...
void GameController::fireBullet()
{
//at the moment a Bullet is created it should start moving upward
for(size_t loc = 0; loc < bullets_.size();loc++){
//move the corresponding bullet
bullets_.at(loc).moveBullet(8,Direction::NORTH);
}
}
//yes it worked! So the ant and the controller pretty much share the responsibility of the bullet's behaviour
//the bullet is an inanimate object and does not control itself, the ant controls the bullet.
bool GameController::computeMatch(shared_ptr<Region> segment,shared_ptr<Region> bullet)
{
//extrac values from pointers passed in
auto segRegionMax = segment->getRegionMax();
auto segRegionMin = segment->getRegionMin();
auto segCenter = segment->getCenter();
auto bullRegionMax = bullet->getRegionMax();
auto bullRegionMin = bullet->getRegionMin();
auto bulCenter = bullet->getCenter();
//radius for segment and center can be computed
auto segRad = segRegionMax - segRegionMin;
auto bulRad = bullRegionMax - bullRegionMin;
//compute degree of match
//for bullet on left of segment
if(bulCenter < segCenter){
if((bulCenter+bulRad) < (segCenter-segRad)){
return false;
}//end if
else
return true;
}// end if
else if(bulCenter > segCenter){
//for bullet to right of segment
if((segCenter+bulRad) < (bulCenter-bulRad)){
return false;
}
else
return true;
}// end else if
//bullet on left or right of segment
else if(((bulCenter+bulRad) >= (segCenter-segRad)) || ((bulCenter - bulRad) <= (segCenter+segRad)))
return true;
else
return false;
} | true |
8ad027c72ca8064f6a252f2a83c22c155492b8b4 | C++ | TeamProjectTCA/CommunicationEvent2018 | /Mirror/Common/Drawer.h | SHIFT_JIS | 2,407 | 2.546875 | 3 | [] | no_license | #pragma once
#include "smart_ptr.h"
#include "Base.h"
#include "const.h"
#include <list>
#include <array>
PTR( Drawer );
PTR( Color );
class Drawer : public Base {
public:
enum FONTSIZE_TYPE {
SMALL,
NORMAL,
LITTLE_BIG,
BIG,
SUPER_BIG,
FONT_TYPE_MAX
};
public:
Drawer( );
virtual ~Drawer( );
public:
std::string getTag( );
void initialize( );
void update( );
public:
void setBackImage( ImageProperty png );
void setImage( ImageProperty png );
//ɂ邩ǂ, xW, yW, J[, , tHgTCY, At@l
void setFrontString( bool flag, double x, double y, COLOR col, std::string str, FONTSIZE_TYPE type = NORMAL, int brt = 255 );
void setBackString( bool flag, double x, double y, COLOR col, std::string str, FONTSIZE_TYPE type = NORMAL, int brt = 255 );
void setLine( double sx, double sy, double ex, double ey, COLOR col = WHITE, int brt = 255 );
void setCircle( double x, double y, double r, COLOR col = WHITE, int brt = 255, bool isfill = false );
void setBox( double lx, double ly, double rx, double ry, COLOR col = WHITE );
int getStringW( FONTSIZE_TYPE type, std::string str ) const;
int getStringH( FONTSIZE_TYPE type ) const;
private:
void drawBackImage( );
void drawImage( );
void drawFrontString( );
void drawBackString( );
void drawLine( );
void drawCircle( );
void drawBox( );
void reset( );
private:
struct StringProperty {
float x;
float y;
COLOR col;
std::string str;
int brt;
int handle;
};
struct LineProperty {
float sx;//start
float sy;
float ex;//end
float ey;
COLOR col;
int brt;
};
struct CircleProperty {
float cx;//S
float cy;
float r;//a
COLOR col;
int brt;
bool isFill;
};
struct BoxProperty {
float lx;
float ly;
float rx;
float ry;
COLOR col;
};
int _handle_font[ FONT_TYPE_MAX ];
int _blink;
int _colcode;
int _color_change_speed;
ImageProperty _back_image;
std::array< int, FONT_TYPE_MAX > _size;
std::list< StringProperty > _front_strings; //摜̏ɕ\
std::list< StringProperty > _back_strings; //摜̂ɕ\
std::list< ImageProperty > _images;
std::list< LineProperty > _lines;
std::list< CircleProperty > _circles;
std::list< BoxProperty > _boxes;
ColorPtr _color;
};
| true |
a647c80c08312dd72f423453d3e94e0c4a6e0d7c | C++ | ClickHouse/ClickHouse | /src/Storages/System/StorageSystemTableFunctions.cpp | UTF-8 | 1,251 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | #include <Storages/System/StorageSystemTableFunctions.h>
#include <TableFunctions/TableFunctionFactory.h>
#include <DataTypes/DataTypesNumber.h>
namespace DB
{
namespace ErrorCodes
{
extern const int UNKNOWN_FUNCTION;
}
NamesAndTypesList StorageSystemTableFunctions::getNamesAndTypes()
{
return
{
{"name", std::make_shared<DataTypeString>()},
{"description", std::make_shared<DataTypeString>()},
{"allow_readonly", std::make_shared<DataTypeUInt8>()}
};
}
void StorageSystemTableFunctions::fillData(MutableColumns & res_columns, ContextPtr, const SelectQueryInfo &) const
{
const auto & factory = TableFunctionFactory::instance();
const auto & functions_names = factory.getAllRegisteredNames();
for (const auto & function_name : functions_names)
{
res_columns[0]->insert(function_name);
auto properties = factory.tryGetProperties(function_name);
if (properties)
{
res_columns[1]->insert(properties->documentation.description);
res_columns[2]->insert(properties->allow_readonly);
}
else
throw Exception(ErrorCodes::UNKNOWN_FUNCTION, "Unknown table function {}", function_name);
}
}
}
| true |
113c6018ab1948b4e664193d35b8efc47dafa9d2 | C++ | Murami/rtype | /Server/src/Util/WindowDynamicFile.cpp | UTF-8 | 2,021 | 2.640625 | 3 | [] | no_license | #include <stdexcept>
#if defined (WIN32) || defined (_WIN32)
# include <iostream>
# include "WindowDynamicFile.hh"
namespace DynamicFile
{
WindowDynamicFile::WindowDynamicFile()
{
_isOpen = false;
}
WindowDynamicFile::WindowDynamicFile(const std::string& filename)
{
_isOpen = false;
_handle = LoadLibrary(filename.c_str());
if (_handle == NULL)
std::cerr << "Can't open the library " << filename << std::endl;
else
_isOpen = true;
}
WindowDynamicFile::~WindowDynamicFile()
{
if (_isOpen == true)
FreeLibrary(_handle);
}
void WindowDynamicFile::open(const std::string& filename)
{
if (_isOpen == true)
{
FreeLibrary(_handle);
_isOpen = false;
}
if ((_handle = LoadLibrary(TEXT(filename.c_str()))) == NULL)
{
char *str;
FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&str, 0, NULL);
std::cerr << "Can't open the library \"" << filename << "\"\n" << str << std::endl;
}
else
_isOpen = true;
}
void WindowDynamicFile::close()
{
if (_isOpen == true)
FreeLibrary(_handle);
_isOpen = false;
}
void* WindowDynamicFile::loadSymbol(const std::string& name)
{
void *res;
if (!_isOpen)
std::cerr << "You don't have an open file" << std::endl;
else
{
res = reinterpret_cast<void *>(GetProcAddress(_handle, TEXT(name.c_str())));
if (res == NULL)
{
char *str;
FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&str, 0, NULL);
std::cerr << "Can't load the symbol \"" << name << "\"\n" << str << std::endl;
}
else
return (res);
}
return (NULL);
}
}
#endif /* WIN32 */
| true |
6d2f90e7012f1cc9c295a7732f875a825d8a0d9c | C++ | pqnelson/last1120c-cc | /tests/ASTTests/ModifierTests.cc | UTF-8 | 442 | 2.953125 | 3 | [] | no_license | #include <gtest/gtest.h>
#include "AST/Modifier.h"
TEST(ModTest, Ctor)
{
Modifier mod;
ASSERT_EQ(mod.as_int(), 0);
}
TEST(ModTest, OrEq)
{
Modifier arg(Modifier::FuncArgs);
Modifier aut0(Modifier::Auto);
arg |= aut0;
ASSERT_EQ(arg.as_int(), 5);
}
TEST(ModTest, Is_)
{
Modifier mod(Modifier::FuncArgs);
ASSERT_TRUE(mod.is_func_arg());
ASSERT_FALSE(mod.is_auto());
ASSERT_FALSE(mod.is_none());
}
| true |
b6a1ce2a972b7e8bb9cd4c9861f7bd02c282bced | C++ | Arvy1998/Calculus-and-Play-with-New-Syntax | /Sorting_Array_LAB3.cpp | UTF-8 | 794 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
using namespace std;
int NuskaitytiSeka(int masyvas[], int &kiekis) {
cin >> kiekis;
for (auto i = 0; i < kiekis; i++) {
cin >> masyvas[i];
}
return *masyvas;
}
void SurikiuotiElementus(int masyvas[], int &kiekis) {
int i, j, temp;
for (i = 1; i < kiekis; i++) {
j = i;
while (j > 0 && masyvas[j - 1] < masyvas[j]) {
temp = masyvas[j];
masyvas[j] = masyvas[j - 1];
masyvas[j - 1] = temp;
j--;
}
}
}
void SpausdintiRezultatus(int masyvas[], int kiekis) {
for (auto j = 0; j < kiekis; j++) {
cout << masyvas[j] << " ";
}
}
int main() {
ios::sync_with_stdio(0);
int masyvas[10000];
int kiekis;
NuskaitytiSeka(masyvas, kiekis);
SurikiuotiElementus(masyvas, kiekis);
SpausdintiRezultatus(masyvas, kiekis);
return 0;
}
| true |
c4211e5499b1d3abf1f730dc00b4638b147d2f38 | C++ | RubensPetrovich/ELEC4cpp | /tp1nico/histogram.cpp | UTF-8 | 2,019 | 3.484375 | 3 | [] | no_license | //
// header-start
//////////////////////////////////////////////////////////////////////////////////
//
// \file histogram.cpp
//
// \brief TP1 histogram
//
// \author Doens Nicolas
//
//////////////////////////////////////////////////////////////////////////////////
// header-log
//
// $Author$
// $Date$
// $Revision$
//
//////////////////////////////////////////////////////////////////////////////////
// header-end
//
//
// Compiled with g++ 5.3.0 (MSYS2 project)
//
// g++ -std=c++14 -O3 -o histogram histogram.cpp
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
#include <algorithm>
using std::string;
using std::vector;
// Read from a file a set of numbers (double format)
// compute a running mean value
// compute the median after sort
//
int main(int argc, char *argv[]) {
string file_name{argv[1]}; //On récupère le nom du fichier;
vector<double> buf; //Vecteur qui va contenir les valeurs lus dans le fichier (doubles);
std::ifstream fin(file_name, std::ios::in); //Ouverture en mode LECTURE.
string line;
auto mean = 0.0; //Moyenne
while (std::getline(fin, line)) { //Parcour du fichier ligne par ligne;
auto d = std::stod(line); //String => double;
buf.push_back(d); //Ajout de la valeur a la fin du vecteur;
mean = (buf.size() == 1) ? d : mean + (d - mean) / buf.size(); //Calcul de la moyenne.
}
std::sort(buf.begin(), buf.end()); //Triage du vecteur
auto mid = buf.size() / 2; //Calcul de la mediane
double median = (buf.size() % 2) ? buf[mid] : (buf[mid - 1] + buf[mid]) / 2; //
std::cout << "number of elements = " << buf.size()
<< ", median = " << median << ", mean = " << mean << std::endl;
//Histogramme :
}
| true |
4117091ac7d4b8939cc5479be349e28b1363f2d3 | C++ | nerzhul250/Marathons | /cppProblems/Conservation.cpp | UTF-8 | 1,688 | 2.578125 | 3 | [] | no_license | #include <bits/stdc++.h>
#define ff first
#define ss second
#define fore(i,a,b) for(int i=a,colchin=b;i<colchin;++i)
#define pb push_back
#define ALL(s) s.begin(),s.end()
#define FIN ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define SZ(s) int(s.size())
using namespace std;
typedef long long int ll;
typedef pair<int,int> ii;
const int MAXN=100005;
int labos[MAXN];
vector<int> g[MAXN];
int n,m;
vector<int> tsort(int s){ // lexicographically smallest topological sort
vector<int> r;
multiset<ii> q;
vector<int> d(2*n,0);
fore(i,0,n)fore(j,0,g[i].size())d[g[i][j]]++;
fore(i,0,n)if(!d[i])q.insert(ii(labos[i],i));
while(!q.empty()){
int x=0;
if(r.size()==0){
if(s==0){
x=q.begin()->ss;
r.pb(q.begin()->ff);
q.erase(q.begin());
}else if(s==1){
x=q.rbegin()->ss;
r.pb(q.rbegin()->ff);
q.erase(next(q.rbegin()).base());
}
}else{
if(r.back()==q.begin()->ff){
x=q.begin()->ss;
r.pb(q.begin()->ff);
q.erase(q.begin());
}else{
x=q.rbegin()->ss;
r.pb(q.rbegin()->ff);
q.erase(next(q.rbegin()).base());
}
}
fore(i,0,g[x].size()){
d[g[x][i]]--;
if(!d[g[x][i]])q.insert(ii(labos[g[x][i]],g[x][i]));
}
}
return r; // if not DAG it will have less than n elements
}
int minimoS(int s){
vector<int> r=tsort(s);
int minimo=0;
int prev=r[0];
fore(i,0,r.size()){
if(r[i]!=prev){
minimo++;
prev=r[i];
}
}
return minimo;
}
int main(){FIN;
int t;
cin >> t;
while(t--){
cin >> n >> m;
fore(i,0,n){
cin >> labos[i];
g[i].clear();
}
fore(i,0,m){
int u,v;
cin >> u >> v;
u--;
v--;
g[u].pb(v);
}
cout << min(minimoS(0),minimoS(1))<<"\n";
}
return 0;
}
| true |
ed78005b75661b60c87a7af7bdde7c7b3f3279ad | C++ | wyx150137/wyx-infinity37-ac-code-on-BZOJ | /3613_37.cpp | UTF-8 | 753 | 2.546875 | 3 | [] | no_license |
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
using namespace std;
int mod;
typedef long long LL;
const int N = 5000005;
int a[N],sa,sb,sc,sd,n;
int F(int x)
{
LL ans = 0;
LL x2 = (LL)x*x%mod;LL x3 = x2*x%mod;
ans = (((ans+(LL)sa*x3%mod)%mod+(LL)sb*x2%mod)%mod+(LL)sc*x%mod)%mod+sd;
ans = ans%mod;
return ans;
}
bool judge(int b)
{
int mx = 1;
for(int i = 1;i<= n;i++)
{
mx = max(mx,a[i]-b);
if(mx>a[i]+b)return false;
}
return true;
}
int main()
{
scanf("%d%d%d%d%d%d%d",&n,&sa,&sb,&sc,&sd,&a[1],&mod);
for(int i = 2;i<= n;i++)
a[i] = (F(a[i-1])+F(a[i-2]))%mod;
int l = 0,r = mod+1;
while(l<r)
{
int mid = (l+r)>>1;
if(judge(mid))r = mid;
else l = mid+1;
}
printf("%d\n",l);
return 0;
}
| true |
25052cdc611274965eedaf9339f5ce0731d3932d | C++ | kaulszhang/base | /include/util/serialization/NVPair.h | GB18030 | 1,633 | 2.890625 | 3 | [] | no_license | // NVPair.h
#ifndef _UTIL_SERIALIZATION_NV_PAIR_H_
#define _UTIL_SERIALIZATION_NV_PAIR_H_
#include "util/serialization/Serialization.h"
namespace util
{
namespace serialization
{
template <typename T> // TǷconst
struct NVPair
: wrapper
{
char const * name_;
T & t_;
NVPair(
char const * name,
T & t)
: name_(name)
,t_(t)
{
}
T const & const_data() const
{
return t_;
}
T & data() const
{
return t_;
}
char const * name() const
{
return name_;
}
/// ֧nvpֱлֵ
template <typename Archive>
void serialize(Archive & ar)
{
ar & t_;
}
};
/// Ӷ鹹array
template<class T>
NVPair<T> const make_nvp(
char const * name,
T const & t)
{
return NVPair<T>(name, const_cast<T &>(t));
}
} // namespace serialize
} // namespace util
#define STRINGLIZE(s) #s
#define SERIALIZATION_NVP(v) \
util::serialization::make_nvp(STRINGLIZE(v), v)
#define SERIALIZATION_NVP_NAME(n, v) \
util::serialization::make_nvp(n, v)
#define SERIALIZATION_NVP_1(t, v) \
util::serialization::make_nvp(STRINGLIZE(v), t.v)
#endif // _UTIL_SERIALIZATION_NV_PAIR_H_
| true |
341d079b0554eb7db8591fa425137e641a891256 | C++ | kimeyongchan/MobileStar | /Client/MobileStar/Classes/GameMap.cpp | UTF-8 | 7,102 | 2.671875 | 3 | [] | no_license | #include "GameMap.h"
#include "NavGraphNode.h"
//생성자
GameMap::GameMap()
: m_pNavGraph(NULL)
, m_pCellSpace(NULL)
, m_iTileX(0)
, m_iTileY(0)
, m_fCellSpaceNeighborhoodRange(1024)
{
}
//소멸자
GameMap::~GameMap()
{
Clear();
}
//맵에서 로드된 것들을 삭제한다.
void GameMap::Clear()
{
//NavGraph를 제거한다.
delete m_pNavGraph;
//CellSpace를 제거한다.
delete m_pCellSpace;
}
//맵을 불러온다.
bool GameMap::LoadMap(int tileX,int tileY)
{
Clear();
m_pNavGraph = new SparseGraph(tileX, tileY);
//맵을 임시로 생성한다.
m_iTileX = tileX;
m_iTileY = tileY;
//타일 생성
for(int i=0;i<m_iTileY;i++){
for(int j=0;j<m_iTileX;j++){
auto tile = new TileNode();
tile->setPosition(Vec2((j-i) * TILE_WIDTH_SIZE / 2,(j+i) * TILE_HEIGHT_SIZE / 2));
addChild(tile);
m_Tiles.push_back(tile);
}
}
//노드 생성
if(DIVIDE_NODE){
for(int i=0;i<m_iTileY*2;i++){
for(int j=0;j<m_iTileX*2;j++){
NavGraphNode node;
node.setPosition(Vec2((j-i) * (TILE_WIDTH_SIZE/2) / 2,(j+i) * (TILE_HEIGHT_SIZE/2) / 2 - TILE_HEIGHT_SIZE / 4));
m_pNavGraph->AddNode(node);
}
}
}else{
for(int i=0;i<m_iTileY;i++){
for(int j=0;j<m_iTileX;j++){
NavGraphNode node;
node.setPosition(Vec2((j-i) * TILE_WIDTH_SIZE / 2,(j+i) * TILE_HEIGHT_SIZE / 2));
m_pNavGraph->AddNode(node);
}
}
}
//임시 타일 스프라이트
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
auto pTile = Sprite::create("Texture/TileW.png");
pTile->setAnchorPoint(Vec2(0.5f,0));
pTile->setPosition(Vec2((j-i) * 1280 / 2,(j+i) * 640 / 2) + Vec2(0,-32));
addChild(pTile);
}
}
if(DIVIDE_NODE) {
// for(int i=0;i<m_iTileY*2;i++){
// for(int j=0;j<m_iTileX*2;j++){
// auto pTile = Sprite::create("Texture/DivideTile.png");
// pTile->setPosition(m_pNavGraph->GetNode(i*m_iTileX*2 + j).getPosition());
//
// addChild(pTile);
// }
// }
}else{
// for(int i=0;i<m_iTileY;i++){
// for(int j=0;j<m_iTileX;j++){
// auto pTile = Sprite::create("Texture/Tile.png");
// pTile->setPosition(m_pNavGraph->GetNode(i*m_iTileX + j).getPosition());
// addChild(pTile);
// }
// }
}
m_pNavGraph->AddAllEdgeFromPresentNode();
PartitionNavGraph();
return false;
}
//미리 계산되어 있는 비용 테이블에서 비용을 가져온다.
float
GameMap::CalculateCostToTravelBetweenNodes(int nd1, int nd2)const
{
assert (nd1>=0 && nd1<m_pNavGraph->NumNodes() &&
nd2>=0 && nd2<m_pNavGraph->NumNodes() &&
"<GameMap::CalculateCostToTravelBetweenNodes>: invalid index");
return m_PathCosts[nd1][nd2];
}
int GameMap::GetTileIndexFromPosition(const Vec2& position){
if(DIVIDE_NODE){
Vec2 MovePos = position;
int tileX = (MovePos.x / (TILE_WIDTH_SIZE/4) + MovePos.y / (TILE_HEIGHT_SIZE/4)) / 2;
int tileY = ((MovePos.y / (TILE_HEIGHT_SIZE/4) - (MovePos.x / (TILE_WIDTH_SIZE/4))) / 2 + 1);
int Index = tileY * (m_iTileX*2) + tileX;
Index++;
if(Index < 0 || Index >= m_pNavGraph->NumNodes())
return -1;
else
return Index;
}else{
Vec2 MovePos = position + Vec2(0,TILE_HEIGHT_SIZE/2);
int tileX = (MovePos.x / (TILE_WIDTH_SIZE/2) + MovePos.y / (TILE_HEIGHT_SIZE/2)) / 2;
int tileY = (MovePos.y / (TILE_HEIGHT_SIZE/2) - (MovePos.x / (TILE_WIDTH_SIZE/2))) / 2;
int Index = tileY * m_iTileX + tileX;
if(Index < 0 || Index >= m_pNavGraph->NumNodes())
return -1;
else
return Index;
}
}
//해당 위치로부터 가장 가까운 유효화된 노드 인덱스를 구한다.
int GameMap::GetClosestValidNodeFromPosition(Vec2 pos){
double ClosestSoFar = MathMgr->MaxDouble;
int ClosestNode = -1;
//셀 이웃 탐색 Range를 얻어온다.
const float range = GetCellSpaceNeighborhoodRange();
//셀 공간에서 이웃들을 계산한다.
GetCellSpace()->CalculateNeighbors(pos, range);
//이웃들을 순회하면서 가까운 노드를 찾는다.
for (NavGraphNode* pN = GetCellSpace()->begin();
!GetCellSpace()->end();
pN = GetCellSpace()->next())
//SparseGraph::NodeIterator NodeItr(*m_pNavGraph);
//for (NavGraphNode* pN=NodeItr.begin();!NodeItr.end();pN=NodeItr.next())
{
if(!pN->IsEmpty()) continue;
float dist = Vec2DistanceSq(pos, pN->getPosition());
//가장 가까운 거리와 노드 인덱스를 저장해둔다.
if (dist < ClosestSoFar)
{
ClosestSoFar = dist;
ClosestNode = pN->GetIndex();
}
}
return ClosestNode;
}
//공간을 분할한다.
void GameMap::PartitionNavGraph()
{
if (m_pCellSpace) delete m_pCellSpace;
m_pCellSpace = new CellSpace<NavGraphNode*>(TILE_WIDTH_SIZE * TILE_WIDTH_NUM, TILE_HEIGHT_SIZE * TILE_HEIGHT_NUM, TILE_WIDTH_NUM / 4, TILE_HEIGHT_NUM / 4, m_pNavGraph->NumNodes());
//셀 공간에 노드를 집어 넣는다.
SparseGraph::NodeIterator NodeItr(*m_pNavGraph);
for (NavGraphNode* pN=NodeItr.begin();!NodeItr.end();pN=NodeItr.next())
{
m_pCellSpace->AddObject(pN);
}
}
std::list<int> GameMap::GetIndicesFromTileIndex(int iTileIndex, int iDistance){
int tileX = (DIVIDE_NODE) ? m_iTileX * 2 : m_iTileX;
std::list<int> IndexList;
for(int i=-iDistance;i<=iDistance;i++){
for(int j=-iDistance;j<=iDistance;j++){
int CurrentTileIndex = iTileIndex + i * tileX + j;
//만약 내 타일이면 제외시킨다.
if(iTileIndex == CurrentTileIndex)
continue;
//세로로 음수줄이거나 최대치를 넘은 줄이면 제외시킨다.
if(iTileIndex + i * tileX >= m_pNavGraph->NumNodes() || iTileIndex + i * tileX < 0)
continue;
//화면 옆으로 삐져나갈 경우 제외시킨다.
if(CurrentTileIndex < (iTileIndex + i*tileX) / tileX * tileX || CurrentTileIndex >= ((iTileIndex + i*tileX) / tileX + 1) * tileX )
continue;
//인덱스가 음수이거나 최대치를 넘으면 제외시킨다.
if(CurrentTileIndex < 0 || CurrentTileIndex >= m_pNavGraph->NumNodes())
continue;
IndexList.push_back(CurrentTileIndex);
}
}
return IndexList;
}
| true |
1cfe864053280c466c2ea7c883d2dac89ced1570 | C++ | richard-stern/13PeoplesSky | /13PeoplesSky/project2D/TextureManager.cpp | UTF-8 | 1,776 | 3.40625 | 3 | [
"MIT"
] | permissive | #include "TextureManager.h"
// initialise the instance to nullptr so we know it hasn't been created
TextureManager* TextureManager::m_instance = nullptr;
TextureManager::TextureManager() { }
TextureManager::~TextureManager()
{
// delete all the textures
for (auto pair : m_textures)
delete pair.second;
// and all the fonts
for (auto pair : m_fonts)
delete pair.second;
}
TextureManager* TextureManager::GetInstance()
{
return m_instance;
}
void TextureManager::Create()
{
// we never want to create more than one!
if (m_instance)
return;
m_instance = new TextureManager();
}
void TextureManager::Destroy()
{
delete m_instance;
m_instance = nullptr;
}
// grabs a texture based on a file name by checking if it already exists in
// the map, and if not it creates it and stores it
aie::Texture* TextureManager::LoadTexture(std::string fileName)
{
// auto here so I don't have to type out the whole iterator type
auto foundTexture = m_textures.find(fileName);
// check if the texture exists
if (foundTexture == m_textures.end())
{
// texture doesn't exist, let's create it
m_textures[fileName] = new aie::Texture(fileName.c_str());
}
// texture SHOULD exist in the map now!
return m_textures[fileName];
}
aie::Font* TextureManager::LoadFont(std::string fileName,
unsigned short fontSize)
{
// stick the font size onto the end of the file name as the key
std::string key = fileName + std::to_string(fontSize);
auto foundFont = m_fonts.find(key);
// check if the font exists
if (foundFont == m_fonts.end())
{
// font doesn't exist! let's create it
m_fonts[key] = new aie::Font(fileName.c_str(), fontSize);
}
// font should exist!
return m_fonts[key];
} | true |
7d4e5a7c2f2057bab2204401d4769e14c4d0e9b0 | C++ | antoni-heredia/ED-COMPARTIDO | /Practica2/include/Vector_Dinamico.tpp | UTF-8 | 1,794 | 3.359375 | 3 | [
"MIT"
] | permissive | #ifndef VectorDinamico_tpp
#define VectorDinamico_tpp
#include <cassert>
template <class T>
Vector_Dinamico<T>::Vector_Dinamico(int n){
assert(n>=0);
if (n>0)
datos = new T[n];
nelementos = n;
}
template <class T>
Vector_Dinamico<T>::Vector_Dinamico(const Vector_Dinamico<T> & original){
nelementos = original.nelementos;
if(nelementos>0){
datos = new T[nelementos];
for(int i=0; i<nelementos; i++)
datos[i] = original.datos[i];
}
else
nelementos = 0;
}
template <class T>
Vector_Dinamico<T>::~Vector_Dinamico(){
if (nelementos>0)
delete []datos;
}
template <class T>
int Vector_Dinamico<T>::size() const{
return nelementos;
}
template <class T>
void Vector_Dinamico<T>::resize(int n){
assert(n>=0);
if(n != nelementos){
if (n!=0){
T* nuevos_datos = new T[n];
if (nelementos>0){
int minimo = n<nelementos?n:nelementos;
for(int i=0; i<minimo; i++)
nuevos_datos[i] = datos[i];
delete[] datos;
}
nelementos = n;
datos = nuevos_datos;
}
else{ //Si n==0
if(nelementos>0)
delete[] datos;
datos = 0;
nelementos=0;
}
}
}
template <class T>
T& Vector_Dinamico<T>::operator[](const int i){
assert(i>=0 && i<nelementos);
return datos[i];
}
template <class T>
const T& Vector_Dinamico<T>::operator[](const int i)const{
assert(i>=0 && i<nelementos);
return datos[i];
}
template <class T>
Vector_Dinamico<T>& Vector_Dinamico<T>::operator=(const Vector_Dinamico<T> &original){
if (this != &original)
if (nelementos>0)
delete[] datos;
nelementos = original.nelementos;
if (nelementos>0){
datos = new T[nelementos];
for(int i=0; i<nelementos; i++)
datos[i] = original.datos[i];
}
return *this;
}
#endif
| true |
d7dd810328d567e006a51b82a5606b28e827d3ed | C++ | MajaGruca/CppClass | /lab3/smarttree/SmartTree.cpp | UTF-8 | 3,201 | 3.484375 | 3 | [] | no_license | //
// Created by ktr on 18.03.2017.
//
#include "SmartTree.h"
#include <sstream>
#include <string>
#include <memory>
namespace datastructures{
std::unique_ptr <SmartTree> CreateLeaf(int value)
{
std::unique_ptr<SmartTree> leaf = std::make_unique<SmartTree>();
leaf->value=value;
leaf->left= nullptr;
leaf->right= nullptr;
return leaf;
}
std::unique_ptr <SmartTree> InsertLeftChild(std::unique_ptr<SmartTree> tree, std::unique_ptr<SmartTree> left_subtree)
{
if(tree!= nullptr)
{
if(tree->left== nullptr)
{
tree->left=std::move(left_subtree);
return std::move(tree);
}
}
return nullptr;
}
std::unique_ptr <SmartTree> InsertRightChild(std::unique_ptr<SmartTree> tree, std::unique_ptr<SmartTree> right_subtree)
{
if(tree!= nullptr)
{
if(tree->right== nullptr)
{
tree->right=std::move(right_subtree);
return std::move(tree);
}
}
return nullptr;
}
void PrintTreeInOrder(const std::unique_ptr<SmartTree> &unique_ptr, std::ostream *out)
{
if(unique_ptr->left!= nullptr)
{
PrintTreeInOrder( unique_ptr->left,out);
}
*out << unique_ptr->value<<", ";
if(unique_ptr->right!= nullptr)
{
PrintTreeInOrder( unique_ptr->right,out);
}
}
std::string DumpTree(const std::unique_ptr<SmartTree> &tree)
{
std::string str;
str += "["+std::to_string(tree->value)+" ";
if(tree->left!= nullptr)
str+=DumpTree(tree->left);
else
str+= "[none]";
str+=" ";
if(tree->right!= nullptr)
str+=DumpTree(tree->right);
else
str+= "[none]";
str+="]";
return str;
}
std::unique_ptr <SmartTree> RestoreTree(const std::string &tree)
{
std::string temp,value;
int it_value=0;
temp=tree.substr(1,tree.length()-2);
while (isdigit(temp[it_value]) || temp[it_value]=='-')
{
value+=temp[it_value];
it_value++;
}
if(value!="")
{
std::string left,right;
int it_left=-1,iter=0,l=0;
while(temp[iter]!='\0' && it_left!=0)
{
if(temp[iter]=='[')
{
if(it_left<0)
it_left=1;
else
it_left++;
if(l==0)
l=iter;
}
else
{
if (temp[iter] == ']')
it_left--;
}
iter++;
}
left=temp.substr(l,iter-value.length()-1);
right=temp.substr(iter+1,temp.length()-iter);
auto root = CreateLeaf(std::atoi(value.c_str()));
root->left = RestoreTree(left);
root->right = RestoreTree(right);
return root;
}
else
return nullptr;
}
} | true |
aba07e0ae169b242b9fe79f7f6add8b946e70c60 | C++ | ZhenyingZhu/ClassicAlgorithms | /src/CPP/src/leetcode/NQueens.cpp | UTF-8 | 3,706 | 3.421875 | 3 | [] | no_license | /*
* [Source] https://leetcode.com/problems/n-queens/
* [Difficulty]: Hard
* [Tag]: Backtracking
*/
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// [Solution]: Use a vector of int to indicate how previous queens locate. Then place queens to available positions.
// [Corner Case]:
class Solution {
private:
vector<bool> computeValidSlots(const vector<int>& prevRows, const int curRow, const int n) {
vector<bool> availableSlots(n, true);
for (int preRow = 0; preRow < (int)prevRows.size(); ++preRow) {
int pos = prevRows[preRow];
availableSlots[pos] = false;
int diff = curRow - preRow;
if (pos - diff >= 0)
availableSlots[pos - diff] = false;
if (pos + diff < n)
availableSlots[pos + diff] = false;
}
return availableSlots;
}
vector<string> generateRes(const vector<int>& rows, const int n) {
vector<string> res;
for (const int& i : rows) {
string row(n, '.');
row[i] = 'Q';
res.push_back(row);
}
return res;
}
void nQueensHelper(int row, const int n, vector<int>& prevRows, vector<vector<string>>& reses) {
if (row == n) {
reses.push_back(generateRes(prevRows, n));
return;
}
vector<bool> availableSlots = computeValidSlots(prevRows, row, n);
for (int i = 0; i < n; ++i) {
if (!availableSlots[i])
continue;
prevRows.push_back(i);
nQueensHelper(row + 1, n, prevRows, reses);
prevRows.pop_back();
}
}
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> reses;
if (n <= 0)
return reses;
vector<int> prevRows;
nQueensHelper(0, n, prevRows, reses);
return reses;
}
};
/* Java solution
https://github.com/ZhenyingZhu/ClassicAlgorithms/blob/master/src/algorithms/arrandstring/N-QueensSolution.java
*/
/* Java solution
public class Solution {
public List<String[]> solveNQueens(int n) {
List<String[]> result=new ArrayList<String[]>();
if(n<=0) return result;
int[] positions=new int[n];
solveNQueens(positions, 0, result);
return result;
}
public void solveNQueens(int[] positions, int idx, List<String[]> result){
if(idx==positions.length){
String[] solution=createStringList(positions);
result.add(solution);
}
int[] col=new int[positions.length];
for(int i=0; i<idx; i++){
int vertical=positions[i];
col[vertical]=-1;
int offset=idx-i;
if((vertical-offset)>=0) col[vertical-offset]=-1;
if((vertical+offset)<col.length) col[vertical+offset]=-1;
}
for(int i=0; i<col.length; i++){
if(col[i]!=-1){
int[] prev=copy(positions, idx);
prev[idx]=i;
solveNQueens(prev, idx+1, result);
}
}
}
public int[] copy(int[] array, int idx){
int[] result=new int[array.length];
for(int i=0; i<idx; i++){
result[i]=array[i];
}
return result;
}
public String[] createStringList(int[] positions){
String[] result=new String[positions.length];
for(int i=0; i<positions.length; i++){
int pos=positions[i];
StringBuffer row=new StringBuffer();
for(int j=0; j<positions.length; j++){
if(j!=pos) row.append('.');
else row.append('Q');
}
result[i]=row.toString();
}
return result;
}
}
*/
int main() {
Solution sol;
vector<vector<string>> res = sol.solveNQueens(4);
for (const vector<string>& v : res) {
for (const string& s : v)
cout << s << endl;
cout << endl;
}
return 0;
}
| true |
2abdc0cdc21d58889809414e8db22960f8e72f5b | C++ | kidlatmc29/cs2430 | /pas/pa4/pa4.cpp | UTF-8 | 1,644 | 3.828125 | 4 | [] | no_license | // Ovalles, Isabel
// pa4.cpp
// 11-2-2020
// DESCRIPTION: Pa 4 creates a Word Heap on a user given size. It is filled up
// with words given by the user as well. Then it prints out the children of
// a given key. Following that, testing for class functions and then the heaps
// are emptied.
// SOURCES: Textbook code examples pg 50, 250, figure 6.8
#include <iostream>
#include "heap.h"
using namespace std;
int main()
{
WordHeap sentence;
WordHeap copySentence;
int numOfVals;
string input;
cout << endl << "Welcome to PA 4" << endl;
cout << "Created WordHeap sentence..." << endl;
cout << "How many values do you want to add to the heap? ";
cin >> numOfVals;
for(int i = 0; i < numOfVals; i++) {
cout << "Enter a word you want to add: ";
cin >> input;
sentence.insert(input);
}
cout << endl << "What value do you want to print the children of?: ";
cin >> input;
sentence.printChildren(input);
// test copy constructor
cout << endl << "Creating WordHeap s2 sentence using copy constructor...."
<< endl;
WordHeap s2(sentence);
cout << endl <<"Removing three words from s2 using deleteMax...." << endl;
for(int i = 0; i < 3; i++) {
cout << s2.deleteMax() << endl;
}
cout << endl << "Creating WordHeap copySentence from s2 using copy assignment...."
<< endl;
copySentence = s2;
cout << "Emptying sentence: " << endl;
sentence.makeEmpty();
cout << endl << "Emptying s2: " << endl;
s2.makeEmpty();
cout << endl << "Emptying copySentence: " << endl;
copySentence.makeEmpty();
cout << endl << "End of PA 4" << endl << endl;
return 0;
} | true |
359d5b8b8961983cfce7824da8c6df7f042e86b8 | C++ | jysandy/exoredis | /binary_string.cpp | UTF-8 | 773 | 2.75 | 3 | [] | no_license | #include "binary_string.hpp"
binary_string::binary_string()
: expiry_set_(false)
{
}
binary_string::binary_string(const std::vector<unsigned char>& bdata)
: expiry_set_(false), bdata_(bdata)
{
}
binary_string::binary_string(const std::vector<unsigned char>& bdata,
long long expiry_milliseconds)
: bdata_(bdata), expiry_set_(true)
{
expiry_time_ = chrono::system_clock::now()
+ chrono::milliseconds(expiry_milliseconds);
}
const std::vector<unsigned char>& binary_string::bdata() const
{
return bdata_;
}
std::vector<unsigned char>& binary_string::bdata()
{
return bdata_;
}
bool binary_string::has_expired() const
{
if (!expiry_set_)
{
return false;
}
return expiry_time_ < chrono::system_clock::now();
}
| true |
c84252427c648f946be0c5986e39b83e3c9b7642 | C++ | EsauPR/NeuralNetwork-ModeladoFuncionesBooleanas-RedMadaline | /src/ModeladoFunciones.cpp | UTF-8 | 5,178 | 2.890625 | 3 | [] | no_license | /*
Modelado de Funciones Booleanas
@author Oscar Esaú Peralta Rosales
@email esau.opr@gmail.com
*/
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <string.h>
#include <time.h>
#include "processInput.cpp"
using namespace std;
void readParams( int *T, double *miu, double *factorMiu ); // Read algorithm parameters
void help(); // Show the program help
vector<double> steepestDescent( vector<vector<double> > X, int T, int N, int P, double miu ); // Adjusting weights by steepest Descent
vector<vector<double> > construcPoints( vector<double> a );
vector<double> orientacion( vector<double> W, vector<double> xi, int ori );
double evalua( vector<double> W, vector<double> xi );
bool evaluaRed( vector<vector<double> > cIn, vector<double> cOut, vector<double> xi );
int main(int argc, char const *argv[]) {
int nCin = 0;
int P;
double miu = 0.000005;
vector<vector<double> > X; // Data input, the las element of the each row i represents the value di
vector<double> W; // Weights
vector<vector<double> > points;
vector<vector<double> > cIn;
vector<double> cOut;
if ( argc < 2 ) {
printf("Error: Enter a input file as argument\n");
help();
exit( EXIT_FAILURE );
}
srand(time(NULL));
X = readInput( argv[1]);
printVec(X);
P = X[0].size() - 1;
// Capa de entrada
for (int i = 0; i < X.size(); i++) {
if( X[i][P] == 1.0 ) {
nCin ++;
points = construcPoints( X[i] );
puts("Puntos");
printVec( points );
W = steepestDescent( points, 1, points.size(), P, miu );
W = orientacion( W, X[i], 1 );
cIn.push_back( W );
}
}
// Capa de Salida
vector<double> xi;
xi.push_back(1);
for (int i = 1; i < P ; i++) {
xi.push_back( -1.0 );
}
xi.push_back(1);
points = construcPoints( xi );
puts("Puntos");
printVec( points );
cOut = steepestDescent( points, 1, 1, P, miu );
cOut = orientacion( cOut, xi, -1 );
// Imprimiendo Solución
puts("Capa de entrada:");
printf("Número de Neuronas: %d\n", cIn.size() );
for (int i = 0; i < cIn.size(); i++) {
printf("Neurona %i:\n", i+1);
printVec( cIn[i] );
}
puts("\nCapa de Salida:");
printf("Neurona 1:\n");
printVec( cOut );
puts("\nEvaluación de la Red");
for (int i = 0; i < X.size(); i++) {
evaluaRed(cIn, cOut, X[i]);
}
exit(EXIT_SUCCESS);
}
// Adjusting weights by steepest Descent
vector<double> steepestDescent( vector<vector<double> > X, int T, int N, int P, double miu ) {
vector<double> W; // Solution weights
W.resize( P );
for (int i = 0; i < P; i++) {
//W[i] = 2 - ( ( rand() % 2 ) == 0 ) ? 1 : -1;
W[i] = 2 - (long double)( rand() % 10 ) / 5.0;
}
for (int t = 0; t < T; t++) {
for (int m = 0; m < N; m++) {
// Getting the error of each xi
double error = 0.0;
for (int i = 0; i < P; i++) {
error += W[i] * X[m][i];
}
// The las element of the each row of X represents the value di
error = X[m][P] - error;
// Computing the gradient
vector<double> D_Wm;
D_Wm.resize( P );
for (int i = 0; i < P; i++) {
D_Wm[i] = 2 * error * X[m][i] * miu;
}
for (int i = 0; i < P; i++) {
W[i] += D_Wm[i];
}
}
}
return W;
}
vector<vector<double> > construcPoints( vector<double> a ) {
vector<vector<double> > X;
int d = a.size();
a[d-1] = 0;
double inc;
for (int i = 1; i < d - 1; i++) {
if ( a[i] == -1.0 ) {
inc = 1;
}
else {
inc = -1;
}
a[i] += inc;
X.push_back( a );
a[i] -= inc;
}
return X;
}
double evalua( vector<double> W, vector<double> xi ) {
double sum = 0.0;
for (int i = 0; i < W.size(); i++) {
sum += W[i] * xi[i];
}
return sum;
}
vector<double> orientacion( vector<double> W, vector<double> xi, int ori ) {
double sum = evalua( W, xi );
if( ori == 1 && sum < 0 || ori == -1 && sum > 0 ) {
for (int i = 0; i < W.size(); i++) {
W[i] *= -1;
}
}
return W;
}
bool evaluaRed( vector<vector<double> > cIn, vector<double> cOut, vector<double> xi ) {
vector<double> xn;
xn.push_back( 1.0 );
for (int i = 0; i < cIn.size(); i++) {
double sum = evalua( cIn[i], xi);
//printVec(xi);
//printf("Sum %d: %lf\n", i+1, sum );
if ( sum > 0 ) {
xn.push_back( 1.0 );
}
else {
xn.push_back( -1.0 );
}
}
double sum = evalua( cOut, xn );
for (int j = 1; j < xi.size() - 1; j++) {
printf("%2d ", (int)xi[j] );
}
if( sum > 0 ) {
printf("=> 1\n");
}
else {
printf("=> -1\n");
}
}
// Show the program help
void help() {
printf("\nHow to use:\n");
printf("\n\tSteepestDescent [file_input]\n" );
}
| true |
aab3655cc5cb2d6821efd75d29df0be37023eb20 | C++ | KEN8111git/cpp-practice | /main.cpp | UTF-8 | 895 | 3.34375 | 3 | [] | no_license | #include "subclass.hpp"
using namespace std;
int main()
{
int input1, input2;
string mathtype;
string confirm = "yes";
while (confirm == "yes")
{
cout << "What would you do? [add, subtract, multiply, divide]";
cin >> mathtype;
cout << "type the value";
cin >> input1 >> input2;
if (mathtype == "add")
{
cout << calculation::add(input1, input2) << "\n";
}
else if (mathtype == "subtract")
{
cout << calculation::subtract(input1, input2) << "\n";
}
else if (mathtype == "multiply")
{
cout << calculation::multiple(input1, input2) << "\n";
}
else if (mathtype == "divide")
{
cout << calculation::multiple(input1, input2) << "\n";
}
else
{
cout << "invalid type.\n";
return 1;
}
cout << "continue? [yes/no]";
cin >> confirm;
}
if (confirm == "no")
return 0;
} | true |
1417642ea89d87cf0284d9a73a9587da01ecee3e | C++ | aSimpleUsername/weatherLog | /classes/date/date.h | UTF-8 | 2,488 | 3.703125 | 4 | [] | no_license | // date.h - date class declaration
// author Connor Nicholson - 28 APR 20
#ifndef DATE_H
#define DATE_H
#include <string>
#include <sstream>
/**
* @class Date
* @brief Creates Date object
*
*
* @author Connor Nicholson
* @version 03
* @date 28/04/2020
*
* @todo Nil
* @bug Nil
*
*/
class Date {
public:
/**
*@brief default constructor
*/
Date();
/**
*@brief constructor
*@param construct a Date with day of the month, month and year
*/
Date(int day, int month, int year);
/**
* @brief construct a date from string dd/mm/yyyy
* @param date as a string
*/
Date(std::string date);
/**
*@brief sets day
*@param the new day value
*/
void setDay(int day);
/**
*@brief gets day
*@return returns day
*/
int getDay() const;
/**
*@brief sets month
*@param the new month value
*/
void setMonth(int month);
/**
*@brief gets month
*@return returns month
*/
int getMonth() const;
/**
*@brief sets year
*@param the new year value
*/
void setYear(int day);
/**
*@brief gets year
*@return returns year
*/
int getYear() const;
/**
*@brief converts date into string
*@return returns date as string
*/
std::string getDateString() const;
/**
*@brief Assignment operator declaration
*@param the date as a string 'dd/mm/yyy/
*/
Date& operator=(const std::string &date);
/**
*@brief less than operator declaration
*@param date object to compare
*/
bool operator<(const Date& other);
/**
*@brief greater than operator declaration
*@param date object to compare
*/
bool operator>(const Date& other);
/**
*@brief equal to operator declaration
*@param date object to compare
*/
bool operator==(const Date& other);
/**
*@brief not equal to than operator declaration
*@param date object to compare
*/
bool operator!=(const Date& other);
/**
*@brief Returns the month as a string
*@return month as a string
*/
static std::string getMonthString(int month);
private:
int m_day;
int m_month;
int m_year;
};
#endif
| true |
792ecaaa0fd83a6731f52db35422513ccf695e2c | C++ | MyCodingLair/arduinoMazeRunner | /mazeRunner2.ino | UTF-8 | 5,641 | 2.90625 | 3 | [] | no_license | /*
=====================================================
Maze Runner 2 !!!!!!
=====================================================
*/
#include <stdbool.h>
#include <AFMotor.h>
//AF_DCMotor motor(2);
AF_DCMotor motor(3, MOTOR12_8KHZ); //left motor
AF_DCMotor motor2(4, MOTOR12_1KHZ); //right motor
void setup() {
Serial.begin(9600);
Serial.println("Motor Test!");
//set pin analog pin to input
pinMode(0, INPUT);
pinMode(1, INPUT);
pinMode(2, INPUT);
pinMode(3, INPUT);
//set motor speed
motor.setSpeed(220); //left motor is a little bit slower than the right motor, so set the speed a litlle bit higer
motor2.setSpeed(200);
Serial.begin(9600); // Starts the serial communication
delay(2000);
}
void loop() {
//if sensor value < 100 sensor is on (white surface)
//if sensor value > 1000 || 500 sensor in off (black surface)
/*
Sensor 1: furthest Right -> analogPin 0
Sensor 2: Middle Right -> analogPin 1
Sensor 3: Middle Left -> analogPin 2
Sensor 4: Furthest Left -> analogPin 3
*/
Serial.println("=============================================");
Serial.print("Sensor0: "); Serial.println(analogRead(0));
Serial.print("Sensor1: "); Serial.println(analogRead(1));
Serial.print("Sensor2: "); Serial.println(analogRead(2));
Serial.print("Sensor3: "); Serial.println(analogRead(3));
Serial.println("=============================================");
Serial.print("bool Right"); Serial.println(junctionRight());
Serial.print("bool Left"); Serial.println(junctionLeft());
delay(1000);
if(straightLine() == true)
{
forward();
}
else if (outOfBoundToRight() == true)
{
leftTurn();
}
else if (outOfBoundToLeft() == true)
{
rightTurn();
}
else if(junctionRight() == true)
{
enterRightJunction();
}
else if (junctionLeft()==true)
{
enterLeftJunction();
}
else if(endOfLine() == true)
{
stopMotor();
turnAround();
}
else if(tJunction() == true)
{
enterRightJunction();
}
else
{
turnAround();
}
} //end loop()
//============================Sensing============================
bool junctionRight(){
// 1/true == RIGHT
// 0/FALSE == LEFT
if( (analogRead(0)>500) && (analogRead(1)>500) && (analogRead(2)>500) && (analogRead(3)<100) )
{ //right junction detected
return true;
}
else
{
return false;
}
}
bool junctionLeft(){
if( (analogRead(3)>500) && (analogRead(1)>500) && (analogRead(2)>500) && (analogRead(0)<100) )
{ //left junction detected
return true;
}
else
{
return false;
}
}
bool foundJunction(){
if(junctionLeft() == true || junctionRight() == true)
{
return true;
}
else
{
return false;
}
}
bool straightLine(){
if( (analogRead(1) && analogRead(2) > 500) && ((analogRead(0) && analogRead(3) < 100)) ){
return true;
}else{
return false;
}
}
bool outOfBoundToLeft(){
if ( (analogRead(3)&&analogRead(2) < 100) && (analogRead(0)&&analogRead(1) > 500) ){
return true;
} else{
return false;
}
}
bool outOfBoundToRight(){
if( (analogRead(0)&&analogRead(1) < 100) && (analogRead(2)&&analogRead(3) > 500) ){
return true;
} else{
return false;
}
}
bool endOfLine(){
if ( (analogRead(0) && analogRead(1) && analogRead(2) && analogRead(3)) <100 ){ //all sensor ON (white surface)
return true;
} else {
return false;
}
}
bool tJunction(){
if ( (analogRead(0) && analogRead(1) && analogRead(2) && analogRead(3)) > 500 ){ //all sensor OFF (Black surface)
return true;
} else {
return false;
}
}
//============================Sensing============================
//============================Entering Junction============================
void enterRightJunction()
{
stopMotor();
while(!straightLine())
{
rightTurn();
}
}
void enterLeftJunction()
{
stopMotor();
while(!straightLine())
{
leftTurn();
}
}
//============================Entering Junction============================
//============================Decision============================
//============================Decision============================
//============================Movement============================
void forward(){
motor.run(FORWARD); //left motor
motor2.run(FORWARD); //right motor
}
void backward(){
motor.run(BACKWARD); //left motor
motor2.run(BACKWARD); //right motor
}
void stopMotor(){
motor.run(RELEASE); //left motor
motor2.run(RELEASE); //right motor
}
void leftTurn(){
motor.run(RELEASE); //left motor
motor2.run(FORWARD); //right motor
}
void rightTurn(){
motor.run(FORWARD); //left motor
motor2.run(RELEASE); //right motor
}
void turnAround(){
while( !straightLine() ){
motor.run(BACKWARD); //left motor
motor2.run(FORWARD); //right motor
}
stopMotor();
}
void move()
{
if(straightLine() == true)
{
forward();
}
else if (outOfBoundToRight() == true)
{
leftTurn();
}
else if (outOfBoundToLeft() == true)
{
rightTurn();
}
}
void enterJunction()
{
if(foundJunction() == true && junctionRight() == true)
{
enterRightJunction();
}
else if(foundJunction() == true && junctionLeft() == true)
{
enterLeftJunction();
}
}
//============================Movement============================
| true |
3a12a27c1510466a9b716b617318e37814a816c5 | C++ | matjukov-nikolaj/OOP | /lw02/HTMLEncode/HTMLEncode/HtmlEncode.cpp | UTF-8 | 912 | 3.171875 | 3 | [] | no_license | #include "stdafx.h"
#include "HtmlEncode.h"
const std::unordered_map<std::string, std::string> HTML_ENTITIES = {
{ ">", ">" },
{ "&", "&" },
{ "'", "'" },
{ "<", "<" },
{ "\"", """ }
};
std::string EncodeHtmlEntityInString(const std::string& str, const std::string& searchStr, const std::string& replacementStr)
{
if (searchStr.empty())
{
return str;
}
std::string result;
size_t pos = 0;
while (pos < str.size())
{
size_t foundPos = str.find(searchStr, pos);
result.append(str, pos, foundPos - pos);
if (foundPos == std::string::npos)
{
break;
}
result.append(replacementStr);
pos = foundPos + searchStr.size();
}
return result;
}
std::string HtmlEncode(const std::string& html)
{
std::string result = html;
for (auto& htmlEntity : HTML_ENTITIES)
{
result = EncodeHtmlEntityInString(result, htmlEntity.first, htmlEntity.second);
}
return result;
}
| true |
4258242d7d3a66592fe23a29434c042e5ae53906 | C++ | the-rect0r/Random | /CP/library/graph/graph.h | UTF-8 | 1,260 | 3.109375 | 3 | [] | no_license | #pragma once
#include "../general.h"
#include "../range/range.h"
template <class Edge>
class Graph {
public:
int vertexCount;
int edgeCount = 0;
private:
vector<vector<Edge>> edges;
public:
Graph(int vertexCount) : vertexCount(vertexCount), edges(vertexCount, vector<Edge>()) {}
template <typename...Ts>
int addEdge(int from, int to, Ts... args) {
#ifdef LOCAL
if (from < 0 || to < 0 || from >= vertexCount || to >= vertexCount) {
throw "Out of bounds";
}
#endif
edges[from].emplace_back(to, edgeCount, args...);
int directId = edges[from].size() - 1;
if (Edge::reversable) {
edges[to].push_back(edges[from][directId].reverseEdge(from));
int revId = edges[to].size() - 1;
edges[from][directId].setReverseId(revId);
edges[to][revId].setReverseId(directId);
}
edgeCount++;
return directId;
}
vector<Edge>& operator [](int at) {
return edges[at];
}
void addVertices(int count) {
vertexCount += count;
edges.resize(vertexCount);
}
void clear() {
edgeCount = 0;
for (int i : range(vertexCount)) {
edges[i].clear();
}
}
};
| true |
b077e732c4ac3491a0aecf8e4388f742fd6c13a9 | C++ | 3232731490/CPP | /输入输出流/员工信息的输入输出.cpp | GB18030 | 6,965 | 3.546875 | 4 | [] | no_license | //Լдģfun1,fun2,fun3ʹãfun4
//#include <iostream>
//#include <fstream>
//#include<string>
//using namespace std;
//
//class epoloyee
//{
// friend istream& operator>>(istream& cin, epoloyee& p);//">>"
//public:
// epoloyee() {};
// epoloyee(int a, string name, int age, float w) :m_num(a), m_name(name), m_age(age), m_wages(w) {};
// void set_num(int n)
// {
// m_num = n;
// }
// void set_name(string name)
// {
// m_name = name;
// }
// void set_age(int age)
// {
// m_age = age;
// }
// void set_wages(float wages)
// {
// m_wages = wages;
// }
// int get_num()
// {
// return m_num;
// }
// string get_name()
// {
// return m_name;
// }
// int get_age()
// {
// return m_age;
// }
// float get_wages()
// {
// return m_wages;
// }
//
//private:
// int m_num;//
// string m_name;//
// int m_age;//
// float m_wages;//
//};
//void fun1() //Աݷļб
//{
// epoloyee e[5] = { { 1001,"·",18,0 },
// {1002, "", 18, 10},
// {1003, "ʤ", 20, 20},
// {1004,"",17,30},
// {1005,"",19,19} };
// ofstream ofs;
// ofs.open("epoy.text");
// if (!ofs.is_open())
// {
// cerr << "open epoy.text error !" << endl;
// exit;
// }
// for (int i = 0; i < 5; i++)
// {
// ofs << e[i].get_num() << endl;
// ofs << e[i].get_name() << endl;
// ofs << e[i].get_age() << endl;
// ofs << e[i].get_wages() << endl;
// ofs << endl;
// }
// ofs.close();
//}
//istream& operator>>(istream& cin, epoloyee& p)
//{
// cout << "ԱϢ " << endl;
// int num;
// string name;
// int age;
// float wages;
// cout << "ţ " << endl;
// cin >> num;
// cout << "" << endl;
// cin >> name;
// cout << "䣺 " << endl;
// cin >> age;
// cout << "ʣ " << endl;
// cin >> wages;
// p.m_age = age;
// p.m_name = name;
// p.m_num = num;
// p.m_wages = wages;
// return cin;
//}
//void fun2()//ԱϢļĩβ
//{
// epoloyee e1,e2;
// cin >> e1>>e2;
// ofstream ofs("epoy.text",ios::out|ios::app);
// if (!ofs.is_open())
// {
// cerr << "open epoy.text errror!" << endl;
// exit;
// }
// ofs << e1.get_num() << endl;
// ofs << e1.get_age() << endl;
// ofs << e1.get_wages() << endl;
// ofs << endl;
// ofs << e2.get_num() << endl;
// ofs << e2.get_name() << endl;
// ofs << e2.get_age() << endl;
// ofs << e2.get_wages() << endl;
// ofs << endl;
// ofs.close();
//}
//void fun3()//ļȫְϢ
//{
// ifstream ifs("epoy.text");
// if (!ifs.is_open())
// {
// cerr << "open epoy.text error!" << endl;
// exit;
// }
// char s[100];
// while (ifs.getline(s, 100, EOF))
// {
// cout << s;
// }
// ifs.close();
//}
//
////ʵ
//void fun4()//Ա
//{
// cout << "ҪҵԱţ" << endl;
// int num;
// cin >> num;
// ifstream ifs("epoy.text",ios::beg);
// if (!ifs)
// {
// cerr << "open epoy.text error!" << endl;
// exit;
// }
// epoloyee e[7];
// int num1;
// string name;
// int age;
// float wages;
// char s[100];
// for (int i = 0; i < 7; i++)
// {
// while (ifs.getline(s, 20, '\n'))
// ifs >>num1;
// e[i].set_num(num1);
// ifs.ignore();
// while (ifs.getline(s, 20, '\n'))
// ifs >> name;
// e[i].set_name(name);
// ifs.ignore();
// while (ifs.getline(s, 20, '\n'))
// ifs >> age;
// e[i].set_age(age);
// ifs.ignore();
// while (ifs.getline(s, 20, '\n'))
// ifs >> wages;
// e[i].set_wages(wages);
// ifs.ignore();
// ifs.ignore();
// }
// int count = 0;
// for (int i = 0; i < 7; i++)
// {
// if (num == e[i].get_num())
// {
// cout << "ţ " << e[i].get_num() << endl;
// cout << " " << e[i].get_name() << endl;
// cout << "䣺 " << e[i].get_age()<< endl;
// cout << "ʣ " << e[i].get_wages() << endl;
// break;
// }
// count++;
// }
// if (count == 7)
// {
// cout << "" << endl;
// }
//}
//int main()
//{
// fun1();//ԱϢ
// fun2();//ԱϢԭļԱ
// fun3();//Ա
// fun4();//Ա
// system("pause");
// return 0;
//}
//ϵıҲ֪
#include <iostream>
#include <fstream>
using namespace std;
struct staff
{
int num;
char name[20];
int age;
double pay;
};
int main()
{
staff staf[7] = { 2101,"Li",34,1203,2104,"Wang",23,674.5,2108,"Fun",54,778,
3006,"Xue",45,476.5,5101,"Ling",39,656.6 }, staf1;
fstream iofile("staff.dat", ios::in | ios::out | ios::binary);
if (!iofile)
{
cerr << "open error!" << endl;
abort();
}
int i, m, num;
cout << "Five staff :" << endl;
for (i = 0; i < 5; i++)
{
cout << staf[i].num << " " << staf[i].name << " " << staf[i].age << " " << staf[i].pay << endl;
iofile.write((char*)&staf[i], sizeof(staf[i]));
}
cout << "please input data you want insert:" << endl;
for (i = 0; i < 2; i++)
{
cin >> staf1.num >> staf1.name >> staf1.age >> staf1.pay;
iofile.seekp(0, ios::end);
iofile.write((char*)&staf1, sizeof(staf1));
}
iofile.seekg(0, ios::beg);
for (i = 0; i < 7; i++)
{
iofile.read((char*)&staf[i], sizeof(staf[i]));
cout << staf[i].num << " " << staf[i].name << " " << staf[i].age << " " << staf[i].pay << endl;
}
bool find;
cout << "enter number you want search,enter 0 to stop.";
cin >> num;
while (num)
{
find = false;
iofile.seekg(0, ios::beg);
for (i = 0; i < 7; i++)
{
iofile.read((char*)&staf[i], sizeof(staf[i]));
if (num == staf[i].num)
{
m = iofile.tellg();
cout << num << " is No." << m / sizeof(staf1) << endl;
cout << staf[i].num << " " << staf[i].name << " " << staf[i].age << " " << staf[i].pay << endl;
find = true;
break;
}
}
if (!find)
cout << "can't find " << num << endl;
cout << "enter number you want search,enter 0 to stop.";
cin >> num;
}
iofile.close();
return 0;
} | true |
116c071e155e734b251073d546ddadf38f9d7717 | C++ | giniyat202/shapeshift | /shader.cpp | UTF-8 | 2,524 | 2.8125 | 3 | [] | no_license | #include "shader.h"
#include <gl/glew.h>
#include <assert.h>
#include "program.h"
Shader::Shader(const std::string &source, bool createShader, unsigned int shaderType) :
m_id(0),
m_created(false),
m_compiled(false),
m_type(shaderType)
{
if (createShader)
create();
setSource(source);
}
Shader::~Shader()
{
destroy();
}
void Shader::create()
{
assert(!m_created);
m_id = glCreateShader(m_type);
m_created = true;
setSourceActual();
}
void Shader::destroy()
{
if (m_created)
{
while (!m_programs.empty())
removeFromProgram(*m_programs.begin());
glDeleteShader(m_id);
m_created = false;
m_compiled = false;
}
}
bool Shader::isCreated() const
{
return m_created;
}
unsigned int Shader::id() const
{
return m_id;
}
void Shader::setType(unsigned int shaderType)
{
m_type = shaderType;
}
unsigned int Shader::type() const
{
return m_type;
}
void Shader::setSource(const std::string &source)
{
m_source = source;
if (m_created)
setSourceActual();
}
const std::string &Shader::getSource() const
{
return m_source;
}
bool Shader::compile()
{
assert(m_created);
int success, loglen;
glCompileShader(m_id);
glGetShaderiv(m_id, GL_COMPILE_STATUS, &success);
m_compiled = success == GL_TRUE;
if (!m_compiled)
{
glGetShaderiv(m_id, GL_INFO_LOG_LENGTH, &loglen);
m_errorLog.resize(loglen, 0);
glGetShaderInfoLog(m_id, loglen, NULL, &m_errorLog[0]);
}
return m_compiled;
}
bool Shader::isCompiled() const
{
return m_compiled;
}
const std::string &Shader::errorLog() const
{
return m_errorLog;
}
void Shader::addToProgram(Program *program)
{
assert(m_created);
assert(program != NULL);
assert(program->isCreated());
if (m_programs.find(program) == m_programs.end())
{
m_programs.insert(program);
program->addShader(this);
}
}
void Shader::removeFromProgram(Program *program)
{
assert(m_created);
std::set<Program*>::iterator it = m_programs.find(program);
if (it != m_programs.end())
{
m_programs.erase(it);
program->removeShader(this);
}
}
const std::set<Program *> &Shader::getPrograms() const
{
return m_programs;
}
void Shader::setSourceActual()
{
assert(m_created);
if (m_source.size() > 0)
{
const char *source = &m_source[0];
glShaderSource(m_id, 1, &source, NULL);
}
m_compiled = false;
}
| true |
0be793430086a19311e6e5a182bf0cc49470ef5d | C++ | JohnMurray/pembroke | /pembroke/src/pembroke/event/delayed_test.cpp | UTF-8 | 1,974 | 2.953125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #include <catch2/catch.hpp>
#include <thread>
#include <type_traits>
#include "pembroke/reactor.hpp"
#include "pembroke/event/delayed.hpp"
using namespace std::chrono_literals;
using namespace pembroke::event;
TEST_CASE("Schedule zero-wait delayed event", "[event][delayed][execution]") {
auto r = pembroke::reactor().build();
auto x = 0;
auto event = DelayedEvent(0s, [&]() -> void {
x += 1;
});
CHECK(r->register_event(event));
CHECK(r->tick());
CHECK(x == 1);
}
TEST_CASE("Schedule delayed event (blocking)", "[event][delayed][execution]") {
auto r = pembroke::reactor().build();
auto x = 0;
auto event = DelayedEvent(100us, [&]() -> void {
x += 1;
CHECK(r->stop());
});
CHECK(r->register_event(event));
CHECK(r->run_blocking());
CHECK(x == 1);
}
TEST_CASE("Schedule delayed event (non-blocking)", "[event][delayed][execution]") {
auto r = pembroke::reactor().build();
auto x = 0;
auto event = DelayedEvent(100us, [&]() -> void {
x += 1;
});
CHECK(r->register_event(event));
CHECK(r->tick());
CHECK(x == 0);
std::this_thread::sleep_for(10ms);
CHECK(r->tick());
CHECK(x == 1);
}
TEST_CASE("Cancel a scheduled, delayed event", "[event][delayed][execution]") {
auto r = pembroke::reactor().build();
auto x = 0;
auto event = DelayedEvent(10us, [&]() -> void {
x += 1;
});
CHECK(r->register_event(event));
CHECK(event.cancel());
std::this_thread::sleep_for(10ms);
CHECK(r->tick());
CHECK(x == 0);
}
TEST_CASE("Cancel a scheduled, delayed event before registration", "[event][delayed][execution]") {
auto r = pembroke::reactor().build();
auto x = 0;
auto event = DelayedEvent(10us, [&]() -> void {
x += 1;
});
CHECK(event.cancel());
CHECK_FALSE(r->register_event(event));
std::this_thread::sleep_for(10ms);
CHECK(r->tick());
CHECK(x == 0);
} | true |
4fa34c476811469db520fbf6e9139b2694a1a276 | C++ | changjixiong/program_forest | /exmaple/io/epoll_input.cpp | UTF-8 | 2,561 | 2.796875 | 3 | [] | no_license | #include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<sys/epoll.h>
#include<errno.h>
#include<unistd.h>
#define MAX_BUF 1024
#define MAX_EVENTS 5
int main(int argc, char * argv[]){
int epfd, ready, fd, s, numOpenfds;
struct epoll_event ev;
struct epoll_event evlist[MAX_EVENTS];
char buf[MAX_BUF]={0};
if (argc<2 || strcmp(argv[1], "--help")==0){
printf("%s file ...\n", argv[0]);
exit(EXIT_FAILURE);
}
epfd = epoll_create(argc-1);
if (epfd ==-1){
printf("epoll_create error:%d", errno);
exit(EXIT_FAILURE);
}
for (int i=1; i<argc;i++){
fd = open(argv[i], O_RDONLY);
if (fd ==-1){
printf("open file %s error:%d", argv[i],errno);
exit(EXIT_FAILURE);
}
printf("opened \"%s\" on fd %d\n", argv[i], fd);
ev.events = EPOLLIN;
ev.data.fd=fd;
if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev)==-1){
printf("epoll_ctl file %d to %d error:%d",fd, epfd,errno);
exit(EXIT_FAILURE);
}
}
numOpenfds = argc -1;
while(numOpenfds>0){
printf("About to epoll_wait()\n");
ready = epoll_wait(epfd, evlist, MAX_EVENTS, -1);
if (ready ==-1){
if (errno==EINTR){
continue;
}else{
printf("%d epoll_wait error:%d", epfd,errno);
exit(EXIT_FAILURE);
}
}
printf("Ready: %d\n", ready);
for (int j=0;j<ready;j++){
printf("fd=%d; events: %s%s%s\n", evlist[j].data.fd,
(evlist[j].events & EPOLLIN) ? "EPOLLIN ": "",
(evlist[j].events & EPOLLHUP) ? "EPOLLHUP ": "",
(evlist[j].events & EPOLLERR)? "EPOLLERR ": "");
if (evlist[j].events & EPOLLIN){
s = read(evlist[j].data.fd, buf, MAX_BUF);
if (s==-1){
printf("%d read error:%d", evlist[j].data.fd,errno);
exit(EXIT_FAILURE);
}
printf("read %d bytes: %.*s\n", s, s, buf);
}else if (evlist[j].events & (EPOLLHUP | EPOLLERR)){
printf("closing fd %d\n", evlist[j].data.fd);
if (close(evlist[j].data.fd)==-1){
printf("%d close error:%d", evlist[j].data.fd,errno);
exit(EXIT_FAILURE);
}
numOpenfds--;
}
}
}
printf("All fd closed\n");
exit(EXIT_SUCCESS);
} | true |
982f0f1c3955948ba07bfeba54b18daba42a808a | C++ | jamiepg18/maze3dflyer | /HighScoreList.h | UTF-8 | 2,698 | 3 | 3 | [] | no_license | #ifndef __HighScoreList_h__
#define __HighScoreList_h__
#include <map>
#include <string>
#include "Maze3D.h"
using namespace std;
struct compareDims
{
// comparison function for dims
// "The key comparison function, a Strict Weak Ordering whose argument type is key_type;
// it returns true if its first argument is less than its second argument, and false otherwise."
// We want to order maze dimensions basically by their difficulty, but also make the score list
// visually scannable. So we order by greatest dimension, then 2nd greatest, then smallest,
// and then by sparsity.
bool operator()(string dims1, string dims2) const
{
int w1, h1, d1, s1;
int w2, h2, d2, s2;
if (sscanf(dims1.c_str(), "%dx%dx%d/%d", &w1, &h1, &d1, &s1) < 4 ||
sscanf(dims2.c_str(), "%dx%dx%d/%d", &w2, &h2, &d2, &s2) < 4)
return (dims1 < dims2);
if (w1 < w2) return true;
else if (w1 > w2) return false;
if (h1 < h2) return true;
else if (h1 > h2) return false;
if (d1 < d2) return true;
else if (d1 > d2) return false;
// Note, a maze with greater sparsity is less complex, so reverse the comparison.
if (s1 > s2) return true;
else return false;
}
};
class HighScoreList {
map<string, float, compareDims> highScoreMap;
map<string, float, compareDims>::iterator p;
public:
// Add new score, if it is a new record, for the given dims.
// dims = 'wxhxd/s'. t = time in seconds, to the nearest 100th.
// Return true if new record established.
bool addScore(char *dims, float t);
bool addScore(Maze3D &maze);
float getHighScore(char *dims);
int HighScoreList::getPosition(char *dims);
bool save(void);
bool load(void);
char *filepath;
HighScoreList() { filepath = "maze3dflyer_scores.txt"; }
// makeDims: convert the maze parameters to a single string
static char *dims(Maze3D &maze, bool normalize = false) {
static char buf[16];
int i = maze.w, j = maze.h, k = maze.d;
// sort dimensions by size, so that 6x2x10 has the same best score slot as 10x6x2.
if (normalize) {
if (i < j) swap(i, j);
if (j < k) swap(j, k);
if (i < j) swap(i, j);
}
sprintf(buf, "%dx%dx%d/%d", i, j, k, maze.sparsity);
return buf;
}
static char *formatTime(float t, bool rightJustify = true);
// return pointer to a static buffer with a display of scores
char *toString(Maze3D &maze, int linesAllowed = 20);
static void complexityStats(void);
};
extern HighScoreList highScoreList;
#endif // __HighScoreList_h__
| true |
543db37a7871807dd9dcbba9227f936d0ac6ea2d | C++ | sanwan/AlgorithmExercises | /四、递归和动态规划/3.最长递增子序列相关问题/最长递增子序列_dp优化.cpp | GB18030 | 2,316 | 3.921875 | 4 | [
"MIT"
] | permissive | /*
⣺һ
ONlogNĽⷨ(dpʱ临Ӷ,ҪöֽŻ)
1ʹøend[]end[i]¼i+1ȵĵеСĩβάһУԿԶֲ
2dp[i]ֵΪendλöӦijȣΪǰ涼Сģ
dpɵõǶ٣ȶӦ
1Ӻǰdp[i]ǰ
2dp[j]=dp[i]-1 a[j]<a[i]Ϊ
3......
*/
#include <stdio.h>
#include <stack>
using namespace std;
//õdp
void getdp(int *a,int *dp,int len)
{
int end[len];//end
end[0]=a[0];//һλΪa[0]
dp[0]=1;//dpһλΪ1
int right=0;//endЧλ
int l=0;//Ч
int r=0;//Чұ
int m=0;//Чм
for(int i=0;i<len;++i){
l=0;//ÿl
r=right;//rұ
while(l<=r){//ֲend,<=ûҵl=right+1,Чһλ****
m=(l+r)/2;
if(a[i]>end[m])
l=m+1;
else
r=m-1;
}
right=right>l ? right:l;//Чλ
end[l]=a[i];//Ҫλ
dp[i]=l+1;//dp[i]ΪЧijȣΪl+1
}
}
void getLongestList(int *a,int len)
{
int dp[len];
getdp(a,dp,len);
int maxLen=0;
int index=0;
for(int i=0;i<len;++i)//dpֵ
if(dp[i]>maxLen){
maxLen=dp[i];
index=i;
}
printf("гΪ:%d\n",maxLen);
stack<int> list;//ջУΪǴӺǰУ
list.push(a[index]);//Ƚջ
for(int i=index;i>=0;--i)//Ӻǰ
if(a[i]<a[index] && dp[i]==dp[index]-1){//ǰıȵǰСdpС1ϵջ
list.push(a[i]);
index=i;//ͬʱindexΪλ
}
printf("Ϊ");
while(!list.empty()){//
printf("%d ",list.top());
list.pop();
}
printf("\n");
}
int main(int argc,char *argv[])
{
printf("У-1β");
int n=0,data,a[100];
while(scanf("%d",&data) && data!=-1){
a[n++]=data;
}
getLongestList(a,n);
return 0;
}
| true |
c4cef5822d4d30f6125a77bedc716c407f100a79 | C++ | lindacesari/LSN | /01/2/func.h | UTF-8 | 954 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
#include <cstdlib>
#include <iomanip>
using namespace std;
double error(vector<double> ave, vector<double> ave2, int n) {
if (n == 0) {
return 0.;
}
else {
return sqrt( (ave2[n] - pow(ave[n], 2)) / n );
}
}
void set_rnd(Random& rnd) {
int seed[4];
int p1, p2;
ifstream Primes("Primes");
if (Primes.is_open()){
Primes >> p1 >> p2 ;
} else cerr << "PROBLEM: Unable to open Primes" << endl;
Primes.close();
ifstream input("seed.in");
string property;
if (input.is_open()){
while ( !input.eof() ){
input >> property;
if( property == "RANDOMSEED" ){
input >> seed[0] >> seed[1] >> seed[2] >> seed[3];
rnd.SetRandom(seed,p1,p2);
}
}
input.close();
} else cerr << "PROBLEM: Unable to open seed.in" << endl;
return;
}
| true |
c53e0be6cfe12f54cb8dc47141dd2e79621751f3 | C++ | liujk/edami-gsp | /src/gsp_common.h | UTF-8 | 1,964 | 3.078125 | 3 | [] | no_license | /* -*- mode: cc-mode; tab-width: 2; -*- */
/**
* @file gsp_common.h
*
* @brief Common type definitions used within project
*
* @author: Tomasz Gebarowski <gebarowski@gmail.com>
* @date: Fri May 18 15:13:25 2012
*/
#ifndef __GSP_COMMON_H__
#define __GSP_COMMON_H__
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
//using namespace std;
/**
* @brief Useful macro defining empty set
*/
#define EMPTY_SET ""
/**
* @brief Enumeration representing possible values returned by functions
*/
enum GSP_STATUS
{
GSP_OK, /**< OK */
GSP_EINVAL, /**< Invalid value/pointer */
GSP_EEXIST, /**< Value already exists */
GSP_ENOTFOUND, /**< Value not found */
GSP_ERROR /**< Generic error */
};
/**
* @brief Conversion to string
*/
template < class T >
inline std::string ToString(const T &arg)
{
std::ostringstream out(std::ios_base::out);
out << arg;
return(out.str());
}
/**
* @brief Conversion from string to integer
*/
inline int ToInt(const std::string &arg)
{
int i = 0;
std::stringstream iss(arg);
iss >> i;
return i;
}
/**
* @brief Conversion from string to integer
*/
inline bool ToBool(const std::string &arg)
{
if (arg == "yes" || arg == "YES" || arg == "On" || arg == "on")
return true;
return false;
}
/**
* @brief Conversion from string to double
*/
inline double ToDouble(const std::string &arg)
{
double d = 0;
std::stringstream iss(arg);
iss >> d;
return d;
}
/**
* @brief Conversion from int to string (hex)
*/
inline std::string ToHex(const unsigned int value)
{
std::ostringstream out;
out << std::hex << value;
return (out.str());
}
/**
* @brief Tokenize string based on delimeter character
*
* @param[in] line string to be tokenized
* @param[in] delimeter Used delimeter
*
* @return Vector of tokens
*/
std::vector<std::string> * Tokenize(std::string line,
char delimeter);
#endif /* __GSP_COMMON_H__ */
| true |
80c52dd025e010c8b03aeefa535ad1425fd98463 | C++ | MultivacX/leetcode2020 | /algorithms/easy/0163. Missing Ranges.h | UTF-8 | 1,997 | 3.40625 | 3 | [
"MIT"
] | permissive | // 163. Missing Ranges
// https://leetcode.com/problems/missing-ranges/
// Runtime: 0 ms, faster than 100.00% of C++ online submissions for Missing Ranges.
// Memory Usage: 7.4 MB, less than 69.73% of C++ online submissions for Missing Ranges.
class Solution {
public:
vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) {
nums.insert(nums.begin(), -2000000000);
nums.push_back(2000000000);
const int N = nums.size();
vector<string> ans;
for (int i = 0; i + 1 < N; ++i) {
// [nums[i]+1, nums[i+1]-1]
int l = max(lower, nums[i] + 1);
int u = min(upper, nums[i + 1] - 1);
if (l < u) ans.push_back(to_string(l) + "->" + to_string(u));
else if (l == u) ans.push_back(to_string(l));
}
return ans;
}
};
class Solution {
public:
vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) {
if (nums.empty())
return lower == upper ?
vector<string>{to_string(lower)} :
vector<string>{to_string(lower) + "->" + to_string(upper)};
if (lower == upper)
return {};
const int n = nums.size();
vector<string> ans;
if (lower < nums[0]) {
if (lower == nums[0] - 1) ans.push_back(to_string(lower));
else ans.push_back(to_string(lower) + "->" + to_string(nums[0] - 1));
}
for (int i = 1; i < n; ++i) {
int diff = nums[i] - nums[i - 1];
if (diff == 1) continue;
if (diff == 2) ans.push_back(to_string(nums[i] - 1));
else ans.push_back(to_string(nums[i - 1] + 1) + "->" + to_string(nums[i] - 1));
}
if (nums[n - 1] < upper) {
if (nums[n - 1] == upper - 1) ans.push_back(to_string(upper));
else ans.push_back(to_string(nums[n - 1] + 1) + "->" + to_string(upper));
}
return ans;
}
}; | true |
8ee4aa37622d055be920c7943dd56ff9f22a5286 | C++ | masayuki-fuseya/GameEngineTK | /GameEngineTK/Player.h | SHIFT_JIS | 2,364 | 2.546875 | 3 | [] | no_license | //߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁
//! @file Player.h
//!
//! @brief vC[NX̃wb_t@C
//!
//! @date 2017/06/01
//!
//! @author Masayuki Fuseya
//߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁߁
// dCN[h̖h~ ==================================================
#pragma once
// wb_t@C̓ǂݍ ================================================
#include "Obj3d.h"
#include "KeyboardUtil.h"
#include "CollisionNode.h"
#include <SimpleMath.h>
#include <vector>
class Player :public Obj3d
{
private:
std::vector<Obj3d> m_parts;
KeyboardUtil* m_keyboard;
DirectX::SimpleMath::Vector3 m_starAngle;
// ^N̑x
DirectX::SimpleMath::Vector3 m_batteryVel;
// xxNg
DirectX::SimpleMath::Vector3 m_velocity;
float m_sinAngle;
float m_sinScale;
bool m_shootFlag; // ˒
bool m_isJump;
int m_timer;
// 蔻苅
SphereNode m_collisionNodeBattery;
SphereNode m_collisionNodeTank;
public:
// d͉x
const float GRAVITY_ACC = 0.03f;
// Wv̏x
const float JUMP_SPEED_FIRST = 0.5f;
// Wv̍ōx
const float JUMP_SPEED_MAX = 0.3f;
public:
enum PLAYER_PARTS
{
PLAYER_PARTS_TANK,
PLAYER_PARTS_BATTERY,
PLAYER_PARTS_SHIELD,
PLAYER_PARTS_DRILL,
PLAYER_PARTS_STAR,
PLAYER_PARTS_NUM // Ŝ̐
};
Player();
void Update();
void Calc();
void Render();
void SetKeyboard(KeyboardUtil* keyboard)
{
m_keyboard = keyboard;
}
void SetTranslation(DirectX::SimpleMath::Vector3& translation)
{
m_parts[0].SetTranslation(translation);
}
const DirectX::SimpleMath::Vector3& GetRotation()
{
return m_parts[0].GetRotation();
}
const DirectX::SimpleMath::Vector3& GetTranslation()
{
return m_parts[0].GetTranslation();
}
const SphereNode& GetCollisionNodeBattery()
{
return m_collisionNodeBattery;
}
const SphereNode& GetCollisionNodeTank()
{
return m_collisionNodeTank;
}
const DirectX::SimpleMath::Vector3& GetVelocity()
{
return m_velocity;
}
void StartJump();
void StartFall();
void StopJump();
private:
void ShootBattery();
void ResetBattery();
void MoveParts(DirectX::SimpleMath::Vector3 moveV);
};
| true |
dcae0b33039fe118895e03fc5021566ccf407ae4 | C++ | pedrocunial/DesafiosDeProgramacao | /revisao3/massas/ll_sort/linked_list.hxx | UTF-8 | 543 | 3 | 3 | [] | no_license | #ifndef __LINKED_LIST_HXX__
#define __LINKED_LIST_HXX__
template<typename T>
struct node_t {
node_t *next;
T value;
};
template<typename T>
class LinkedList {
private:
node_t<T> *front;
node_t<T> *back;
std::size_t _size;
public:
LinkedList();
~LinkedList();
void push_back(T value);
T get(std::size_t i);
inline std::size_t size();
inline node_t<T> * get_head();
inline node_t<T> * get_tail();
inline void set_head(node_t<T> *node);
inline void set_tail(node_t<T> *node);
};
#include "linked_list.cxx"
#endif
| true |
2f59f005ed592ac53911590459a5abd6a74c501a | C++ | edmundmk/pomelo | /pomelo/actions.cpp | UTF-8 | 26,210 | 2.578125 | 3 | [
"MIT"
] | permissive | //
// actions.cpp
// pomelo
//
// Created by Edmund Kapusniak on 28/01/2018.
// Copyright © 2018 Edmund Kapusniak.
//
// Licensed under the MIT License. See LICENSE file in the project root for
// full license information.
//
#include <assert.h>
#include "actions.h"
#include "search.h"
actions::actions( errors_ptr errors, automata_ptr automata, bool expected_info )
: _errors( errors )
, _automata( automata )
, _expected_info( expected_info )
{
}
actions::actions()
{
}
void actions::analyze()
{
// Work out actions for each state.
for ( const auto& state : _automata->states )
{
build_actions( state.get() );
}
// Traverse automata using actions and check if any rules are unreachable.
_automata->visited += 1;
traverse_rules( _automata->start );
// Report any unreachable rules and assign rule indices.
int index = 0;
for ( const auto& rule : _automata->syntax->rules )
{
if ( rule->reachable )
{
rule->index = index++;
}
else
{
srcloc sloc = rule_location( rule.get() );
const char* prod = _automata->syntax->source->text( rule->nterm->name );
_errors->error( sloc, "this rule for production %s cannot be reduced", prod );
}
}
_automata->rule_count = index;
// Assign state indices.
index = 0;
for ( const auto& state : _automata->states )
{
if ( state->reachable )
{
state->index = index++;
}
}
_automata->state_count = index;
}
action_table_ptr actions::build_action_table()
{
action_table_ptr table = std::make_shared< action_table >();
// Table dimensions.
table->rule_count = _automata->rule_count;
table->conflict_count = -1;
table->token_count = (int)_automata->syntax->terminals.size();
table->state_count = _automata->state_count;
// Collect rules.
for ( const auto& rule : _automata->syntax->rules )
{
if ( ! rule->reachable )
continue;
assert( rule->index == (int)table->rules.size() );
table->rules.push_back( rule.get() );
}
// Construct table state by state.
for ( const auto& state : _automata->states )
{
if ( ! state->reachable )
continue;
size_t base = table->actions.size();
assert( state->index == (int)base / table->token_count );
table->actions.insert
(
table->actions.end(),
table->token_count,
-1
);
assert( (int)state->actions.size() == table->token_count );
for ( size_t i = 0; i < state->actions.size(); ++i )
{
const action& action = state->actions.at( i );
int actval = -1;
switch ( action.kind )
{
case ACTION_ERROR:
actval = -1;
break;
case ACTION_SHIFT:
if ( action.shift->next != _automata->accept )
{
assert( action.shift->next->index != -1 );
actval = action.shift->next->index;
}
else
{
actval = -2;
}
break;
case ACTION_REDUCE:
assert( action.reduce->drule->index != -1 );
actval = table->state_count + action.reduce->drule->index;
break;
case ACTION_CONFLICT:
actval = conflict_actval( table.get(), action.cflict );
break;
}
table->actions[ base + i ] = actval;
}
}
// Work out remaining action numbers.
table->conflict_count = (int)table->conflicts.size();
table->accept_action = table->state_count + table->rule_count + table->conflict_count;
table->error_action = table->accept_action + 1;
// Reset special actions now we know what to call them.
for ( size_t i = 0; i < table->actions.size(); ++i )
{
int action = table->actions.at( i );
if ( action == -1 )
{
table->actions[ i ] = table->error_action;
}
else if ( action == -2 )
{
table->actions[ i ] = table->accept_action;
}
}
// Compress table.
table->compressed = compress( table->token_count, table->state_count, table->error_action, table->actions );
return table;
}
goto_table_ptr actions::build_goto_table()
{
goto_table_ptr table = std::make_shared< goto_table >();
// Table dimensions.
table->token_count = (int)_automata->syntax->terminals.size();
table->nterm_count = (int)_automata->syntax->nonterminals.size();
table->state_count = _automata->state_count;
// Construct table state by state.
for ( const auto& state : _automata->states )
{
if ( ! state->reachable )
continue;
size_t base = table->gotos.size();
assert( state->index == (int)base / table->nterm_count );
table->gotos.insert
(
table->gotos.end(),
table->nterm_count,
table->state_count
);
for ( transition* trans : state->next )
{
if ( trans->sym->is_terminal )
continue;
nonterminal* nterm = (nonterminal*)trans->sym;
assert( nterm->value >= table->token_count );
assert( nterm->value < table->token_count + table->nterm_count );
int value = nterm->value - table->token_count;
assert( trans->next->index != -1 );
table->gotos[ base + value ] = trans->next->index;
}
}
// Compress table.
table->compressed = compress( table->nterm_count, table->state_count, table->state_count, table->gotos );
return table;
}
void actions::report_conflicts()
{
// Report conflict.
for ( const auto& state : _automata->states )
{
if ( state->has_conflict )
{
report_conflicts( state.get() );
}
}
}
void actions::print()
{
source_ptr source = _automata->syntax->source;
for ( const auto& state : _automata->states )
{
printf( "%p\n", state.get() );
for ( const auto& entry : _automata->syntax->terminals )
{
terminal* term = entry.second.get();
const action& action = state->actions.at( term->value );
if ( action.kind == ACTION_ERROR )
{
continue;
}
printf( " %s -> ", source->text( term->name ) );
switch ( action.kind )
{
case ACTION_ERROR:
break;
case ACTION_SHIFT:
printf( "SHIFT %p\n", action.shift->next );
break;
case ACTION_REDUCE:
printf( "REDUCE %s\n", source->text( action.reduce->drule->nterm->name ) );
break;
case ACTION_CONFLICT:
printf( "CONFLICT\n" );
if ( action.cflict->shift )
{
printf( " SHIFT %p\n", action.cflict->shift->next );
}
for ( reduction* reduction : action.cflict->reduce )
{
printf( " REDUCE %s\n", source->text( reduction->drule->nterm->name ) );
}
break;
}
}
for ( transition* trans : state->next )
{
if ( trans->sym->is_terminal )
continue;
printf( " ** %s -> %p\n", source->text( trans->sym->name ), trans->next );
}
}
}
void actions::build_actions( state* s )
{
source_ptr source = _automata->syntax->source;
// All actions in the state start off as errors.
size_t terminals_count = _automata->syntax->terminals.size();
s->actions.assign( terminals_count, { ACTION_ERROR } );
// Go through all reductions and check reduce/reduce conflicts.
for ( reduction* reduction : s->reductions )
{
for ( terminal* lookahead : reduction->lookahead )
{
action* action = &s->actions.at( lookahead->value );
switch ( action->kind )
{
case ACTION_ERROR:
{
// Set reduction.
action->kind = ACTION_REDUCE;
action->reduce = reduction;
break;
}
case ACTION_SHIFT:
{
assert( ! "should never happen" );
break;
}
case ACTION_REDUCE:
{
// Attempt to resolve with precedence.
int old_prec = rule_precedence( action->reduce->drule );
int new_prec = rule_precedence( reduction->drule );
if ( old_prec != new_prec && old_prec != -1 && new_prec != -1 )
{
// This reduce/reduce conflict is resolved by precedence.
::reduction* winner;
if ( new_prec > old_prec )
{
winner = reduction;
}
else
{
winner = action->reduce;
}
if ( _expected_info )
{
_errors->info
(
rule_location( winner->drule ),
"conflict on %s reduce %s/reduce %s resolved in favour of reduce %s",
source->text( lookahead->name ),
source->text( action->reduce->drule->nterm->name ),
source->text( reduction->drule->nterm->name ),
source->text( winner->drule->nterm->name )
);
}
action->reduce = winner;
}
else
{
// This is an actual conflict.
conflict_ptr conflict = std::make_unique< ::conflict >( lookahead );
conflict->reduce.push_back( action->reduce );
conflict->reduce.push_back( reduction );
action->kind = ACTION_CONFLICT;
action->cflict = conflict.get();
_automata->conflicts.push_back( std::move( conflict ) );
s->has_conflict = true;
}
break;
}
case ACTION_CONFLICT:
{
// Add reduction to the conflict.
action->cflict->reduce.push_back( reduction );
break;
}
}
}
}
// Go through all transitions of terminals and check shift/reduce conflicts.
for ( transition* trans : s->next )
{
if ( ! trans->sym->is_terminal )
{
continue;
}
action* action = &s->actions.at( trans->sym->value );
switch ( action->kind )
{
case ACTION_ERROR:
{
// Set reduction.
action->kind = ACTION_SHIFT;
action->shift = trans;
break;
}
case ACTION_SHIFT:
{
assert( ! "should never happen" );
break;
}
case ACTION_REDUCE:
{
// Attempt to resolve with precedence.
terminal* shift_symbol = (terminal*)trans->sym;
int reduce_prec = rule_precedence( action->reduce->drule );
int shift_prec = shift_symbol->precedence;
enum { UNKNOWN, SHIFT, REDUCE, CONFLICT } result = UNKNOWN;
if ( reduce_prec == -1 || shift_prec == -1 )
{
// Precedence is missing for either shift or reduce.
result = CONFLICT;
}
else if ( shift_prec > reduce_prec )
{
// Shift precedence is higher.
result = SHIFT;
}
else if ( reduce_prec > shift_prec )
{
// Reduce precedence is higher.
result = REDUCE;
}
else if ( shift_symbol->associativity == ASSOC_RIGHT )
{
// Right-associative, resolve in favour of shift.
assert( shift_prec == reduce_prec );
result = SHIFT;
}
else if ( shift_symbol->associativity == ASSOC_LEFT )
{
// Left-associative, resolve in favour of reduce.
assert( shift_prec == reduce_prec );
result = REDUCE;
}
else
{
// Nonassociative with equal precedence, conflict.
result = CONFLICT;
}
switch ( result )
{
case UNKNOWN:
{
assert( ! "should never happen" );
break;
}
case SHIFT:
{
if ( _expected_info )
{
_errors->info
(
trans->tok.sloc,
"conflict on %s shift/reduce %s resolved in favour of shift",
source->text( shift_symbol->name ),
source->text( action->reduce->drule->nterm->name )
);
}
action->kind = ACTION_SHIFT;
action->shift = trans;
break;
}
case REDUCE:
{
// Reduction is already present in the action.
if ( _expected_info )
{
_errors->info
(
rule_location( action->reduce->drule ),
"conflict on %s shift/reduce %s resolved in favour of reduce %s",
source->text( shift_symbol->name ),
source->text( action->reduce->drule->nterm->name ),
source->text( action->reduce->drule->nterm->name )
);
}
break;
}
case CONFLICT:
{
conflict_ptr conflict = std::make_unique< ::conflict >( shift_symbol );
conflict->shift = trans;
conflict->reduce.push_back( action->reduce );
action->kind = ACTION_CONFLICT;
action->cflict = conflict.get();
_automata->conflicts.push_back( std::move( conflict ) );
s->has_conflict = true;
break;
}
}
break;
}
case ACTION_CONFLICT:
{
// Add shift to the conflict. TODO: check precedence against
// all reductions if they are all either SHIFT or REDUCE.
action->cflict->shift = trans;
break;
}
}
}
}
int actions::rule_precedence( rule* r )
{
return r->precedence ? r->precedence->precedence : -1;
}
srcloc actions::rule_location( rule* r )
{
size_t iloc = r->lostart;
const location& loc = _automata->syntax->locations[ iloc ];
return loc.stoken.sloc;
}
void actions::traverse_rules( state* s )
{
// If we've already been here, ignore this state.
if ( s->visited == _automata->visited )
{
return;
}
// This state is reachable.
s->visited = _automata->visited;
s->reachable = true;
// If this is the accept state, the start rule is reachable.
if ( s == _automata->accept )
{
for ( reduction* reduce : s->reductions )
{
reduce->drule->reachable = true;
}
return;
}
// If any of the nonterminal transitions have been visited, then we can
// now traverse them as both this state and the reduction that branches
// off here are reachable.
for ( transition* trans : s->next )
{
if ( ! trans->sym->is_terminal && trans->visited == _automata->visited )
{
traverse_rules( trans->next );
}
}
// Follow all actions.
for ( const action& action : s->actions )
{
switch ( action.kind )
{
case ACTION_ERROR:
break;
case ACTION_SHIFT:
traverse_rules( action.shift->next );
break;
case ACTION_REDUCE:
traverse_reduce( s, action.reduce );
break;
case ACTION_CONFLICT:
if ( action.cflict->shift )
{
traverse_rules( action.cflict->shift->next );
}
for ( reduction* reduce : action.cflict->reduce )
{
traverse_reduce( s, reduce );
}
break;
}
}
}
void actions::traverse_reduce( state* s, reduction* reduce )
{
// This rule is reachable.
reduce->drule->reachable = true;
// If the rule is an epsilon rule, traverse forward from this state.
if ( reduce->drule->locount <= 1 )
{
for ( transition* trans : s->next )
{
if ( trans->sym == reduce->drule->nterm )
{
trans->visited = _automata->visited;
assert( trans->prev->visited == _automata->visited );
traverse_rules( trans->next );
break;
}
}
return;
}
// Otherwise, look back along the goto links.
for ( transition* prev : s->prev )
{
for ( reducefrom* rgoto : prev->rgoto )
{
if ( rgoto->drule == reduce->drule )
{
transition* nterm = rgoto->nonterminal;
assert( ! nterm->sym->is_terminal );
// This nonterminal transition has been visited.
nterm->visited = _automata->visited;
// We can traverse into the goto state if the state before it
// has been visisted, otherwise it will be traversed when and
// if the state is visted.
if ( nterm->prev->visited == _automata->visited )
{
traverse_rules( nterm->next );
}
}
}
}
}
int actions::conflict_actval( action_table* table, conflict* conflict )
{
// Build conflict.
int size = 1 + ( conflict->shift ? 1 : 0 ) + (int)conflict->reduce.size();
int action[ size ];
size_t i = 0;
action[ i++ ] = size;
if ( conflict->shift )
{
assert( conflict->shift->next->index != -1 );
action[ i++ ] = conflict->shift->next->index;
}
for ( reduction* reduce : conflict->reduce )
{
assert( reduce->drule->index != -1 );
action[ i++ ] = table->state_count + reduce->drule->index;
}
// Check if it already exists.
int index = 0;
while ( index < (int)table->conflicts.size() )
{
int* othact = table->conflicts.data() + index;
bool equal = true;
for ( int i = 0; i < size; ++i )
{
if ( action[ i ] != othact[ i ] )
{
equal = false;
break;
}
}
if ( equal )
{
return table->state_count + table->rule_count + index;
}
index += othact[ 0 ];
}
// No, it doesn't.
table->conflicts.insert( table->conflicts.end(), action, action + size );
return table->state_count + table->rule_count + index;
}
void actions::report_conflicts( state* s )
{
// Detailed reporting of conflicts requires pathfinding through the graph.
_automata->ensure_distances();
// Group conflicts by whether or not they shift, and by reduction sets.
for ( size_t i = 0; i < s->actions.size(); )
{
action* action = &s->actions.at( i++ );
if ( action->kind != ACTION_CONFLICT || action->cflict->reported )
{
continue;
}
std::vector< conflict* > conflicts;
conflicts.push_back( action->cflict );
action->cflict->reported = true;
for ( size_t j = i; j < s->actions.size(); ++j )
{
::action* similar = &s->actions.at( j++ );
if ( similar->kind != ACTION_CONFLICT || action->cflict->reported )
{
continue;
}
if ( similar_conflict( action->cflict, similar->cflict ) )
{
conflicts.push_back( similar->cflict );
similar->cflict->reported = true;
}
}
report_conflict( s, conflicts );
}
}
bool actions::similar_conflict( conflict* a, conflict* b )
{
// Conflicts are only similar if they have a shift (or not have a shift).
if ( ( a->shift != nullptr ) != ( b->shift != nullptr ) )
return false;
// Similar conflicts should have the same number of reductions.
if ( a->reduce.size() != b->reduce.size() )
return false;
// Reductions should have been added to the conflicts in the same order.
for ( size_t i = 0; i < a->reduce.size(); ++i )
{
if ( a->reduce.at( i ) != b->reduce.at( i ) )
return false;
}
return true;
}
void actions::report_conflict( state* s, const std::vector< conflict* >& conflicts )
{
source_ptr source = _automata->syntax->source;
conflict* cflict = conflicts.front();
// If all reductions and shift in conflict are marked, then don't report it.
bool expected = true;
for ( conflict* cflict : conflicts )
{
if ( cflict->shift && ! cflict->shift->conflicts )
{
expected = false;
}
for ( reduction* reduce : cflict->reduce )
{
if ( ! reduce->drule->conflicts )
{
expected = false;
}
}
}
// Tokens involved in conflict.
std::string report = "conflict on";
for ( conflict* conflict : conflicts )
{
report += " ";
report += source->text( conflict->term->name );
}
report += " ";
if ( cflict->shift )
{
report += "shift/";
}
for ( size_t i = 0; i < cflict->reduce.size(); ++i )
{
if ( i != 0 )
{
report += "/";
}
report += "reduce ";
report += source->text( cflict->reduce.at( i )->drule->nterm->name );
}
srcloc sloc = rule_location( cflict->reduce.front()->drule );
if ( expected )
{
if ( _expected_info )
{
_errors->info( sloc, "%s", report.c_str() );
}
return;
}
_errors->error( sloc, "%s", report.c_str() );
// Work out which token to use in examples.
state* next_state = nullptr;
terminal* next_token = nullptr;
if ( cflict->shift )
{
for ( conflict* conflict : conflicts )
{
// Emulate parse with this potential conflict token.
assert( conflict->shift );
state* test_state = conflict->shift->next;
if ( ! next_state || test_state->accept_distance < next_state->accept_distance )
{
next_state = test_state;
next_token = conflict->term;
}
}
}
else
{
next_token = conflicts.front()->term;
}
// Find left context which successfully supports all conflicting actions.
parse_search_ptr sp;
std::vector< std::pair< rule*, parse_search_ptr > > reducep;
left_search_ptr lsearch = std::make_shared< left_search >( _automata, s );
while ( left_context_ptr lcontext = lsearch->generate() )
{
bool success = true;
if ( cflict->shift )
{
assert( next_state );
sp = std::make_shared< parse_search >( _automata, lcontext );
success = success && sp->shift( next_state, next_token );
}
reducep.clear();
for ( reduction* reduce : cflict->reduce )
{
auto rp = std::make_shared< parse_search >( _automata, lcontext );
success = success && rp->reduce( reduce->drule, next_token );
reducep.emplace_back( reduce->drule, rp );
}
if ( success )
{
break;
}
}
// Perform right-context searches and report results.
if ( sp )
{
sp->search();
report.clear();
report += "shift\n ";
sp->print( &report );
srcloc sloc = cflict->shift->tok.sloc;
_errors->info( sloc, "%s", report.c_str() );
}
for ( const auto& reduce : reducep )
{
reduce.second->search();
report.clear();
report += "reduce ";
report += source->text( reduce.first->nterm->name );
report += "\n ";
reduce.second->print( &report );
_errors->info( rule_location( reduce.first ), "%s", report.c_str() );
}
}
| true |
47acb92f026c51312c764d3b5f625689e89ce25a | C++ | PsymonLi/sw | /platform/drivers/windows/Tools/IonicConfig/NetCfg.cpp | UTF-8 | 9,110 | 2.9375 | 3 | [] | no_license | #include "NetCfg.h"
#define LOCK_TIME_OUT 5000
// Function: ReleaseRef
// Purpose: Release reference.
// Arguments:
// punk [in] IUnknown reference to release.
// Returns: Reference count.
// Notes:
VOID ReleaseRef(IN IUnknown* punk) {
if (punk) {
punk->Release();
}
return;
}
// Function: HrGetINetCfg
// Purpose: Get a reference to INetCfg.
// Arguments:
// fGetWriteLock [in] If TRUE, Write lock.requested.
// lpszAppName [in] Application name requesting the reference.
// ppnc [out] Reference to INetCfg.
// lpszLockedBy [in] Optional. Application who holds the write lock.
// Returns: S_OK on success, otherwise an error code.
HRESULT HrGetINetCfg(IN BOOL fGetWriteLock,
IN LPCWSTR lpszAppName,
OUT INetCfg** ppnc,
OUT LPWSTR* lpszLockedBy) {
INetCfg* pnc = NULL;
INetCfgLock* pncLock = NULL;
HRESULT hr = S_OK;
// Initialize the output parameters.
*ppnc = NULL;
if (lpszLockedBy) {
*lpszLockedBy = NULL;
}
// Initialize COM
hr = CoInitialize(NULL);
if (hr == S_OK) {
// Create the object implementing INetCfg.
hr = CoCreateInstance(CLSID_CNetCfg, NULL, CLSCTX_INPROC_SERVER, IID_INetCfg, (void**)&pnc);
if (hr == S_OK) {
if (fGetWriteLock) {
// Get the locking reference
hr = pnc->QueryInterface(IID_INetCfgLock, (LPVOID*)&pncLock);
if (hr == S_OK) {
// Attempt to lock the INetCfg for read/write
hr = pncLock->AcquireWriteLock(LOCK_TIME_OUT, lpszAppName, lpszLockedBy);
if (hr == S_FALSE) {
hr = NETCFG_E_NO_WRITE_LOCK;
}
}
}
if (hr == S_OK) {
// Initialize the INetCfg object.
hr = pnc->Initialize(NULL);
if (hr == S_OK) {
*ppnc = pnc;
pnc->AddRef();
}
else {
// Initialize failed, if obtained lock, release it
if (pncLock) {
pncLock->ReleaseWriteLock();
}
}
}
ReleaseRef(pncLock);
ReleaseRef(pnc);
}
// In case of error, uninitialize COM.
if (hr != S_OK) {
CoUninitialize();
}
}
return hr;
}
// Function: HrReleaseINetCfg
// Purpose: Get a reference to INetCfg.
// Arguments:
// pnc [in] Reference to INetCfg to release.
// fHasWriteLock [in] If TRUE, reference was held with write lock.
// Returns: S_OK on success, otherwise an error code.
HRESULT HrReleaseINetCfg(IN INetCfg* pnc,
IN BOOL fHasWriteLock) {
INetCfgLock* pncLock = NULL;
HRESULT hr = S_OK;
// Uninitialize INetCfg
hr = pnc->Uninitialize();
// If write lock is present, unlock it
if (hr == S_OK && fHasWriteLock) {
// Get the locking reference
hr = pnc->QueryInterface(IID_INetCfgLock, (LPVOID*)&pncLock);
if (hr == S_OK) {
hr = pncLock->ReleaseWriteLock();
ReleaseRef(pncLock);
}
}
ReleaseRef(pnc);
// Uninitialize COM.
CoUninitialize();
return hr;
}
// Function: HrGetComponentEnum
// Purpose: Get network component enumerator reference.
// Arguments:
// pnc [in] Reference to INetCfg.
// pguidClass [in] Class GUID of the network component.
// ppencc [out] Enumerator reference.
// Returns: S_OK on success, otherwise an error code.
HRESULT HrGetComponentEnum(INetCfg* pnc,
IN const GUID* pguidClass,
OUT IEnumNetCfgComponent** ppencc) {
INetCfgClass* pncclass;
HRESULT hr;
*ppencc = NULL;
// Get the class reference.
hr = pnc->QueryNetCfgClass(pguidClass, IID_INetCfgClass, (PVOID*)&pncclass);
if (hr == S_OK) {
// Get the enumerator reference.
hr = pncclass->EnumComponents(ppencc);
// We don't need the class reference any more.
ReleaseRef(pncclass);
}
return hr;
}
// Function: HrGetFirstComponent
// Purpose: Enumerates the first network component.
// Arguments:
// pencc [in] Component enumerator reference.
// ppncc [out] Network component reference.
// Returns: S_OK on success, otherwise an error code.
HRESULT HrGetFirstComponent(IN IEnumNetCfgComponent* pencc,
OUT INetCfgComponent** ppncc) {
HRESULT hr;
ULONG ulCount;
*ppncc = NULL;
pencc->Reset();
hr = pencc->Next(1, ppncc, &ulCount);
return hr;
}
// Function: HrGetNextComponent
// Purpose: Enumerate the next network component.
// Arguments:
// pencc [in] Component enumerator reference.
// ppncc [out] Network component reference.
// Returns: S_OK on success, otherwise an error code.
// Notes: The function behaves just like HrGetFirstComponent if
// it is called right after HrGetComponentEnum.
HRESULT HrGetNextComponent(IN IEnumNetCfgComponent* pencc,
OUT INetCfgComponent** ppncc) {
HRESULT hr;
ULONG ulCount;
*ppncc = NULL;
hr = pencc->Next(1, ppncc, &ulCount);
return hr;
}
#include <iostream>
#include <iomanip>
std::ostream& operator<<(std::ostream& os, REFGUID guid) {
os << std::uppercase;
os.width(8);
os << std::hex << std::setfill('0') << guid.Data1 << '-';
os.width(4);
os << std::hex << std::setfill('0') << guid.Data2 << '-';
os.width(4);
os << std::hex << std::setfill('0') << guid.Data3 << '-';
os.width(2);
os << std::hex << std::setfill('0')
<< static_cast<short>(guid.Data4[0])
<< static_cast<short>(guid.Data4[1])
<< '-'
<< static_cast<short>(guid.Data4[2])
<< static_cast<short>(guid.Data4[3])
<< static_cast<short>(guid.Data4[4])
<< static_cast<short>(guid.Data4[5])
<< static_cast<short>(guid.Data4[6])
<< static_cast<short>(guid.Data4[7]);
os << std::nouppercase;
return os;
}
void DisplayInterface(PCWSTR strName) {
INetCfg* pnetcfg = NULL;
INetCfgComponent* pncfgcomp = NULL;
IEnumNetCfgComponent* pencc;
HRESULT hr = S_OK;
LPWSTR strDevDesc = NULL;
GUID InstanceGuid;
DWORD Status = 0;
bool bIonicComponent = false;
std::ios state(NULL);
state.copyfmt(std::cout);
hr = HrGetINetCfg(FALSE, L"IonicConfig", &pnetcfg, NULL);
if (hr == S_OK) {
hr = HrGetComponentEnum(pnetcfg, &GUID_DEVCLASS_NET, &pencc);
if (hr == S_OK) {
hr = HrGetFirstComponent(pencc, &pncfgcomp);
while (hr == S_OK) {
bIonicComponent = false;
//std::cout << std::endl;
hr = pncfgcomp->GetDisplayName(&strDevDesc);
if (S_OK == hr) {
if (wcscmp(strDevDesc, strName) == 0) {
//std::wcout << L"Device desc: " << strDevDesc << std::endl;
bIonicComponent = true;
}
CoTaskMemFree(strDevDesc);
strDevDesc = NULL;
}
if (bIonicComponent) {
hr = pncfgcomp->GetInstanceGuid(&InstanceGuid);
if (S_OK == hr) {
std::cout << "\tNetCfgID:\t" << InstanceGuid << std::endl;
}
hr = pncfgcomp->GetPnpDevNodeId(&strDevDesc);
if (hr == S_OK) {
std::wcout << L"\tDev Node Id:\t" << strDevDesc << std::endl;
CoTaskMemFree(strDevDesc);
strDevDesc = NULL;
}
hr = pncfgcomp->GetBindName(&strDevDesc);
if (hr == S_OK) {
std::wcout << L"\tBind Name:\t" << strDevDesc << std::endl;
CoTaskMemFree(strDevDesc);
strDevDesc = NULL;
}
hr = pncfgcomp->GetDeviceStatus(&Status);
if (hr == S_OK) {
std::cout << "\tDevice Status:\t0x" << std::hex << std::setfill('0') << std::setw(8) << std::right << Status << std::endl;
CoTaskMemFree(strDevDesc);
strDevDesc = NULL;
}
}
ReleaseRef(pncfgcomp);
hr = HrGetNextComponent(pencc, &pncfgcomp);
}
ReleaseRef(pencc);
}
else {
std::cout << "IEnumNetCfgComponent not found. Err:" << hr;
}
hr = pnetcfg->Apply();
HrReleaseINetCfg(pnetcfg, TRUE);
}
std::cout.copyfmt(state);
}
| true |
4915ba9381212e4b8fdce968e95fdf40a214620f | C++ | yakirzhang/Learnning_project | /DesignModel/MainSecen.cpp | UTF-8 | 276 | 2.53125 | 3 | [] | no_license | #include <IntFloatPort.h>
#include <iostream>
#include <string>
#include <memory>
using namespace std;
int main() {
IntFloatPort port(5557);
int a=0;
float b=0;
while(cin>>a>>b){
auto s = std::make_shared<IntFloatPort::Sendingthings>(a,b);
port.Send(s);
}
} | true |
6965e32fb8b60fcaf011a8842c9704231e9a06ac | C++ | FenrisChimera8898/2020-10-27-GD1P04-SUMMATIVE3-BaileyJohnson | /Source/Summative3/main.cpp | UTF-8 | 3,312 | 2.78125 | 3 | [] | no_license | //
// Bachelor of Software Engineering
// Media Design School
// Auckland
// New Zealand
//
// (c) 2020 Media Design School
//
// File Name : main.cpp
// Description : Main driver code. runs the opengl Render, Update, and Shutdown Fucntions. Also pass through keyboard input.
// Author : Bailey Johnson
// Mail : bailey.johnson@mds.ac.nz
//
// Library Includes
#include <glew.h>
#include <freeglut.h>
#include <iostream>
#include <time.h>
// Local Includes
#include "ShaderLoader.h"
#include "GameManager.h"
#include "Input.h"
// This Include
// Variables
Audio* audio;
Input* input;
Menu* menu;
float PreviousTimeStamp;
bool keyBuffer[256];
// Function Prototypes
void Render();
void Update();
void ShutDown();
void Keyboard(unsigned char key, int x, int y);
void KeyboardUp(unsigned char key, int x, int y);
void SpecialKeyboard(int key, int x, int y);
// Implementation
int main(int argc, char** argv)
{
//glut and glew initialisation
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowPosition(50, 50);
glutInitWindowSize(900, 900);
glutCreateWindow("Summative 3 - Bailey Johnson");
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
if (glewInit() != GLEW_OK)
{
std::cout << "GLEW initialisation has failed. Terminating application." << std::endl;
return 0;
}
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
//Create and play background audio to run throughout the whole program
audio = new Audio("backgroundAudio.wav");
audio->audioSystem->playSound(audio->FX_Thump, 0, false, 0);
//Create Input
input = new Input();
//Create Menu
menu = new Menu();
//Previous Time for DeltaTime
PreviousTimeStamp = (float)glutGet(GLUT_ELAPSED_TIME);
//glut Functions
glutDisplayFunc(Render);
glutIdleFunc(Update);
glutCloseFunc(ShutDown);
glutKeyboardFunc(Keyboard);
glutKeyboardUpFunc(KeyboardUp);
glutSpecialFunc(SpecialKeyboard);
glutMainLoop();
return 0;
}
void Render()
{
//All Render Code here
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
//Render Game if bool is true, else Render Menu
if (GameManager::playing == true)
{
input->game->Render();
}
else
{
menu->Render(input->menuSelection);
}
glutSwapBuffers();
}
void Update()
{
//All Update Code here
//Delta Time
float CurrentTimeStamp = (float)glutGet(GLUT_ELAPSED_TIME);
float DeltaTime = (CurrentTimeStamp - PreviousTimeStamp) * 0.001f;
PreviousTimeStamp = CurrentTimeStamp;
//If game is running then update game object update function
if (GameManager::playing == true)
{
input->game->Update(DeltaTime);
}
//Pass Delta time in to Input
input->inDelta = DeltaTime;
//Update Audio
audio->audioSystem->update();
glutPostRedisplay();
}
//Shutdown - Delete objects
void ShutDown()
{
delete audio;
delete input;
delete menu;
}
//Listen for keyboard down events - send information to Input
void Keyboard(unsigned char key, int x, int y)
{
keyBuffer[key] = true;
input->KeyBoardInput(key, x, y, keyBuffer);
}
//Listen for keyboard up events - send information to Input
void KeyboardUp(unsigned char key, int x, int y)
{
keyBuffer[key] = false;
}
//Listen for keyboard down events of special keys - send information to Input
void SpecialKeyboard(int key, int x, int y)
{
input->SpecialKeyboardInput(key, x, y);
} | true |
cf04b3fada4ba01f8aeab5566b48865dd2ea3864 | C++ | cies96035/CPP_programs | /Kattis/AC/outofsorts.cpp | UTF-8 | 883 | 2.65625 | 3 | [] | no_license | #include<iostream>
using namespace std;
using ll = long long;
const int MAX_N = 1000100;
ll n, m, a, c, x, cnt;
int arr[MAX_N];
bool Search(const int &x, const int &pos, int l, int h){
int m = (l + h) / 2;
if(arr[m] == x){
return true;
}
if(arr[m] > x && m > pos){
return Search(x, pos, l, m - 1);
}
if(arr[m] < x && m < pos){
return Search(x, pos, m + 1, h);
}
return false;
}
int main()
{
cin.tie(0);
ios_base::sync_with_stdio(0);
cin >> n >> m >> a >> c >> x;
a %= m;
c %= m;
x %= m;
for(ll i = 0; i < n; i++){
x = a * x + c;
if(x >= m){
x %= m;
}
arr[i] = x;
}
for(int i = 0; i < n; i++){
if( Search( arr[i], i, 0, n - 1) ){
cnt++;
}
}
cout << cnt << '\n';
return 0;
}
| true |
9368356a29e356b4b8105d2da23a4805a4a1e56d | C++ | cloudplugs/rest-arduino | /examples/CloudPlugsESP8266Example/CloudPlugsESP8266Example.ino | UTF-8 | 1,936 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | #include <ESP8266WiFi.h>
#include <CloudPlugs.h>
#define AUTH_PLUGID "dev-xxxxxxxxxxxxxxxxxx" /**< The device plug ID */
#define AUTH_PASS "your-password" /**< The master password */
#define AUTH_MASTER true
char ssid[] = "YOUR_SSID"; /* your network SSID (name) */
char pass[] = "YOUR_WIFI_PASSPHRASE"; /* your network password (use for WPA, or use as key for WEP) */
int status = WL_IDLE_STATUS;
WiFiClient wClient;
CloudPlugs client(wClient);
String response;
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI): ");
Serial.print(rssi);
Serial.println(" dBm \n");
}
void setup() {
// initialize serial communications at 9600 bps
Serial.begin(9600);
/* Attempt to connect to Wifi network */
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
delay(10000);
}
Serial.println("Connected to wifi");
printWifiStatus();
response = "";
client.setAuth(AUTH_PLUGID, AUTH_PASS, AUTH_MASTER);
}
void debug(const char* tag, bool res, String& response){
Serial.print(tag);
if (res) Serial.print(" ERROR: "); else Serial.print(": ");
Serial.print(client.getLastHttpResult());
Serial.print(" - ");
Serial.println(response);
}
void loop() {
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI): ");
Serial.print(rssi);
Serial.println(" dBm \n");
Serial.print("LOOP: ");
String body = "{\"data\":";
body.concat(getTemp());
body.concat("}");
bool res = client.publishData("temperature", body.c_str(), response);
debug("PUBLISH", res, response);
delay(60000);
}
long getTemp() {
return random(100);
}
| true |
cfbce5e5ed71c08736d3f81bc0d6bec5e6cb2238 | C++ | Williams3DWorld/ExileEngine | /Editor/LogicManager.cpp | UTF-8 | 715 | 2.625 | 3 | [] | no_license | #include "LogicManager.h"
void LogicManager::CloneDynamics()
{
if (!_dynamic_actors.empty())
_dynamic_actors.clear();
for (std::shared_ptr<Actor> a : World::map->GetActors())
{
if (a->IsDynamic())
{
_dynamic_actors.reserve(1);
_dynamic_actors.emplace_back(a); // Clone instance of actor
}
}
}
void LogicManager::CompileDynamics()
{
if (World::map->GetActors().empty())
{
#ifdef _DEBUG
ExCore::Logger::PrintErr("Failed to compile dynamic actors - list is empty!");
#endif
return;
}
CloneDynamics();
}
void LogicManager::Update()
{
for (auto i = 0; i < _dynamic_actors.size(); ++i)
_dynamic_actors[i]->Update();
}
std::vector<std::shared_ptr<Actor>> LogicManager::_dynamic_actors; | true |
2a0e5202af4a0345197a28bf2f98c62001f8d40e | C++ | stomachacheGE/leetcode | /73.矩阵置零.cpp | UTF-8 | 2,022 | 3.734375 | 4 | [] | no_license | /*
* @lc app=leetcode.cn id=73 lang=cpp
*
* [73] 矩阵置零
*/
// @lc code=start
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
// Solution one
// 用两个set分别记录哪些行和哪些列需要置为0
// 但是额外空间是O(m+n)不符合题目要求
// Solution two
// Ref.:https://leetcode-cn.com/problems/set-matrix-zeroes/solution/ju-zhen-zhi-ling-by-leetcode/
// 不用额外空间,而用第一行和第一列是否为0来标记对应的那一行那一列是否该为0
// 注意matrix[0][0]既代表第一行,又代表第一列,因此需要一个额外位来区分行或者列
int m = matrix.size();
if (m == 0) return;
int n = matrix[0].size();
// 第一列单独处理
bool firstRow = false;
for (int i=0; i<n; i++) {
if (matrix[0][i] == 0) firstRow = true;
}
// 用第一行第一列来标记是否置零
for (int i=1; i<m; i++) {
for (int j=0; j<n; j++) { // 注意j从0开始,来判断第一列是不是该置零
if (matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
// 置零
bool firstColumn = matrix[0][0] == 0;
for (int i=1; i<n; i++) {
if (matrix[0][i] == 0) {
for (int j=1; j<m; j++) matrix[j][i] = 0;
}
}
for (int i=1; i<m; i++) {
if (matrix[i][0] == 0) {
for (int j=1; j<n; j++) matrix[i][j] = 0;
}
}
// cout << "firstRow: " << firstRow << ", firstColumn: " << firstColumn << endl;
// 第一行和第一列必须在其他置零后才能置零
if (firstRow) {
for (int i=0; i<n; i++) matrix[0][i] = 0;
}
if (firstColumn) {
for (int i=0; i<m; i++) matrix[i][0] = 0;
}
}
};
// @lc code=end
| true |
b154203e90a143dcd8e80d0d36dc7235a746988e | C++ | secretBackupThatDefinitelyWontBeFound/shhhhh | /MatrixToString.cpp | UTF-8 | 1,565 | 3.21875 | 3 | [] | no_license | //
// Created by to on 1/14/19.
//
#include "MatrixToString.h"
string MatrixToString::problemToString(SearchableMatrix &p) {
std::string answer = p.matrixToString();
pair<int, int> temp_pair = p.getInitialState()->getValue();
answer += "/" + to_string(temp_pair.first) + "," + to_string(temp_pair.second);
temp_pair = p.getGoalState()->getValue();
answer += "/" + to_string(temp_pair.first) + "," + to_string(temp_pair.second);
return answer;
}
string MatrixToString::solutionToString(vector<string> &s) {
std::string answer;
for (auto str : s) {
answer += str + ",";
}
answer = answer.substr(0, answer.size() - 1);
return answer;
}
SearchableMatrix MatrixToString::stringToProblem(std::string &s) {
std::string sep_lines = "/";
std::vector<std::string> lines = split(s, sep_lines);
std::vector<std::vector<std::string>> matrix_str;
std::string separator = ",";
for (int i = 0; i < lines.size() - 2; ++i) {
matrix_str.push_back(split(lines[i], separator));
}
std::vector<std::string> singal_state;
singal_state = split(lines[lines.size() - 2], separator);
std::pair<std::string, std::string> start(singal_state[0], singal_state[1]);
singal_state = split(lines[lines.size() - 1], separator);
std::pair<std::string, std::string> goal(singal_state[0], singal_state[1]);
return SearchableMatrix(matrix_str, start, goal);
}
vector<string> MatrixToString::stringToSolution(std::string &s) {
std::string sep = ",";
return this->split(s, sep);
}
| true |
61e168d0befdffc2176cbf8a281c8fbadae5512c | C++ | MikeMitterer/cpp-gpio | /include/GPIO.h | UTF-8 | 2,289 | 2.8125 | 3 | [] | no_license | //
// Created by Mike Mitterer on 22.07.16.
//
#ifndef RASPIHELLOWORLD_GPIO_H
#define RASPIHELLOWORLD_GPIO_H
//#include <RF24/nRF24L01.h>
//#include <RF24/RF24.h>
#include <functional>
/*! was 1 - This means pin HIGH, true, 3.3volts on a pin. */
#undef HIGH
/*! was 0 - This means pin LOW, false, 0volts on a pin. */
#undef LOW
// RV24 definiert eigenes delay!
#undef delay
/**
* Example GPIO.h file
*
* @defgroup GPIO GPIO Example
*
* See RF24_arch_config.h for additional information
* @{
*/
namespace mm {
namespace gpio {
class Board {
private:
bool initialized = false;
public:
/// Necessary!!!!
/// Returns true if it succeeds - otherwise it returns false
bool init();
virtual ~Board();
private:
};
class Pin {
public:
enum class Direction {
INPUT, OUTPUT, UNDEFINED
};
enum class InputState {
/*! This means pin HIGH, true, 3.3volts on a pin. */
HIGH,
/*! This means pin LOW, false, 0volts on a pin. */
LOW
};
enum class OutputState { ON, OFF};
private:
const uint8_t pin;
Direction direction = Direction::UNDEFINED;
std::function<void (Pin& pin)> closing = [] (Pin& pin) { printf("Closing function!\n"); };
public:
Pin(const uint8_t pinParam) : pin{pinParam} {
}
Pin(const uint8_t pinParam,std::function<void (Pin& pin)> closing) : pin{pinParam} {
mode(direction);
this->closing = closing;
}
~Pin() {
closing(*this);
}
const Direction& mode(const Direction& direction);
InputState read();
void write(const OutputState state);
friend std::ostream &operator<<(std::ostream &os, const Pin &pin);
};
void delay(int8_t milliseconds);
std::ostream &operator<<(std::ostream &os, const Pin::Direction& direction);
std::ostream &operator<<(std::ostream &os, const Pin::OutputState& outputState);
}
}
#endif //RASPIHELLOWORLD_GPIO_H
| true |
53dcd4bcd00912798c9b9cc247a35ec01e72d515 | C++ | DoraSzasz/registration | /itk_source/lib/StackIOHelpers.hpp | UTF-8 | 3,946 | 2.609375 | 3 | [
"MIT"
] | permissive | #ifndef STACKIOHELPERS_HHP_
#define STACKIOHELPERS_HHP_
#include <assert.h>
#include "boost/filesystem.hpp"
#include "itkTransformFileReader.h"
#include "itkTransformFileWriter.h"
#include "itkTranslationTransform.h"
#include "itkTransformFactory.h"
#include "Stack.hpp"
#include "StackTransforms.hpp"
#include "Dirs.hpp"
#include "IOHelpers.hpp"
using namespace boost::filesystem;
// Stack Persistence
template <typename StackType>
void Save(StackType& stack, const string& directory)
{
vector< string > transformPaths = constructPaths(directory, stack.GetBasenames());
for(int slice_number=0; slice_number < stack.GetSize(); ++slice_number)
{
writeTransform(stack.GetTransform(slice_number), transformPaths[slice_number]);
}
}
template <typename StackType>
void Load(StackType& stack, const string& directory)
{
vector< string > transformPaths = constructPaths(directory, stack.GetBasenames());
// Some transforms might not be registered
// with the factory so we add them manually
itk::TransformFactoryBase::RegisterDefaultTransforms();
// TODO: below registers a new version of transform every time Load() is called
itk::TransformFactory< itk::TranslationTransform< double, 2 > >::RegisterTransform();
typename StackType::TransformVectorType newTransforms;
for(unsigned int slice_number=0; slice_number<stack.GetSize(); ++slice_number)
{
itk::TransformBase::Pointer transformBase = readTransform( transformPaths[slice_number] );
typename StackType::TransformType::Pointer transform = static_cast<typename StackType::TransformType*>( transformBase.GetPointer() );
newTransforms.push_back( transform );
}
stack.SetTransforms(newTransforms);
}
template <typename StackType>
void ApplyAdjustments(StackType& stack, const string& directory)
{
// construct path to config transform file
// e.g. config/Rat28/LoRes_adustments/0053.meta
vector< string > transformPaths = constructPaths(directory, stack.GetBasenames());
// Some transforms might not be registered
// with the factory so we add them manually
itk::TransformFactoryBase::RegisterDefaultTransforms();
itk::TransformFactory< itk::TranslationTransform< double, 2 > >::RegisterTransform();
typename StackType::TransformVectorType newTransforms;
for(unsigned int slice_number=0; slice_number<stack.GetSize(); ++slice_number)
{
if( exists(transformPaths[slice_number]) )
{
itk::TransformBase::Pointer transform = readTransform( transformPaths[slice_number] );
// convert Array to Vector
itk::Array< double > parameters( transform->GetParameters() );
itk::Vector< double, 2 > translation;
translation[0] = parameters[0];
translation[1] = parameters[1];
// translate block image
StackTransforms::Translate<StackType>(stack, translation, slice_number );
}
}
}
template <typename DataType>
void saveVectorToFiles(const vector< DataType >& values, const string& dirName, const vector< string >& fileNames)
{
assert(values.size() == fileNames.size());
path dirPath = Dirs::ResultsDir() + dirName;
create_directory(dirPath);
for(unsigned int i=0; i<values.size(); ++i)
{
path leafName = basename( path(fileNames[i]).leaf() );
path outPath = dirPath / leafName;
ofstream outFile(outPath.string().c_str());
outFile << values[i] << endl;
}
}
template <typename DataType>
vector< DataType > loadVectorFromFiles(const string& dirName, const vector< string >& fileNames)
{
path dirPath = Dirs::ResultsDir() + dirName;
typename vector< DataType >::size_type numberOfFiles = fileNames.size();
vector< DataType > values(numberOfFiles);
for(unsigned int i=0; i<numberOfFiles; ++i)
{
path inPath = dirPath / basename( path(fileNames[i]).leaf() );
ifstream inFile(inPath.string().c_str());
assert(inFile.is_open());
inFile >> values[i];
}
return values;
}
#endif
| true |
c3978dcac9263ecc6d1c7c01d75ddef07934ebaf | C++ | dbriemann/lemon | /BitBoard.hpp | UTF-8 | 42,790 | 2.8125 | 3 | [] | no_license | #ifndef BITBOARD_HPP
#define BITBOARD_HPP
#include <sstream>
#include <cstring> //memcpy
using namespace std;
#include "lemon.hpp"
#include "utility_functions.hpp"
#include "utility_constants.hpp"
#include "Move.hpp"
#include "MoveList.hpp"
struct BitBoard {
/*
* BitBoards
*/
//TODO combine to one array?
U64 pieces_by_color_bb[2];
U64 pieces_by_type_bb[6];
/*
* Arrays to help in certain situation
*/
//U8 occupancy[64];
U8 kings[2];
//wrap all following into one U32?
bool castle_short[2];
bool castle_long[2];
bool is_check;
Square en_passent_sq;
U8 draw_counter;
U8 move_number;
U8 player;
/*
* Constructors, copy-constructor, destructor
* move constructor?, move assignment operator?
* operators and related stuff
*/
BitBoard();
BitBoard(const BitBoard &other);
BitBoard& operator=(const BitBoard &other);
/*
* Utility methods
*/
inline void zeroAll();
U8 get(Square line, Square rank) const;
void set(Square line, Square rank, OccupancyType type);
void setFENPosition(string fen);
string getFENCode() const;
void setStartingPosition();
void print() const;
/*
* Move generation methods
*/
inline void genPseudoLegalMoves(MoveList &mlist);
inline void genKnightMoves(MoveList &mlist);
inline void genPawnMoves(MoveList &mlist);
inline void genKingMoves(MoveList &mlist);
inline void genRookMoves(MoveList &mlist);
inline void genBishopMoves(MoveList &mlist);
inline void genQueenMoves(MoveList &mlist);
inline U64 genRankAttacks(const U64 occ, const U8 sq);
inline U64 genFileAttacks(U64 occ, const U8 sq);
inline U64 genDiagAttacks(U64 occ, const U8 sq);
inline U64 genAntiDiagAttacks(U64 occ, const U8 sq);
/*
* Move execution methods
*/
inline bool makeLightMove(Move m);
//bool makeMoveIfLegal(Move m);
inline U64 isAttackedBy(const U64 targets_bb, const U8 atk_color);
};
BitBoard::BitBoard() {
zeroAll(); //bitboards
player = WHITE;
castle_long[WHITE] = castle_long[BLACK] = castle_short[WHITE] = castle_short[BLACK] = true;
kings[WHITE] = kings[BLACK] = 0;
en_passent_sq = NONE;
draw_counter = 0;
move_number = 1;
is_check = false;
// for(int i = 0; i < BOARD_SIZE*BOARD_SIZE; i++) {
// this->occupancy[i] = EMPTY;
// }
}
BitBoard::BitBoard(const BitBoard& other) {
for(int c = WHITE; c <= BLACK; c++) {
this->pieces_by_color_bb[c] = other.pieces_by_color_bb[c];
this->castle_long[c] = other.castle_long[c];
this->castle_short[c] = other.castle_short[c];
this->kings[c] = other.kings[c];
}
for(int t = PAWN; t <= KING; t++) {
this->pieces_by_type_bb[t] = other.pieces_by_type_bb[t];
}
this->is_check = other.is_check;
this->en_passent_sq = other.en_passent_sq;
this->draw_counter = other.draw_counter;
this->move_number = other.move_number;
this->player = other.player;
// for(int i = 0; i < BOARD_SIZE*BOARD_SIZE; i++) {
// this->occupancy[i] = other.occupancy[i];
// }
}
//TEST
BitBoard& BitBoard::operator=(const BitBoard &other) {
memcpy(this, &other, sizeof(BitBoard));
return *this;
}
/*
BitBoard& BitBoard::operator=(const BitBoard& other) {
for(int c = WHITE; c <= BLACK; c++) {
this->pieces_by_color_bb[c] = other.pieces_by_color_bb[c];
this->castle_long[c] = other.castle_long[c];
this->castle_short[c] = other.castle_short[c];
this->kings[c] = other.kings[c];
}
for(int t = PAWN; t <= KING; t++) {
this->pieces_by_type_bb[t] = other.pieces_by_type_bb[t];
}
this->en_passent_sq = other.en_passent_sq;
this->draw_counter = other.draw_counter;
this->move_number = other.move_number;
this->player = other.player;
this->is_check = other.is_check;
// for(int i = 0; i < BOARD_SIZE*BOARD_SIZE; i++) {
// this->occupancy[i] = other.occupancy[i];
// }
return *this;
}*/
inline
void BitBoard::zeroAll() {
pieces_by_color_bb[WHITE] = pieces_by_color_bb[BLACK] = C64(0);
for(int i = PAWN; i <= KING; i++) {
pieces_by_type_bb[i] = C64(0);
}
// for(int i = 0; i < BOARD_SIZE*BOARD_SIZE; i++) {
// occupancy[i] = EMPTY;
// }
}
/*
* executes a move and checks for legality
* returns true if the move was legal and executed properly
* returns false if the move was not legal. in this case
* the board will remain in an undefined/broken state
* user has to make sure the board gets replaced with a proper
* valid board.
* works only with copy/make functionality. remains in illegal
* state to increase performance.
*/
inline
bool BitBoard::makeLightMove(Move m) {
//cout << "Try move: " << moveToStr(m) << endl;
/*
* extraction of move features
*/
const U8 opponent = FLIP(player);
const U32 from = moveGetFeature(m, FROM_MASK, FROM_SHIFT);
const U32 to = moveGetFeature(m, TO_MASK, TO_SHIFT);
const U32 ptype = moveGetFeature(m, PIECE_MASK, PIECE_SHIFT);
const U32 capflag = moveGetFeature(m, CAPTURE_MASK, CAPTURE_SHIFT);
const U32 eptype = moveGetFeature(m, EP_MASK, EP_SHIFT);
const U32 promtype = moveGetFeature(m, PROMOTION_MASK, PROMOTION_SHIFT);
//reset ep square
//const U8 target_piece = occupancy[to];
en_passent_sq = NONE;
U64 check_bb = 0;
/*
* begin moving the piece by removing it from the
* <from> position of its corresponding bbs
* then swap <from> and <to> positions on the
* occupancy helper board
*/
pieces_by_color_bb[player] &= ~iBitMask(from);
pieces_by_type_bb[ptype] &= ~iBitMask(from);
//swap(occupancy[from], occupancy[to]);
/*
* in case of a capture remove the
* opponent's piece from its bbs
*/
if(capflag) {
if(eptype == EP_TYPE_CAPTURE) {
//captured pawn is one step ahead of <to>
U8 pbit = to - PAWN_MOVE_DIRECTIONS[player];
pieces_by_color_bb[opponent] &= ~iBitMask(pbit);
//pieces_by_type_bb[occupancy[pbit]] &= ~iBitMask(pbit); //already swapped..from<->to
pieces_by_type_bb[PAWN] &= ~iBitMask(pbit); //already swapped..from<->to
//occupancy[pbit] = EMPTY;
} else {
U64 kill_bb = ~iBitMask(to);
pieces_by_color_bb[opponent] &= kill_bb;
//pieces_by_type_bb[occupancy[from]] &= ~iBitMask(to); //already swapped..from<->to
pieces_by_type_bb[PAWN] &= kill_bb;
pieces_by_type_bb[KNIGHT] &= kill_bb;
pieces_by_type_bb[BISHOP] &= kill_bb;
pieces_by_type_bb[ROOK] &= kill_bb;
pieces_by_type_bb[QUEEN] &= kill_bb;
//check if capture disables opponent
//from future castling by capturing a rook
//if(target_piece == ROOK) {
if(to == CASTLE_SHORT_ROOK[opponent]) {
castle_short[opponent] = false;
} else if(to == CASTLE_LONG_ROOK[opponent]) {
castle_long[opponent] = false;
}
//}
}
//reset draw counter
draw_counter = 0;
} else {
//special non capture moves
if(ptype == PAWN) {
draw_counter = 0;
if(eptype == EP_TYPE_CREATE) {
en_passent_sq = to - PAWN_MOVE_DIRECTIONS[player];
}
} else if(ptype == KING) {
const U32 castleflag = moveGetFeature(m, CASTLE_MASK, CASTLE_SHIFT);
if(castleflag) {
if(to == CASTLE_SHORT_TARGET[player]) {
check_bb |= CASTLE_SHORT_PATH[player];
if(is_check || isAttackedBy(check_bb, FLIP(player))) {
//cout << "CASTLE SHORT CANCEL" << endl;
return false;
}
//castle short
//move rook..
//swap(occupancy[CASTLE_SHORT_ROOK[player]], occupancy[CASTLE_SHORT_ROOK_TARGET[player]]);
pieces_by_color_bb[player] &= ~iBitMask(CASTLE_SHORT_ROOK[player]);
pieces_by_color_bb[player] |= iBitMask(CASTLE_SHORT_ROOK_TARGET[player]);
pieces_by_type_bb[ROOK] &= ~iBitMask(CASTLE_SHORT_ROOK[player]);
pieces_by_type_bb[ROOK] |= iBitMask(CASTLE_SHORT_ROOK_TARGET[player]);
} else {
check_bb |= CASTLE_LONG_CHECK_PATH[player];
if(is_check || isAttackedBy(check_bb, FLIP(player))) {
//cout << "CASTLE LONG CANCEL" << endl;
return false;
}
//castle long
//move rook..
//swap(occupancy[CASTLE_LONG_ROOK[player]], occupancy[CASTLE_LONG_ROOK_TARGET[player]]);
pieces_by_color_bb[player] &= ~iBitMask(CASTLE_LONG_ROOK[player]);
pieces_by_color_bb[player] |= iBitMask(CASTLE_LONG_ROOK_TARGET[player]);
pieces_by_type_bb[ROOK] &= ~iBitMask(CASTLE_LONG_ROOK[player]);
pieces_by_type_bb[ROOK] |= iBitMask(CASTLE_LONG_ROOK_TARGET[player]);
}
}
}
}
if(ptype == ROOK) {
//disable castling on rook moves
if(from == CASTLE_SHORT_ROOK[player]) {
castle_short[player] = false;
} else if(from == CASTLE_LONG_ROOK[player]) {
castle_long[player] = false;
}
} else if(ptype == KING) {
kings[player] = to;
//king moves always disable all castling rights
castle_long[player] = false;
castle_short[player] = false;
}
/*
* finally add the moving piece to its destination
* position on its corresponding bbs
*/
pieces_by_color_bb[player] |= iBitMask(to);
pieces_by_type_bb[ptype] |= iBitMask(to);
//promotion..
if(promtype != EMPTY) {
//occupancy[to] = promtype;
pieces_by_type_bb[PAWN] &= ~iBitMask(to);
pieces_by_type_bb[promtype] |= iBitMask(to);
}
//check for check
check_bb = iBitMask(kings[player]);
if(isAttackedBy(check_bb, FLIP(player))) {
//cout << "ATTACK CHECK CANCEL" << endl;
return false;
}
/*
* finish everything
*/
//delete from helper board
//occupancy[from] = EMPTY; //already swapped..from<->to
//switch player
player = FLIP(player);
if(player == WHITE) {
move_number++;
}
//determine check status
if(isAttackedBy(iBitMask(kings[player]), FLIP(player))) {
is_check = true;
} else {
is_check = false;
}
return true;
}
//bool BitBoard::makeMoveIfLegal(Move m) {
// /*
// * temporary variables
// * and extraction of move features
// */
// bool success = true;
// const U8 opponent = FLIP(player);
// const U32 from = moveGetFeature(m, FROM_MASK, FROM_SHIFT);
// const U32 to = moveGetFeature(m, TO_MASK, TO_SHIFT);
// const U32 ptype = moveGetFeature(m, PIECE_MASK, PIECE_SHIFT);
// const U32 capflag = moveGetFeature(m, CAPTURE_MASK, CAPTURE_SHIFT);
// const U32 eptype = moveGetFeature(m, EP_MASK, EP_SHIFT);
// const U32 promtype = moveGetFeature(m, PROMOTION_MASK, PROMOTION_SHIFT);
// /*
// * backup game state specific variables
// * in case the move is illegal and
// * must be reverted in place
// */
// bool castle_000[2];
// castle_000[WHITE] = castle_long[WHITE];
// castle_000[BLACK] = castle_long[BLACK];
// bool castle_00[2];
// castle_00[WHITE] = castle_short[WHITE];
// castle_00[BLACK] = castle_short[BLACK];
// U8 draw = draw_counter;
// U8 ep = en_passent_sq;
// //remember piece types?
// //const U8 from_piece = occupancy[from];
// const U8 to_piece = occupancy[to];
// //cout << intToString(ptype) << " " << intToString(to_piece) << endl;
// //reset ep square
// en_passent_sq = NONE;
// /*
// * begin moving the piece by removing it from the
// * <from> position of its corresponding bbs
// * then swap <from> and <to> positions on the
// * occupancy helper board
// */
// pieces_by_color_bb[player] &= ~iBitMask(from);
// pieces_by_type_bb[ptype] &= ~iBitMask(from);
// swap(occupancy[from], occupancy[to]);
// /*
// * in case of a capture remove the
// * opponent's piece from its bbs
// */
// if(capflag) {
// if(eptype == EP_TYPE_CAPTURE) {
// //captured pawn is one step ahead of <to>
// U8 pbit = to - PAWN_MOVE_DIRECTIONS[player];
// pieces_by_color_bb[opponent] &= ~iBitMask(pbit);
// pieces_by_type_bb[occupancy[pbit]] &= ~iBitMask(pbit); //already swapped..from<->to
// occupancy[pbit] = EMPTY;
// } else {
// pieces_by_color_bb[opponent] &= ~iBitMask(to);
// pieces_by_type_bb[occupancy[from]] &= ~iBitMask(to); //already swapped..from<->to
// //check if capture disables opponent
// //from future castling by capturing a rook
// if(to_piece == ROOK) {
// if(to == CASTLE_SHORT_ROOK[opponent]) {
// castle_short[opponent] = false;
// } else if(to == CASTLE_LONG_ROOK[opponent]) {
// castle_long[opponent] = false;
// }
// }
// }
// //reset draw counter
// draw_counter = 0;
// } else {
// const U32 castleflag = moveGetFeature(m, CASTLE_MASK, CASTLE_SHIFT);
// //special non capture moves
// if(eptype == EP_TYPE_CREATE) {
// en_passent_sq = to - PAWN_MOVE_DIRECTIONS[player];
// } else if(ptype == KING) {
// if(castleflag) {
// //TODO check squares for attacks + check
// //TODO castling flag -> castling type??
// if(to == CASTLE_SHORT_TARGET[player]) {
// //castle short
// //move rook..
// swap(occupancy[CASTLE_SHORT_ROOK[player]], occupancy[CASTLE_SHORT_ROOK_TARGET[player]]);
// pieces_by_color_bb[player] &= ~iBitMask(occupancy[CASTLE_SHORT_ROOK[player]]);
// pieces_by_color_bb[player] |= iBitMask(occupancy[CASTLE_SHORT_ROOK_TARGET[player]]);
// pieces_by_type_bb[ROOK] &= ~iBitMask(occupancy[CASTLE_SHORT_ROOK[player]]);
// pieces_by_type_bb[ROOK] |= iBitMask(occupancy[CASTLE_SHORT_ROOK_TARGET[player]]);
// } else {
// //castle long
// //move rook..
// swap(occupancy[CASTLE_LONG_ROOK[player]], occupancy[CASTLE_LONG_ROOK_TARGET[player]]);
// pieces_by_color_bb[player] &= ~iBitMask(occupancy[CASTLE_LONG_ROOK[player]]);
// pieces_by_color_bb[player] |= iBitMask(occupancy[CASTLE_LONG_ROOK_TARGET[player]]);
// pieces_by_type_bb[ROOK] &= ~iBitMask(occupancy[CASTLE_LONG_ROOK[player]]);
// pieces_by_type_bb[ROOK] |= iBitMask(occupancy[CASTLE_LONG_ROOK_TARGET[player]]);
// }
// }
// kings[player] = to;
// //king moves always disable all castling rights
// castle_long[player] = false;
// castle_short[player] = false;
// }
// }
// /*
// * finally add the moving piece to its destination
// * position on its corresponding bbs
// */
// pieces_by_color_bb[player] |= iBitMask(to);
// pieces_by_type_bb[ptype] |= iBitMask(to);
// //promotion..
// if(promtype != EMPTY) {
// occupancy[to] = promtype;
// pieces_by_type_bb[PAWN] &= ~iBitMask(to);
// pieces_by_type_bb[promtype] |= iBitMask(to);
// }
// if(success) {
// //delete from helper board
// occupancy[from] = EMPTY; //already swapped..from<->to
// //switch player
// player = FLIP(player);
// if(player == WHITE) {
// move_number++;
// }
// } else {
// //revert everything to backups
// draw_counter = draw;
// en_passent_sq = ep;
// castle_long[WHITE] = castle_000[WHITE];
// castle_long[BLACK] = castle_000[BLACK];
// castle_short[WHITE] = castle_00[WHITE];
// castle_short[BLACK] = castle_00[BLACK];
// occupancy[from] = ptype;
// occupancy[to] = to_piece;
// }
// return success;
//}
//TODO: merge all movegen functions into one big?
//or inline or #define stuff
inline
void BitBoard::genPseudoLegalMoves(MoveList &mlist) {
//TODO
// if(is_check) {
// ERROR("CHECK MOVE GEN");
// } else {
genQueenMoves(mlist);
genRookMoves(mlist);
genBishopMoves(mlist);
genKnightMoves(mlist);
genPawnMoves(mlist);
genKingMoves(mlist);
// }
}
inline
void BitBoard::genKingMoves(MoveList &mlist) {
U64 bb;
const U64 occ_bb = pieces_by_color_bb[WHITE] | pieces_by_color_bb[BLACK];
const U64 unocc_bb = ~occ_bb;
const U64 opp_bb = pieces_by_color_bb[FLIP(player)];
Move m = 0;
U32 from, to;
from = kings[player];
bb = KING_TARGET_BBS[from] & unocc_bb;
//normal moves
while(bb) {
to = bitscanfwd(bb);
m = moveCreate(from, to, KING, CAPTURE_NO, EMPTY, EP_TYPE_NONE, CASTLE_NO, MOVE_PRE_EVAL_DEFAULT);
mlist.put(m);
bb &= ~iBitMask(to);
}
bb = KING_TARGET_BBS[from] & opp_bb;
//captures
while(bb) {
to = bitscanfwd(bb);
m = moveCreate(from, to, KING, CAPTURE_YES, EMPTY, EP_TYPE_NONE, CASTLE_NO, MOVE_PRE_EVAL_DEFAULT);
mlist.put(m);
bb &= ~iBitMask(to);
}
//castling
if(castle_short[player] && !(occ_bb & CASTLE_SHORT_PATH[player])) {
//castling short is possible
m = moveCreate(from, CASTLE_SHORT_TARGET[player], KING, CAPTURE_NO, EMPTY, EP_TYPE_NONE, CASTLE_YES, MOVE_PRE_EVAL_CASTLE);
mlist.put(m);
}
if(castle_long[player] && !(occ_bb & CASTLE_LONG_PATH[player])) {
//castling long is possible
m = moveCreate(from, CASTLE_LONG_TARGET[player], KING, CAPTURE_NO, EMPTY, EP_TYPE_NONE, CASTLE_YES, MOVE_PRE_EVAL_CASTLE);
mlist.put(m);
}
}
inline
U64 BitBoard::genRankAttacks(const U64 occ, const U8 sq) {
//TODO.. U32??
U32 f = sq & 7;
U32 r = sq & ~7; //== rank*8
U32 o = (U32)(occ >> (r+1)) & 63;
return ((U64) RANK_ATTACK_BBS[f][o]) << r;
}
inline
U64 BitBoard::genFileAttacks(U64 occ, const U8 sq) {
//TODO.. U32??
U32 f = sq & 7;
occ = FILE_A & (occ >> f);
U32 o = (MAGIC_DIAGONAL_C2H7 * occ) >> 58;
return FILE_ATTACK_BBS[RANK(sq)][o] << f;
}
inline
U64 BitBoard::genDiagAttacks(U64 occ, const U8 sq) {
occ &= A1H8_DIAGONAL_TARGET_BBS[sq];
occ = (occ * FILE_B) >> 58;
return A1H8_DIAGONAL_TARGET_BBS[sq] & FILLUP_ATTACK_BBS[sq&7][occ];
}
inline
U64 BitBoard::genAntiDiagAttacks(U64 occ, const U8 sq) {
occ &= H1A8_DIAGONAL_TARGET_BBS[sq];
occ = (occ * FILE_B) >> 58;
return H1A8_DIAGONAL_TARGET_BBS[sq] & FILLUP_ATTACK_BBS[sq&7][occ];
}
inline
void BitBoard::genQueenMoves(MoveList &mlist) {
U64 bb;
const U64 occ_bb = pieces_by_color_bb[WHITE] | pieces_by_color_bb[BLACK];
const U64 own_bb = pieces_by_color_bb[player];
const U64 opp_bb = pieces_by_color_bb[FLIP(player)];
U64 pieces_to_move_bb = pieces_by_type_bb[QUEEN] & own_bb;
U64 captures_bb;
U32 from,to;
Move m = 0;
while(pieces_to_move_bb) {
from = bitscanfwd(pieces_to_move_bb);
bb = genDiagAttacks(occ_bb, from);
bb |= genAntiDiagAttacks(occ_bb, from);
bb |= genRankAttacks(occ_bb, from);
bb |= genFileAttacks(occ_bb, from);
bb &= ~own_bb;
captures_bb = bb & opp_bb;
bb &= ~opp_bb;
//normal moves
while(bb) {
to = bitscanfwd(bb);
m = moveCreate(from, to, QUEEN, CAPTURE_NO, EMPTY, EP_TYPE_NONE, CASTLE_NO, MOVE_PRE_EVAL_DEFAULT); //TODO VALUE
mlist.put(m);
bb &= ~iBitMask(to);
}
bb = captures_bb;
//captures
while(bb) {
to = bitscanfwd(bb);
m = moveCreate(from, to, QUEEN, CAPTURE_YES, EMPTY, EP_TYPE_NONE, CASTLE_NO, MOVE_PRE_EVAL_DEFAULT); //TODO VALUE
mlist.put(m);
bb &= ~iBitMask(to);
}
pieces_to_move_bb &= ~iBitMask(from);
}
}
inline
void BitBoard::genBishopMoves(MoveList &mlist) {
U64 bb;
const U64 occ_bb = pieces_by_color_bb[WHITE] | pieces_by_color_bb[BLACK];
const U64 own_bb = pieces_by_color_bb[player];
const U64 opp_bb = pieces_by_color_bb[FLIP(player)];
U64 pieces_to_move_bb = pieces_by_type_bb[BISHOP] & own_bb;
U64 captures_bb;
U32 from,to;
Move m = 0;
while(pieces_to_move_bb) {
from = bitscanfwd(pieces_to_move_bb);
bb = genDiagAttacks(occ_bb, from);
bb |= genAntiDiagAttacks(occ_bb, from);
bb &= ~own_bb;
captures_bb = bb & opp_bb;
bb &= ~opp_bb;
//normal moves
while(bb) {
to = bitscanfwd(bb);
m = moveCreate(from, to, BISHOP, CAPTURE_NO, EMPTY, EP_TYPE_NONE, CASTLE_NO, MOVE_PRE_EVAL_DEFAULT); //TODO VALUE
mlist.put(m);
bb &= ~iBitMask(to);
}
bb = captures_bb;
//captures
while(bb) {
to = bitscanfwd(bb);
m = moveCreate(from, to, BISHOP, CAPTURE_YES, EMPTY, EP_TYPE_NONE, CASTLE_NO, MOVE_PRE_EVAL_GOODCAP); //TODO VALUE
mlist.put(m);
bb &= ~iBitMask(to);
}
pieces_to_move_bb &= ~iBitMask(from);
}
}
inline
void BitBoard::genRookMoves(MoveList &mlist) {
U64 bb;
const U64 occ_bb = pieces_by_color_bb[WHITE] | pieces_by_color_bb[BLACK];
const U64 own_bb = pieces_by_color_bb[player];
const U64 opp_bb = pieces_by_color_bb[FLIP(player)];
U64 play_rooks_bb = pieces_by_type_bb[ROOK] & own_bb;
U64 captures_bb;
U32 from, to;
Move m = 0;
while(play_rooks_bb) {
from = bitscanfwd(play_rooks_bb);
bb = genRankAttacks(occ_bb, from);
bb |= genFileAttacks(occ_bb, from);
bb &= ~own_bb;
captures_bb = bb & opp_bb;
bb &= ~opp_bb;
//normal moves
while(bb) {
to = bitscanfwd(bb);
m = moveCreate(from, to, ROOK, CAPTURE_NO, EMPTY, EP_TYPE_NONE, CASTLE_NO, MOVE_PRE_EVAL_DEFAULT); //TODO VALUE
mlist.put(m);
bb &= ~iBitMask(to);
}
bb = captures_bb;
//captures
while(bb) {
to = bitscanfwd(bb);
m = moveCreate(from, to, ROOK, CAPTURE_YES, EMPTY, EP_TYPE_NONE, CASTLE_NO, MOVE_PRE_EVAL_GOODCAP); //TODO VALUE
mlist.put(m);
bb &= ~iBitMask(to);
}
play_rooks_bb &= ~iBitMask(from);
}
}
inline
void BitBoard::genKnightMoves(MoveList &mlist) {
U64 bb;
const U64 unocc_bb = ~(pieces_by_color_bb[WHITE] | pieces_by_color_bb[BLACK]);
const U64 opp_bb = pieces_by_color_bb[FLIP(player)];
Move m = 0;
U32 from, to;
//for every knight of player's color
U64 play_knights_bb = pieces_by_type_bb[KNIGHT] & pieces_by_color_bb[player];
while(play_knights_bb) {
//extract every knight
from = bitscanfwd(play_knights_bb);
//generate non-capture moves
//gen all targets for current knight
bb = KNIGHT_TARGET_BBS[from] & unocc_bb;
//create moves
while(bb) {
//extract target square
to = bitscanfwd(bb);
m = moveCreate(from, to, KNIGHT, CAPTURE_NO, EMPTY, EP_TYPE_NONE, CASTLE_NO, MOVE_PRE_EVAL_DEFAULT); //TODO VALUE
mlist.put(m);
bb &= ~iBitMask(to);
}
//generate captures
bb = KNIGHT_TARGET_BBS[from] & opp_bb;
//create captures
while(bb) {
//extract target square
to = bitscanfwd(bb);
//TODO check capture goodness
m = moveCreate(from, to, KNIGHT, CAPTURE_YES, EMPTY, EP_TYPE_NONE, CASTLE_NO, MOVE_PRE_EVAL_GOODCAP); //TODO VALUE
mlist.put(m);
bb &= ~iBitMask(to);
}
play_knights_bb &= ~iBitMask(from);
}
}
/*
* checks if any of the squares in targets_bb are attacked
* by the pieces of player atk_color
* returns a bitboard with the attacker's bits set, 0 == no attacker
*/
inline
U64 BitBoard::isAttackedBy(const U64 targets_bb, const U8 atk_color) {
U64 opp_bb;
U64 bb;
U64 check = 0;
const U64 occ_bb = pieces_by_color_bb[WHITE] | pieces_by_color_bb[BLACK];
U8 sq;
//test all opponent pieces for attacks on targets_bb
//treat targets as knights
bb = targets_bb;
opp_bb = pieces_by_color_bb[atk_color] & pieces_by_type_bb[KNIGHT];
while(bb) {
sq = bitscanfwd(bb);
check |= KNIGHT_TARGET_BBS[sq] & opp_bb;
bb &= ~iBitMask(sq);
if(check) {
return check;
}
}
//treat targets as bishops //include queen
bb = targets_bb;
opp_bb = pieces_by_color_bb[atk_color] & (pieces_by_type_bb[BISHOP] | pieces_by_type_bb[QUEEN]);
while(bb) {
sq = bitscanfwd(bb);
check |= (genDiagAttacks(occ_bb, sq) | genAntiDiagAttacks(occ_bb, sq)) & opp_bb;
bb &= ~iBitMask(sq);
if(check) {
return check;
}
}
//treat targets as rooks //include queen
bb = targets_bb;
opp_bb = pieces_by_color_bb[atk_color] & (pieces_by_type_bb[ROOK] | pieces_by_type_bb[QUEEN]);
while(bb) {
sq = bitscanfwd(bb);
check |= (genRankAttacks(occ_bb, sq) | genFileAttacks(occ_bb, sq)) & opp_bb;
bb &= ~iBitMask(sq);
if(check) {
return check;
}
}
//treat targets as pawns
opp_bb = pieces_by_color_bb[atk_color] & pieces_by_type_bb[PAWN];
bb = targets_bb;
if(atk_color == WHITE) {
bb = (_SHIFT_SE(bb) & (opp_bb & ~FILE_A)) | (_SHIFT_SW(bb) & (opp_bb & ~FILE_H));
} else {
bb = (_SHIFT_NE(bb) & (opp_bb & ~FILE_A)) | (_SHIFT_NW(bb) & (opp_bb & ~FILE_H));
}
if(bb) {
return bb;
}
//treat targets as kings
bb = KING_TARGET_BBS[kings[atk_color]] & targets_bb;
if(bb) {
return bb;
}
return false;
}
inline
void BitBoard::genPawnMoves(MoveList &mlist) {
const U64 unocc_bb = ~(pieces_by_color_bb[WHITE] | pieces_by_color_bb[BLACK]);
const U64 opp_bb = pieces_by_color_bb[FLIP(player)];
const U64 own_bb = pieces_by_color_bb[player] & pieces_by_type_bb[PAWN];
Move m = 0;
U32 from, to;
U64 bb;
U64 two_steppers, capture_west_targets, capture_east_targets, ep_takers, promo_rank;
U64 ep_target = iBitMask(en_passent_sq) & EP_RANKS;
//TODO remove if white/black conditionals somehow
//TODO promotions..efficient?
//one step advances
bb = pieces_by_type_bb[PAWN] & pieces_by_color_bb[player];
if(player == WHITE) {
promo_rank = RANK_8;
ep_takers = (_SHIFT_SE(ep_target) & (own_bb & ~FILE_A)) | (_SHIFT_SW(ep_target) & (own_bb & ~FILE_H));
capture_east_targets = _SHIFT_NE(bb) & (opp_bb & ~FILE_A);
capture_west_targets = _SHIFT_NW(bb) & (opp_bb & ~FILE_H);
bb = _SHIFT_N(bb) & unocc_bb;
two_steppers = _SHIFT_N(bb & RANK_3) & unocc_bb; //only white pawns that are on rank 3 AFTER one step could a do a double step
} else {
promo_rank = RANK_1;
ep_takers = (_SHIFT_NE(ep_target) & (own_bb & ~FILE_A)) | (_SHIFT_NW(ep_target) & (own_bb & ~FILE_H));
capture_east_targets = _SHIFT_SE(bb) & (opp_bb & ~FILE_A);
capture_west_targets = _SHIFT_SW(bb) & (opp_bb & ~FILE_H);
bb = _SHIFT_S(bb) & unocc_bb;
two_steppers = _SHIFT_S(bb & RANK_6) & unocc_bb; //only black pawns that are on rank 6 AFTER one step could a do a double step
}
//extract single step moves
while(bb) {
to = bitscanfwd(bb);
from = (int)to - PAWN_MOVE_DIRECTIONS[player];
//check promotion
if(iBitMask(to) & promo_rank) {
m = moveCreate(from, to, PAWN, CAPTURE_NO, QUEEN, EP_TYPE_NONE, CASTLE_NO, MOVE_PRE_EVAL_PROMO);
mlist.put(m);
m = moveCreate(from, to, PAWN, CAPTURE_NO, ROOK, EP_TYPE_NONE, CASTLE_NO, MOVE_PRE_EVAL_PROMO);
mlist.put(m);
m = moveCreate(from, to, PAWN, CAPTURE_NO, BISHOP, EP_TYPE_NONE, CASTLE_NO, MOVE_PRE_EVAL_PROMO);
mlist.put(m);
m = moveCreate(from, to, PAWN, CAPTURE_NO, KNIGHT, EP_TYPE_NONE, CASTLE_NO, MOVE_PRE_EVAL_PROMO);
mlist.put(m);
} else {
m = moveCreate(from, to, PAWN, CAPTURE_NO, EMPTY, EP_TYPE_NONE, CASTLE_NO, MOVE_PRE_EVAL_DEFAULT);
mlist.put(m);
}
bb &= ~iBitMask(to);
}
//extract double step moves
bb = two_steppers;
while(bb) {
//TODO creates en passent square..?!
to = bitscanfwd(bb);
from = (int)to - 2*PAWN_MOVE_DIRECTIONS[player];
m = moveCreate(from, to, PAWN, CAPTURE_NO, EMPTY, EP_TYPE_CREATE, CASTLE_NO, MOVE_PRE_EVAL_DEFAULT);
mlist.put(m);
bb &= ~iBitMask(to);
}
//extract captures
//east
bb = capture_east_targets;
while(bb) {
to = bitscanfwd(bb);
from = (int)to - PAWN_CAP_EAST_DIRECTIONS[player];
//TODO check capture goodness
//check promotion
if(iBitMask(to) & promo_rank) {
m = moveCreate(from, to, PAWN, CAPTURE_YES, QUEEN, EP_TYPE_NONE, CASTLE_NO, MOVE_PRE_EVAL_PROMOCAP);
mlist.put(m);
m = moveCreate(from, to, PAWN, CAPTURE_YES, ROOK, EP_TYPE_NONE, CASTLE_NO, MOVE_PRE_EVAL_PROMOCAP);
mlist.put(m);
m = moveCreate(from, to, PAWN, CAPTURE_YES, BISHOP, EP_TYPE_NONE, CASTLE_NO, MOVE_PRE_EVAL_PROMOCAP);
mlist.put(m);
m = moveCreate(from, to, PAWN, CAPTURE_YES, KNIGHT, EP_TYPE_NONE, CASTLE_NO, MOVE_PRE_EVAL_PROMOCAP);
mlist.put(m);
} else {
m = moveCreate(from, to, PAWN, CAPTURE_YES, EMPTY, EP_TYPE_NONE, CASTLE_NO, MOVE_PRE_EVAL_GOODCAP);
mlist.put(m);
}
bb &= ~iBitMask(to);
}
//west
bb = capture_west_targets;
while(bb) {
to = bitscanfwd(bb);
from = (int)to - PAWN_CAP_WEST_DIRECTIONS[player];
//TODO check capture goodness
//check promotion
if(iBitMask(to) & promo_rank) {
m = moveCreate(from, to, PAWN, CAPTURE_YES, QUEEN, EP_TYPE_NONE, CASTLE_NO, MOVE_PRE_EVAL_PROMOCAP);
mlist.put(m);
m = moveCreate(from, to, PAWN, CAPTURE_YES, ROOK, EP_TYPE_NONE, CASTLE_NO, MOVE_PRE_EVAL_PROMOCAP);
mlist.put(m);
m = moveCreate(from, to, PAWN, CAPTURE_YES, BISHOP, EP_TYPE_NONE, CASTLE_NO, MOVE_PRE_EVAL_PROMOCAP);
mlist.put(m);
m = moveCreate(from, to, PAWN, CAPTURE_YES, KNIGHT, EP_TYPE_NONE, CASTLE_NO, MOVE_PRE_EVAL_PROMOCAP);
mlist.put(m);
} else {
m = moveCreate(from, to, PAWN, CAPTURE_YES, EMPTY, EP_TYPE_NONE, CASTLE_NO, MOVE_PRE_EVAL_GOODCAP);
mlist.put(m);
}
bb &= ~iBitMask(to);
}
//if there is a current ep. square check if pawns can capture there
if(en_passent_sq) {
bb = ep_takers;
while(bb) {
from = bitscanfwd(bb);
m = moveCreate(from, en_passent_sq, PAWN, CAPTURE_YES, EMPTY, EP_TYPE_CAPTURE, CASTLE_NO, MOVE_PRE_EVAL_GOODCAP);
mlist.put(m);
bb &= ~iBitMask(from);
}
}
}
//inefficient
//used only for utility functionality like extracting the FEN string
U8 BitBoard::get(Square line, Square rank) const {
const Square bit = SQ(line,rank);//8*rank + line;
U8 color_offset = 0;
U8 piece = EMPTY;
if(pieces_by_color_bb[BLACK] & iBitMask(bit)) {
color_offset = MASK_COLOR;
}
//TODO remove debug overhead
//piece = occupancy[bit];
for(int p = PAWN; p <= KING; p++) {
if(pieces_by_type_bb[p] & iBitMask(bit)) {
piece = p;
break;
}
}
// if(piece != occupancy[bit]) {
// ERROR("BitBoard::get() : boards not synced...");
// exit(1); //BANG BANG
// }
return piece | color_offset;
}
void BitBoard::set(Square line, Square rank, OccupancyType type) {
const U8 bit = 8*rank + line; //8*y + x == bit position in U64
if(type == EMPTY) {
//occupancy[bit] = EMPTY;
U64 rmask = ~(iBitMask(bit));
pieces_by_color_bb[WHITE] &= rmask;
pieces_by_color_bb[BLACK] &= rmask;
for(int p = PAWN; p <= KING; p++) {
pieces_by_type_bb[p] &= rmask;
}
} else {
//occupancy[bit] = (type & MASK_PIECE);
U64 amask = iBitMask(bit);
pieces_by_type_bb[type & MASK_PIECE] |= amask;
U8 color = (type & MASK_COLOR) >> 3;
pieces_by_color_bb[color] |= iBitMask(bit);
if((type & MASK_PIECE) == KING) {
kings[(type & MASK_COLOR) >> 3] = bit;
}
}
}
void BitBoard::setStartingPosition() {
setFENPosition("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
}
void BitBoard::setFENPosition(string fen) {
Square x = 0;
Square y = BOARD_SIZE - 1;
istringstream iss(fen);
zeroAll();
//set piece positions
if(iss) {
string position;
iss >> position;
for(char c : position) {
if(c == '/') {
x = 0;
y--;
} else if(c >= '1' && c <= '8') {
int stop = x + (int)(c-'0');
for(; x < stop; x++) {
set(x, y, EMPTY);
}
} else {
//handle pieces
switch(c) {
//black pieces are lowercase letters
case 'p':
set(x, y, BPAWN); break;
case 'n':
set(x, y, BKNIGHT); break;
case 'k':
set(x, y, BKING); break;
case 'b':
set(x, y, BBISHOP); break;
case 'r':
set(x, y, BROOK); break;
case 'q':
set(x, y, BQUEEN); break;
//white pieces are uppercase letters
case 'P':
set(x, y, WPAWN); break;
case 'N':
set(x, y, WKNIGHT); break;
case 'K':
set(x, y, WKING); break;
case 'B':
set(x, y, WBISHOP); break;
case 'R':
set(x, y, WROOK); break;
case 'Q':
set(x, y, WQUEEN); break;
default:
string err = "FEN CODE CORRUPTED (PIECE -> ";
err += c; err += ")";
ERROR(err); break;
}
x++;
}
}
} else {
ERROR("FEN CODE CORRUPTED (POSITION)");
}
//set player to move
if(iss) {
char c;
iss >> c;
if(c == 'w') {
player = WHITE;
} else if(c == 'b') {
player = BLACK;
} else {
string err = "FEN CODE CORRUPTED (COLOR ->";
err += c; err += ")";
ERROR(err);
}
} else {
ERROR("FEN CODE CORRUPTED (PLAYER TO MOVE)");
}
//set castling rights
if(iss) {
castle_long[BLACK] = castle_long[WHITE] = castle_short[BLACK] = castle_short[WHITE] = false;
string castle;
iss >> castle;
for(char c : castle) {
switch(c) {
case 'K':
castle_short[WHITE] = true; break;
case 'Q':
castle_long[WHITE] = true; break;
case 'k':
castle_short[BLACK] = true; break;
case 'q':
castle_long[BLACK] = true; break;
case '-':
castle_long[BLACK] = castle_long[WHITE] = castle_short[BLACK] = castle_short[WHITE] = false;
break; //disable all
default:
string err = "FEN CODE CORRUPTED (CASTLING RIGHTS ->";
err += c; err += ")";
ERROR(err);
break;
}
}
} else {
ERROR("FEN CODE CORRUPTED (CASTLING RIGHTS)");
}
//set en passent state
if(iss) {
string ep;
iss >> ep;
if(ep == "-") {
//no en passent
en_passent_sq = NONE;
} else {
for(U32 i = 0; i < ep.size(); i+=2) {
if(ep[i] >= 'a' && ep[i] <= 'h' && ep[i+1] >= '1' && ep[i+1] <= '8') {
int x = ep[i] - 'a';
int y = ep[i+1] - '1';
en_passent_sq = SQ(x,y);
} else {
string err = "FEN CODE CORRUPTED (EN PASSENT ->";
err += ep; err += ")";
ERROR(err);
}
}
if(ep.size() > 4 && ep[0] >= 'a' && ep[0] <= 'h' && ep[1] >= '1' && ep[2] <= '8') {
} else {
}
}
} else {
ERROR("FEN CODE CORRUPTED (EN PASSENT)");
}
//half moves until draw
if(iss) {
string s;
iss >> s;
//TODO -- CHECK ILLEGAL VALUES... atoi is bad
draw_counter = atoi(s.c_str());
} else {
ERROR("FEN CODE CORRUPTED (HALF MOVES UNTIL DRAW)");
}
//next move number
if(iss) {
string s;
iss >> s;
//TODO -- CHECK ILLEGAL VALUES... atoi is bad
move_number = atoi(s.c_str());
} else {
ERROR("FEN CODE CORRUPTED (MOVE NUMBER)");
}
}
string BitBoard::getFENCode() const {
string fen = "";
int empty_count = 0;
for(int y = BOARD_SIZE-1; y >= 0; y--) {
for(int x = 0; x < BOARD_SIZE; x++) {
uint8_t c = get(x,y);
if(c == EMPTY) {
empty_count++;
} else {
if(empty_count > 0) {
fen += intToString(empty_count);
empty_count = 0;
}
switch (c) {
case BPAWN:
fen += 'p'; break;
case BKNIGHT:
fen += 'n'; break;
case BBISHOP:
fen += 'b'; break;
case BROOK:
fen += 'r'; break;
case BQUEEN:
fen += 'q'; break;
case BKING:
fen += 'k'; break;
case WPAWN:
fen += 'P'; break;
case WKNIGHT:
fen += 'N'; break;
case WBISHOP:
fen += 'B'; break;
case WROOK:
fen += 'R'; break;
case WQUEEN:
fen += 'Q'; break;
case WKING:
fen += 'K'; break;
default:
break;
}
}
}
if(empty_count > 0) {
fen += intToString(empty_count);
empty_count = 0;
}
if(y > 0) {
fen += "/";
}
}
fen += " ";
//to move
if(player == WHITE) {
fen += "w";
} else {
fen += "b";
}
fen += " ";
//castling rights
if(castle_short[WHITE]) {
fen += "K";
}
if(castle_long[WHITE]) {
fen += "Q";
}
if(castle_short[BLACK]) {
fen += "k";
}
if(castle_long[BLACK]) {
fen += "q";
}
if(!castle_short[WHITE] && !castle_long[WHITE] && !castle_short[BLACK] && !castle_long[BLACK]) {
fen += "-";
}
fen += " ";
//en passent
if(en_passent_sq != NONE) {
char xx = CHESS_COORDS[FILE(en_passent_sq)];
Square yy = RANK(en_passent_sq) + 1;
fen += xx;
fen += intToString(yy);
} else {
fen += "-";
}
fen += " ";
//50 half moves until draw
fen += intToString(draw_counter) + " ";
//moves
fen += intToString(move_number) + " ";
return fen;
}
void BitBoard::print() const {
cout << endl << "******************************************************************************" << endl << endl;
cout << " +---+---+---+---+---+---+---+---+" << endl;
for(int y = BOARD_SIZE-1; y >= 0; y--) {
cout << " " << intToString(y+1) << " |";
for(int x = 0; x < BOARD_SIZE; x++) {
char symbol = PIECE_SYMBOLS[get(x,y)];
if(symbol == ' ') {
if(x % 2 == 0 && y % 2 == 0) {
symbol = '.';
} else if(x % 2 == 1 && y % 2 == 1) {
symbol = '.';
}
}
cout << " " << symbol << " |";
//cout << " " << (int)get(x,y) << " |";
}
cout << endl;
cout << " +---+---+---+---+---+---+---+---+" << endl;
}
cout << " a b c d e f g h" << endl << endl << endl;
cout << " Color to move: " << COLORS[player] << endl;
cout << " Castling rights --- White: ";
if(castle_short[WHITE]) {
cout << "0-0 ";
}
if(castle_long[WHITE]) {
cout << "0-0-0 ";
}
cout << " Black: ";
if(castle_short[BLACK]) {
cout << "0-0 ";
}
if(castle_long[WHITE]) {
cout << "0-0-0 ";
}
cout << endl;
cout << " En passent field: ";
if(en_passent_sq != NONE) {
char xx = CHESS_COORDS[FILE(en_passent_sq)];
Square yy = RANK(en_passent_sq) + 1;
cout << xx << intToString(yy) << endl;
} else {
cout << "-" << endl;
}
cout << " 50 moves draw counter: " << intToString(draw_counter) << endl;
cout << " Next move number: " << intToString(move_number) << endl;
cout << " FEN-Code: " << getFENCode() << endl;
cout << endl << "******************************************************************************" << endl << endl;
}
#endif // BITBOARD_HPP
| true |
32e58bbddb43f8cea7a5d30f0c6e5df66b84bcce | C++ | egg0315/USACO-Solution | /ch1/ride.cpp | UTF-8 | 624 | 2.984375 | 3 | [] | no_license | /*
ID: codefor3
TASK: ride
LANG: C++
*/
/* LANG can be C++11 or C++14 for those more recent releases */
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int mod = 47;
int get(string s) {
long product = 1;
for(auto& c : s) {
product = (product * (c-'A'+1)) %mod;
}
return product;
}
int main() {
ofstream fout ("test.out");
ifstream fin ("test.in");
string group, comet;
fin >> comet >> group;
if(get(comet) == get(group)) {
fout << "GO" << endl;
}
else {
fout << "STAY" << endl;
}
return 0;
}
| true |
4c1420c8a86d6886e950486a7d0772e436a09c3c | C++ | michaelellison/Mike-s-Demo-App | /lib/CAT/CATVariant.h | UTF-8 | 1,716 | 2.65625 | 3 | [
"Libpng",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"Zlib",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | /// \file CATVariant.h
/// \brief Variant type for databases
/// \ingroup CAT
///
/// Copyright (c) 2010 by Michael Ellison.
/// See COPYING.txt for license (MIT License).
///
// $Author: mike $
// $Date: 2011-05-30 17:06:23 -0500 (Mon, 30 May 2011) $
// $Revision: 3 $
// $NoKeywords: $
#ifndef _CATVariant_H_
#define _CATVariant_H_
#include "CATInternal.h"
#include "CATString.h"
typedef enum CATVARIANT_TYPE
{
CATVARIANT_NULL,
CATVARIANT_INT64,
CATVARIANT_DOUBLE,
CATVARIANT_TEXT,
//----------------
CATVAIRANT_NUMTYPES
};
class CATVariant
{
public:
CATVariant();
CATVariant( const CATVariant& src);
CATVariant( const char* val);
CATVariant( CATInt64 val);
CATVariant( CATFloat64 val);
~CATVariant();
CATVARIANT_TYPE GetType() const;
// return true if changed.
bool Clear ();
bool SetInt64 ( CATInt64 val);
bool SetDouble ( CATFloat64 val);
bool SetString ( const CATString& val);
CATInt64 GetInt64 () const;
CATFloat64 GetDouble () const;
CATString GetString () const;
CATVariant& operator= ( const CATVariant& src);
CATVariant& operator= ( CATFloat64 val);
CATVariant& operator= ( CATInt64 val);
CATVariant& operator= ( const char* val);
bool operator== ( const CATVariant& cmp) const;
protected:
CATVARIANT_TYPE fType;
CATString fString;
CATInt64 fInt64;
CATFloat64 fDouble;
};
#endif // _CATVariant_H_ | true |
a2bbb924ad01a8bddd316e04781919e1562cc582 | C++ | kerbless/oii2021 | /_exercises/40_missioni/dpGuida.cpp | UTF-8 | 897 | 2.625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main() {
ifstream in("input.txt");
ofstream out("output.txt");
int n, max = 0;
in >> n;
int d[n], s[n];
for (int i = 0; i < n; i++) {
in >> d[i] >> s[i];
if (s[i] > max) max = s[i];
}
max++; // using days as indexes means counting from 1
int x[max] = {0};
for (int i=0; i<n; i++) {
out << "_____" << i << "_____" << "\n";
for (int j=s[i] - d[i]; j>=0; j--) {
out << "j" << j << " " << j << "-" << j+d[i] << " " << x[j] + 1 << ">" << x[j+d[i]] << "? = " << x[j]+1 << "\n";
if (x[j]+1 > x[j+d[i]]) {
x[j+d[i]] = x[j]+1;
}
}
for (int k = 0; k < max; k++)
out << x[k];
out << "\n";
}
int sol = x[0];
for (int i=0; i< max; i++)
if (x[i] > sol) sol = x[i];
out << sol;
}
| true |
da9c04e07bd6d82733ae4d3542fbd36b2153445e | C++ | HekpoMaH/Olimpiads | /9 klas - B/Тема 1 - STL @/bitset.cpp | UTF-8 | 457 | 3.390625 | 3 | [] | no_license | #include <iostream>
using namespace std;
#include <bitset>
int main() {
const bitset<12> mask(2731);
cout << "mask = " << mask << endl;
bitset<12> x;
cout << "Enter a 12-bit bitset in binary: " << flush;
if (cin >> x) {
cout << "x = " << x << endl;
cout << "As ulong: " << x.to_ulong() << endl;
cout << "And with mask: " << (x & mask) << endl;
cout << "Or with mask: " << (x | mask) << endl;
}
}
| true |
7c0a2a990a25edd27b1d495b5b3023f89b9063b7 | C++ | childhood/libAiml | /include/Stream.h | UTF-8 | 405 | 2.609375 | 3 | [] | no_license | #ifndef STREAM_H
#define STREAM_H
#include <map>
#include <string>
using namespace std;
class Stream
{
public:
virtual void Read(const char *str);
virtual void Write(const char *str);
};
class StreamProvider
{
public:
virtual Stream *getStream(const char *str);
};
Stream* getStream(const char *szName);
void setStreamProvider(StreamProvider *streamProvider);
#endif
| true |
4adbe865558b3b62ec4715692d9dc71014647e96 | C++ | intfloat/AlgoSolutions | /gcj/gcj2015_round1C/B.cpp | UTF-8 | 1,542 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
#define FOR(i, n) for (int i = 0; i < n; ++i)
using namespace std;
typedef long long ll;
map<char, double> prob;
string board, target;
int K, L, S;
bool check(string board, string target) {
set<char> s;
FOR(i, board.size()) s.insert(board[i]);
FOR(i, target.size()) {
if (s.find(target[i]) == s.end()) return false;
}
return true;
}
int prelen() {
int len = target.size() - 1;
while (len > 0) {
if (target.substr(0, len) == target.substr(target.size() - len, len))
return len;
--len;
}
return 0;
}
void solve() {
double res = 0.0;
prob.clear();
cin >> K >> L >> S;
cin >> board >> target;
assert(K == board.size() && L == target.size());
if (target.size() > S || !check(board, target)) {
cout << 0.0 << endl;
return;
}
FOR(i, board.size()) prob[board[i]] += 1.0 / ((double)board.size());
int len = prelen();
int mx = 0;
if (target.size() == 1) mx = S;
else {
for (int i = 1; ; ++i) {
if (target.size() * i - (i - 1) * len > S) {
mx = i - 1; break;
}
}
}
double tp = 1.0;
FOR(i, target.size()) tp *= prob[target[i]];
res = tp * (S - target.size() + 1);
res = mx - res;
cout << fixed << setprecision(10) << res << endl;
return;
}
int main() {
int TestCase;
cin >> TestCase;
FOR(caseID, TestCase) {
cout << "Case #" << caseID + 1 << ": ";
solve();
}
return 0;
}
| true |
8f2b2066d547f72c2e64f0876870b7be3913e09f | C++ | GonzaM21/portal | /src/client/client_communicator.cpp | UTF-8 | 2,164 | 3.015625 | 3 | [] | no_license | #include <thread>
#include <vector>
#include "client_communicator.h"
ClientCommunicator ::ClientCommunicator(DataContainer &data_container) :
data_container(data_container) {
this->continue_running = true;
}
void ClientCommunicator::set(SocketConnect socket,
std::string mode, std::string room_name,
std::string player_name) {
this->protocol.setSocket(std::move(socket));
this->protocol << mode;
this->protocol << room_name;
this->protocol << player_name;
}
ClientCommunicator::~ClientCommunicator() {
sender.join();
}
void ClientCommunicator::addMessageToSend(std::string message) {
this->sender_queue.push(message);
}
std::string ClientCommunicator::popMessageReceived() {
return this->receiver_queue.pop();
}
void ClientCommunicator::receiveMessage() {
try {
while (this->continue_running) {
std::string message;
this->protocol >> message;
this->receiver_queue.push(message);
}
this->endExecution();
} catch (const std::runtime_error &e) {
std::cout << e.what() << std::endl;
} catch (...) {
std::cout << "Error inesperado" << std::endl;
}
}
void ClientCommunicator ::sendMessage() {
try {
while (this->continue_running) {
std::string message(this->sender_queue.pop());
if (!this->continue_running || message == "m") break;
this->protocol << message;
}
this->endExecution();
} catch (const std::runtime_error &e) {
std::cout << e.what() << std::endl;
} catch (...) {
std::cout << "Error inesperado" << std::endl;
}
}
void ClientCommunicator ::run() {
this->sender = std::thread(&ClientCommunicator::sendMessage, this);
this->receiveMessage();
this->endExecution();
this->data_container.setGameFinish();
}
void ClientCommunicator ::endExecution() {
this->continue_running = false;
this->sender_queue.set_terminar_ejecucion();
this->receiver_queue.set_terminar_ejecucion();
this->protocol.closeProtocol();
}
bool ClientCommunicator::isRunnning() {
return this->continue_running;
} | true |
84ea5d828c631461a236f9db9ef3a615cc9c5d2c | C++ | cjacques42/cpp | /d07/ex02/Array.cpp | UTF-8 | 896 | 3.25 | 3 | [] | no_license | #include "Array.hpp"
template<typename T>
Array<T>::Array(void) {
this->_array = new T[0];
this->_len = 0;
}
template<typename T>
Array<T>::Array(T const &src) {
*this = src;
}
template<typename T>
Array<T>::Array(unsigned int len) {
this->_array = new T[len];
this->_len = len;
}
template<typename T>
Array<T> &Array<T>::operator=(T const &src) {
if (this->_array)
delete [] this->_array;
this->_len = src._len;
this->_array = new T[this->_len];
for (unsigned int index = 0; index < this->_len; index++) {
this->_array[index] = src._array[index];
}
return *this;
}
template<typename T>
T &Array<T>::operator[](unsigned int index) {
if (index >= this->_len)
throw std::exception();
return this->_array[index];
}
template<typename T>
unsigned int Array<T>::size(void) const {
return this->_len;
}
template<typename T>
Array<T>::~Array(void) {
delete [] this->_array;
}
| true |
640a5c761148798aa842af3e4b9b4e271c630aea | C++ | Bavya333/Coding | /C++/reversewordsll.cpp | UTF-8 | 492 | 3.0625 | 3 | [] | no_license | #include<iostream>
using namespace std;
struct node
{
string s;
node *next;
};
int main()
{
node *head,*m;
char a;
string s,a;
head->next=NULL;
int i=0;
cin>>a;
while(a[i]!='\n')
{
if(a[i]!='.')
{
s+=a[i];
}
else
{
m->next=head;
m->s=s;
head=m;
s.clear();
}
i++;
}
while(m!=NULL)
{
cout<<m->s<<".";
m=m->next;
}
}
| true |
a56a6b81aa128c547ca3581b224d4cf66377bf5e | C++ | Konnie789/BlackjackBot | /Blackjack_Bot - Version 3/Card.h | UTF-8 | 414 | 2.953125 | 3 | [] | no_license | //reference: C++ Programming 49 - Deck of Cards
//https://www.youtube.com/watch?v=NAAEMILMt-Q
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <string>
using std::cout;
using std::cin;
using std::string;
using std::endl;
class Card{
private:
char suit;
string value;
public:
Card();
Card(string cardValue, char cardSuit);
string print() const;
};
| true |
21bc9d3d0d196be3c256c30732cd7d1d65e2057b | C++ | CamiloOrbes/Proyecto-final | /SINCRONO/main.cpp | UTF-8 | 4,027 | 2.53125 | 3 | [] | no_license | #include <QDebug>
#include <QTextStream>
#include <QFile>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
QSerialPort serial;
serial.setPortName("COM5"); //Poner el nombre del puerto, probablemente no sea COM3
if(serial.open(QIODevice::ReadWrite)){
//Ahora el puerto seria está abierto
if(!serial.setBaudRate(QSerialPort::Baud9600)) //Configurar la tasa de baudios
qDebug()<<serial.errorString();
if(!serial.setDataBits(QSerialPort::Data8))
qDebug()<<serial.errorString();
if(!serial.setParity(QSerialPort::NoParity))
qDebug()<<serial.errorString();
if(!serial.setStopBits(QSerialPort::OneStop))
qDebug()<<serial.errorString();
if(!serial.setFlowControl(QSerialPort::NoFlowControl))
qDebug()<<serial.errorString();
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//Sincrona
serial.waitForReadyRead(1000);
serial.write("k\n"); //Enviar un caracter a Arduino para saber que debe iniciar la transmisión
char message[1024]; //Número máximo de caracteres
int l = 0;
if(serial.waitForReadyRead(10000)){
//Data was returned
l = serial.readLine(message,100); //Leer toda la línea que envía arduino
qDebug()<<"Response: "<<message;
}else{
//No data
qDebug()<<"Time out";
}
float velocidad;
velocidad = atof(&message[0]);
cout<<velocidad<<"m/s"<<endl;
if (velocidad!=0){
cout<<"Funciono"<<endl;
}
serial.close();
}else{
qDebug()<<"Serial COM3 not opened. Error: "<<serial.errorString();
}
return 0;
}
/*float QtGuiApplication::Arduino()
{
float velocidad,Vx,Vy;
QSerialPort serial;
serial.setPortName("COM5"); //Poner el nombre del puerto, probablemente no sea COM3
if(serial.open(QIODevice::ReadWrite)){
//Ahora el puerto seria está abierto
if(!serial.setBaudRate(QSerialPort::Baud9600)) //Configurar la tasa de baudios
qDebug()<<serial.errorString();
if(!serial.setDataBits(QSerialPort::Data8))
qDebug()<<serial.errorString();
if(!serial.setParity(QSerialPort::NoParity))
qDebug()<<serial.errorString();
if(!serial.setStopBits(QSerialPort::OneStop))
qDebug()<<serial.errorString();
if(!serial.setFlowControl(QSerialPort::NoFlowControl))
qDebug()<<serial.errorString();
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//Sincrona
serial.waitForReadyRead(1000);
serial.write("k\n"); //Enviar un caracter a Arduino para saber que debe iniciar la transmisión
char message[1024]; //Número máximo de caracteres
int l = 0;
if(serial.waitForReadyRead(10000)){
//Data was returned
l = serial.readLine(message,100); //Leer toda la línea que envía arduino
qDebug()<<"Response: "<<message;
}else{
//No data
qDebug()<<"Time out";
}
velocidad = atof(&message[0]);
cout<<velocidad<<"m/s"<<endl;
if (velocidad!=0){
cout<<"Funciono"<<endl;
}
serial.close();
}else{
qDebug()<<"Serial COM5 not opened. Error: "<<serial.errorString();
}
return velocidad;
}
void QtGuiApplication::mousePressEvent(QMouseEvent * ev)
{
//creacion de cada pelota.
float Vloci,VX,VY;
Vloci =Arduino();
float ang = atan2(600-ev->y(),ev->x());
VX = Vloci*cos(ang);
VY = Vloci*sin(ang);
if(!(tiros==0)){
bars.push_back(new BolasGraf(VX,VY,colorset));
scene->addItem(bars.back());
bars.back()->setPos(0,600);
if (tiros == 0) { return; }
disparo = QDateTime::currentDateTime();
tiros--;
timer->start(18);
}
}
*/
| true |
57fe101abdecea1a489ed2ff0954fed34639990d | C++ | esaurez/cppmetrics | /src/statistics.hpp | UTF-8 | 4,996 | 3.171875 | 3 | [] | no_license | #ifndef _STATISTICS_H_INCLUDED
#define _STATISTICS_H_INCLUDED
#include <algorithm>
#include <chrono>
#include <iostream>
#include <numeric>
#include <vector>
namespace MetricsCpp{
template <class DataType, class AverageType>
class Statistics{
public:
AverageType average;
DataType min,max,percentile25,median,percentile75,percentile90,percentile99,percentile999,percentile9999;
int aggregateResults(){
if(!elements.empty()){
std::sort(elements.begin(),elements.end());
average = std::accumulate(elements.begin(),elements.end(),DataType(0))/elements.size();
min = *elements.cbegin();
max = *elements.crbegin();
percentile25 = getPercentile(25.0);
median = getPercentile(50.0);
percentile75= getPercentile(75.0);
percentile90= getPercentile(90.0);
percentile99= getPercentile(99.0);
percentile999= getPercentile(99.9);
percentile9999= getPercentile(99.99);
}
return 0;
}
friend std::ostream& operator<<(std::ostream& os, const Statistics& ss) {
os<<ss.average<<",";
os<<ss.min<<",";
os<<ss.max<<",";
os<<ss.percentile25<<",";
os<<ss.median<<",";
os<<ss.percentile75<<",";
os<<ss.percentile90<<",";
os<<ss.percentile99<<",";
os<<ss.percentile999<<",";
os<<ss.percentile9999<<",";
os<<ss.elements.size()<<",";
return os;
}
int addNewElement(DataType element){
elements.emplace_back(std::move(element));
return 0;
}
Statistics& operator=(const Statistics& other){
if (this != &other) { // self-assignment check expected
std::copy(other.elements.begin(),other.elements.end(), std::back_inserter(elements));
}
return *this;
}
private:
std::vector<DataType> elements;
DataType getPercentile(double percentile) const{
const int position = (percentile*elements.size())/100;
return elements.at(position);
}
};
template <class DataType, class AverageType>
class DurationStatistics{
public:
AverageType average;
DataType min,max,percentile25,median,percentile75,percentile90,percentile99;
int aggregateResults(){
if(!elements.empty()){
std::sort(elements.begin(),elements.end());
average = std::accumulate(elements.begin(),elements.end(),DataType(0))/DataType(elements.size());
min = *elements.cbegin();
max = *elements.crbegin();
percentile25 = getPercentile(25.0);
median = getPercentile(50.0);
percentile75= getPercentile(75.0);
percentile90= getPercentile(90.0);
percentile99= getPercentile(99.0);
}
return 0;
}
friend std::ostream& operator<<(std::ostream& os, const DurationStatistics& ss) {
if(ss.elements.size()==0){
os<<"0,0,0,0,0,0,0,0,0,";
}
else{
os<<ss.average<<",";
os<<ss.min.count()<<",";
os<<ss.max.count()<<",";
os<<ss.percentile25.count()<<",";
os<<ss.median.count()<<",";
os<<ss.percentile75.count()<<",";
os<<ss.percentile90.count()<<",";
os<<ss.percentile99.count()<<",";
os<<ss.elements.size()<<",";
}
return os;
}
int addNewDuration(DataType size){
elements.push_back(size);
return 0;
}
private:
std::vector<DataType> elements;
DataType getPercentile(double percentile) const{
const int position = (percentile*elements.size())/100;
return elements.at(position);
}
};
class TimeStatistics{
public:
typedef std::chrono::microseconds ms;
TimeStatistics() : average(0),min(0),max(0),percentile25(0),median(0),percentile75(0),percentile90(0),percentile99(0){};
TimeStatistics(const ms &avg, const ms &mini, const ms &maxi, const ms &per25, const ms &med, const ms &per75, const ms &per90, const ms &per99, const std::string &config="") : average(avg), min(mini), max(maxi), percentile25(per25), median(med), percentile75(per75), percentile90(per90), percentile99(per99),configuration(config) {};
TimeStatistics& operator=(const TimeStatistics& other);
ms average;
ms min;
ms max;
ms percentile25;
ms median;
ms percentile75;
ms percentile90;
ms percentile99;
std::string configuration;
friend std::ostream& operator<<(std::ostream& os, const TimeStatistics& dt);
};
using SizeStatistics = Statistics<int,double>;
using MemoryStatistics = Statistics<double,double>;
using ClockStatistics = Statistics<clock_t,clock_t>;
}
#endif
| true |
dbf3884a9454f35389643cba4216e37d8a16ed71 | C++ | trmcnealy/Kokkos.NET | /runtime.Kokkos.NET/Analyzes/GeoJson.hpp | UTF-8 | 14,377 | 2.90625 | 3 | [
"MIT"
] | permissive | #pragma once
#include "runtime.Kokkos/ViewTypes.hpp"
#include "runtime.Kokkos/Extensions.hpp"
#include <MathExtensions.hpp>
#include <StdExtensions.hpp>
#include <Print.hpp>
#include "Analyzes/Variant.hpp"
#include <unordered_map>
namespace Spatial
{
struct empty
{
}; // this Geometry type represents the empty point set, ∅, for the coordinate space (OGC Simple Features).
constexpr bool operator==(empty, empty) { return true; }
constexpr bool operator!=(empty, empty) { return false; }
constexpr bool operator<(empty, empty) { return false; }
constexpr bool operator>(empty, empty) { return false; }
constexpr bool operator<=(empty, empty) { return true; }
constexpr bool operator>=(empty, empty) { return true; }
template<typename T>
struct point
{
using coordinate_type = T;
constexpr point() : x(), y() {}
constexpr point(T x_, T y_) : x(x_), y(y_) {}
T x;
T y;
};
template<typename T>
constexpr bool operator==(const point<T> & lhs, const point<T> & rhs)
{
return lhs.x == rhs.x && lhs.y == rhs.y;
}
template<typename T>
constexpr bool operator!=(const point<T> & lhs, const point<T> & rhs)
{
return !(lhs == rhs);
}
template<typename T>
struct box
{
using coordinate_type = T;
using point_type = point<coordinate_type>;
constexpr box(const point_type & min_, const point_type & max_) : min(min_), max(max_) {}
point_type min;
point_type max;
};
template<typename T>
constexpr bool operator==(const box<T> & lhs, const box<T> & rhs)
{
return lhs.min == rhs.min && lhs.max == rhs.max;
}
template<typename T>
constexpr bool operator!=(const box<T> & lhs, const box<T> & rhs)
{
return lhs.min != rhs.min || lhs.max != rhs.max;
}
template<typename G, typename T = typename G::coordinate_type>
box<T> envelope(const G & geometry)
{
using limits = std::numeric_limits<T>;
T min_t = limits::has_infinity ? -limits::infinity() : limits::min();
T max_t = limits::has_infinity ? limits::infinity() : limits::max();
point<T> min(max_t, max_t);
point<T> max(min_t, min_t);
for_each_point(geometry, [&](const point<T> & point) {
if(min.x > point.x)
min.x = point.x;
if(min.y > point.y)
min.y = point.y;
if(max.x < point.x)
max.x = point.x;
if(max.y < point.y)
max.y = point.y;
});
return box<T>(min, max);
}
template<typename T, template<typename...> class Cont = std::vector>
struct multi_point : Cont<point<T>>
{
using coordinate_type = T;
using point_type = point<T>;
using container_type = Cont<point_type>;
using size_type = typename container_type::size_type;
template<class... Args>
multi_point(Args&&... args) : container_type(std::forward<Args>(args)...)
{
}
multi_point(std::initializer_list<point_type> args) : container_type(std::move(args)) {}
};
template<typename T, template<typename...> class Cont = std::vector>
struct line_string : Cont<point<T>>
{
using coordinate_type = T;
using point_type = point<T>;
using container_type = Cont<point_type>;
using size_type = typename container_type::size_type;
template<class... Args>
line_string(Args&&... args) : container_type(std::forward<Args>(args)...)
{
}
line_string(std::initializer_list<point_type> args) : container_type(std::move(args)) {}
};
template<typename T, template<typename...> class Cont = std::vector>
struct multi_line_string : Cont<line_string<T>>
{
using coordinate_type = T;
using line_string_type = line_string<T>;
using container_type = Cont<line_string_type>;
using size_type = typename container_type::size_type;
template<class... Args>
multi_line_string(Args&&... args) : container_type(std::forward<Args>(args)...)
{
}
multi_line_string(std::initializer_list<line_string_type> args) : container_type(std::move(args)) {}
};
template<typename T, template<typename...> class Cont = std::vector>
struct linear_ring : Cont<point<T>>
{
using coordinate_type = T;
using point_type = point<T>;
using container_type = Cont<point_type>;
using size_type = typename container_type::size_type;
template<class... Args>
linear_ring(Args&&... args) : container_type(std::forward<Args>(args)...)
{
}
linear_ring(std::initializer_list<point_type> args) : container_type(std::move(args)) {}
};
template<typename T, template<typename...> class Cont = std::vector>
struct polygon : Cont<linear_ring<T>>
{
using coordinate_type = T;
using linear_ring_type = linear_ring<T>;
using container_type = Cont<linear_ring_type>;
using size_type = typename container_type::size_type;
template<class... Args>
polygon(Args&&... args) : container_type(std::forward<Args>(args)...)
{
}
polygon(std::initializer_list<linear_ring_type> args) : container_type(std::move(args)) {}
};
template<typename T, template<typename...> class Cont = std::vector>
struct multi_polygon : Cont<polygon<T>>
{
using coordinate_type = T;
using polygon_type = polygon<T>;
using container_type = Cont<polygon_type>;
using size_type = typename container_type::size_type;
template<class... Args>
multi_polygon(Args&&... args) : container_type(std::forward<Args>(args)...)
{
}
multi_polygon(std::initializer_list<polygon_type> args) : container_type(std::move(args)) {}
};
template<typename T, template<typename...> class Cont = std::vector>
struct geometry_collection;
template<typename T, template<typename...> class Cont = std::vector>
using geometry_base = System::variant<empty,
point<T>,
line_string<T, Cont>,
polygon<T, Cont>,
multi_point<T, Cont>,
multi_line_string<T, Cont>,
multi_polygon<T, Cont>,
geometry_collection<T, Cont>>;
template<typename T, template<typename...> class Cont = std::vector>
struct geometry : geometry_base<T, Cont>
{
using coordinate_type = T;
using geometry_base<T>::geometry_base;
};
template<typename T, template<typename...> class Cont>
struct geometry_collection : Cont<geometry<T>>
{
using coordinate_type = T;
using geometry_type = geometry<T>;
using container_type = Cont<geometry_type>;
using size_type = typename container_type::size_type;
template<class... Args>
geometry_collection(Args&&... args) : container_type(std::forward<Args>(args)...)
{
}
geometry_collection(std::initializer_list<geometry_type> args) : container_type(std::move(args)) {}
};
struct equal_comp_shared_ptr
{
template<typename T>
bool operator()(const T & lhs, const T & rhs) const
{
return lhs == rhs;
}
template<typename T>
bool operator()(const std::shared_ptr<T> & lhs, const std::shared_ptr<T> & rhs) const
{
if(lhs == rhs)
{
return true;
}
return *lhs == *rhs;
}
};
struct null_value_t
{
};
constexpr bool operator==(const null_value_t&, const null_value_t&) { return true; }
constexpr bool operator!=(const null_value_t&, const null_value_t&) { return false; }
constexpr bool operator<(const null_value_t&, const null_value_t&) { return false; }
constexpr null_value_t null_value = null_value_t();
#define DECLARE_VALUE_TYPE_ACCESOR(NAME, TYPE) \
TYPE* get##NAME() noexcept \
{ \
return match([](TYPE& val) -> TYPE* { return &val; }, [](auto&) -> TYPE* { return nullptr; }); \
} \
const TYPE* get##NAME() const noexcept { return const_cast<value*>(this)->get##NAME(); }
struct value;
using value_base = System::
variant<null_value_t, bool, uint64_t, int64_t, double, std::string, std::shared_ptr<std::vector<value>>, std::shared_ptr<std::unordered_map<std::string, value>>>;
derived_struct value : public value_base
{
using array_type = std::vector<value>;
using array_ptr_type = std::shared_ptr<std::vector<value>>;
using const_array_ptr_type = std::shared_ptr<const std::vector<value>>;
using object_type = std::unordered_map<std::string, value>;
using object_ptr_type = std::shared_ptr<std::unordered_map<std::string, value>>;
using const_object_ptr_type = std::shared_ptr<const std::unordered_map<std::string, value>>;
value() : value_base(null_value) {}
value(null_value_t) : value_base(null_value) {}
value(bool v) : value_base(v) {}
value(const char* c) : value_base(std::string(c)) {}
value(std::string str) : value_base(std::move(str)) {}
template<typename T, std::enable_if_t<std::is_integral<T>::value, int> = 0, std::enable_if_t<std::is_signed<T>::value, int> = 0>
value(T t) : value_base(int64_t(t))
{
}
template<typename T, std::enable_if_t<std::is_integral<T>::value, int> = 0, std::enable_if_t<!std::is_signed<T>::value, int> = 0>
value(T t) : value_base(uint64_t(t))
{
}
template<typename T, std::enable_if_t<std::is_floating_point<T>::value, int> = 0>
value(T t) : value_base(double(t))
{
}
value(array_type array) : value_base(std::make_shared<array_type>(std::forward<array_type>(array))) {}
value(array_ptr_type array) : value_base(array) {}
value(object_type object) : value_base(std::make_shared<object_type>(std::forward<object_type>(object))) {}
value(object_ptr_type object) : value_base(object) {}
bool operator==(const value & rhs) const
{
assert(valid() && rhs.valid());
if(this->which() != rhs.which())
{
return false;
}
System::detail::comparer<value, equal_comp_shared_ptr> visitor(*this);
return visit(rhs, visitor);
}
explicit operator bool() const { return !is<null_value_t>(); }
DECLARE_VALUE_TYPE_ACCESOR(Int, int64_t)
DECLARE_VALUE_TYPE_ACCESOR(Uint, uint64_t)
DECLARE_VALUE_TYPE_ACCESOR(Bool, bool)
DECLARE_VALUE_TYPE_ACCESOR(Double, double)
DECLARE_VALUE_TYPE_ACCESOR(String, std::string)
array_ptr_type getArray() noexcept
{
return match([](array_ptr_type& val) -> array_ptr_type { return val; }, [](auto&) -> array_ptr_type { return nullptr; });
}
const_array_ptr_type getArray() const noexcept { return const_cast<value*>(this)->getArray(); }
object_ptr_type getObject() noexcept
{
return match([](object_ptr_type& val) -> object_ptr_type { return val; }, [](auto&) -> object_ptr_type { return nullptr; });
}
const_object_ptr_type getObject() const noexcept { return const_cast<value*>(this)->getObject(); }
};
#undef DECLARE_VALUE_TYPE_ACCESOR
using property_map = value::object_type;
using identifier = System::variant<null_value_t, uint64_t, int64_t, double, std::string>;
template<class T>
struct feature
{
using coordinate_type = T;
using geometry_type = geometry<T>; // Fully qualified to avoid GCC -fpermissive error.
geometry_type geometry;
property_map properties;
identifier id;
feature() : geometry(), properties(), id() {}
feature(const geometry_type & geom_) : geometry(geom_), properties(), id() {}
feature(geometry_type&& geom_) : geometry(std::move(geom_)), properties(), id() {}
feature(const geometry_type & geom_, const property_map & prop_) : geometry(geom_), properties(prop_), id() {}
feature(geometry_type&& geom_, property_map&& prop_) : geometry(std::move(geom_)), properties(std::move(prop_)), id() {}
feature(const geometry_type & geom_, const property_map & prop_, const identifier & id_) : geometry(geom_), properties(prop_), id(id_) {}
feature(geometry_type&& geom_, property_map&& prop_, identifier&& id_) : geometry(std::move(geom_)), properties(std::move(prop_)), id(std::move(id_)) {}
};
template<class T>
constexpr bool operator==(const feature<T> & lhs, const feature<T> & rhs)
{
return lhs.id == rhs.id && lhs.geometry == rhs.geometry && lhs.properties == rhs.properties;
}
template<class T>
constexpr bool operator!=(const feature<T> & lhs, const feature<T> & rhs)
{
return !(lhs == rhs);
}
template<class T, template<typename...> class Cont = std::vector>
struct feature_collection : Cont<feature<T>>
{
using coordinate_type = T;
using feature_type = feature<T>;
using container_type = Cont<feature_type>;
using size_type = typename container_type::size_type;
template<class... Args>
feature_collection(Args&&... args) : container_type(std::forward<Args>(args)...)
{
}
feature_collection(std::initializer_list<feature_type> args) : container_type(std::move(args)) {}
};
}
| true |
91abd4b0c044d83c03bb66d26669fd3adc0b9221 | C++ | Gci04/ITLab_MiniComputationalGeometry | /Vor_Diagram/t_point/TPoint.h | WINDOWS-1251 | 1,664 | 2.921875 | 3 | [] | no_license | #include <cmath>
enum Position{LEFT, RIGHT, BEYOND, BEHIND, BETWEEN, ORIGIN, DESTINATION}; //
//, C, , , , ,
// ""
class TPoint
{
protected:
double x; //
double y;
public:
TPoint(double _x = 0.0, double _y = 0.0);
//
TPoint operator+(const TPoint& P);
TPoint operator-(const TPoint& P);
friend TPoint operator*(const double scalar, const TPoint& P); // C * TPoint
double det(const TPoint& _P1, const TPoint& _P2); //
//
int operator<(const TPoint& P) const; //
int operator>(const TPoint& P) const;
int operator==(const TPoint& P) const;
int operator!=(const TPoint& P) const;
//
double& operator[](const int i); // i = 0 -> x; i = 1 -> y
double Lenght(); //
// ()
int Location(TPoint& P1, TPoint& P2); // P1 - , P2 -
//double Distation(const Edge& _E); //
};
| true |
6d8f1c352ff21195dba4c0b08d5bace168e746c7 | C++ | zivlakmilos/games | /games2/rpg1/game.cpp | UTF-8 | 3,753 | 2.796875 | 3 | [] | no_license | /*
game.cpp
code for game, main loop, window drawing, handle events
*/
// Include headers
#include "main.h"
#include "player.h"
#include "game.h"
Game::Game()
{
this->x = 100;
this->x = 100;
this->width = 640;
this->height = 480;
this->caption = "";
this->isRunning = true;
this->fps = 10;
}
void Game::initialization(void)
{
// SDL initialization
SDL_Init(SDL_INIT_EVERYTHING);
// Set OpenGL memory usage
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
// Set window caption
SDL_WM_SetCaption(this->caption, NULL);
// Set size of window
SDL_SetVideoMode(this->width, this->height, 32, SDL_OPENGL);
// Set initialize clear color
glClearColor(0, 1, 0, 1);
// Part of screen to be display
glViewport(0, 0, this->width, this->height);
// Shade model
glShadeModel(GL_SMOOTH);
// Enable textures
glEnable(GL_TEXTURE_2D);
// 2D rendering
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Disable depth checking
glDisable(GL_DEPTH_TEST);
// Enable 2D texture
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Clear the window
glClear(GL_COLOR_BUFFER_BIT);
// Player initialization
player.loadTexture(); // Load player texture
// Load musics
}
// void for handle events
void Game::events(SDL_Event event)
{
while(SDL_PollEvent(&event))
{
if(event.type == SDL_QUIT)
this->isRunning = false;
if(event.type == SDL_KEYUP && event.key.keysym.sym == SDLK_ESCAPE)
this->isRunning = false;
if(event.type == SDL_KEYDOWN)
{
if(event.key.keysym.sym == SDLK_UP)
player.moveState(PLAYER_MOVE_ADD, PLAYER_MOVE_UP);
else if(event.key.keysym.sym == SDLK_DOWN)
player.moveState(PLAYER_MOVE_ADD, PLAYER_MOVE_DOWN);
else if(event.key.keysym.sym == SDLK_LEFT)
player.moveState(PLAYER_MOVE_ADD, PLAYER_MOVE_LEFT);
else if(event.key.keysym.sym == SDLK_RIGHT)
player.moveState(PLAYER_MOVE_ADD, PLAYER_MOVE_RIGHT);
}
if(event.type == SDL_KEYUP)
{
if(event.key.keysym.sym == SDLK_UP)
player.moveState(PLAYER_MOVE_DELETE, PLAYER_MOVE_UP);
else if(event.key.keysym.sym == SDLK_DOWN)
player.moveState(PLAYER_MOVE_DELETE, PLAYER_MOVE_DOWN);
else if(event.key.keysym.sym == SDLK_LEFT)
player.moveState(PLAYER_MOVE_DELETE, PLAYER_MOVE_LEFT);
else if(event.key.keysym.sym == SDLK_RIGHT)
player.moveState(PLAYER_MOVE_DELETE, PLAYER_MOVE_RIGHT);
}
if(event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_c)
glClear(GL_COLOR_BUFFER_BIT);
}
}
void Game::mainloop(void)
{
// Initialization
this->initialization();
/*
main loop
*/
while(this->isRunning)
{
// EVENTS
this->events(this->event);
// LOGIC
this->player.move();
// RENDER
glClear(GL_COLOR_BUFFER_BIT); // Cear screen
glPushMatrix(); //Begin render
glOrtho(0, this->width, this->height, 0, -1, 1); // Coordinate system
this->player.render();
glPopMatrix(); // End render
// Swap buffers
SDL_GL_SwapBuffers();
// Regulate FPS
SDL_Delay(this->fps);
}
}
| true |
38e0aba97c8e39a22d9552f93c8cd6a186ec6944 | C++ | sapizi4/flightsim_project | /OpenServerCommand.cpp | UTF-8 | 778 | 2.625 | 3 | [] | no_license | //
// Created by maor on 29/01/2020.
//
/*#include "OpenServerCommand.h"
#include <iostream>
#include <thread>
#include "Shuntingyard.h"
void OpenServerCommand::execute(const vector<string>&cur_lex) {
Shuntingyard shuntingyard;
int port, freq;
try {
//shunting yard algorithm returns double..
port = (int)Shuntingyard::algorithm(cur_lex[index + 1]);
freq = (int)Shuntingyard::algorithm(cur_lex[index + 2]);
index += 3;
} catch (...) {
cerr << "ERROR : WRONG PASSING PARAMETERS" << endl;
exit(1);
}
thread t(&DataReaderServer::openServer, port, freq);
while (!DataReaderServer::isOpen()){
//wait..
}
t.detach();
}
OpenServerCommand::OpenServerCommand(int &index):index(index) {
}*/ | true |
6c72c4923600c052965fdc8a8708d34796f3863e | C++ | mxaviersmp/algorithms | /PAA/3_Algoritimos_Gulosos/ciclistas.cpp | UTF-8 | 1,363 | 3.328125 | 3 | [] | no_license | /*
Duas cidades irão competir juntas na regional de ciclismo este ano. As equipes são de duas pessoas, que
usarão uma bicicleta de dois lugares para a corrida. As duplas devem ser formadas com um membro
de cada cidade. A velocidade de uma dupla é determinada pela velorcidade da pessoa mais rápida, já
que a mais lenta não conseguirá acompanhar o ritmo das pedaladas. Desejamos escolher as equipes
de forma que a soma das velocidades das suplas formadas seja a máxima possível, na esperança que
essas cidades vençam a competição. Considere que conhecemos as velocidades das pessoas de ambas
as cidades, disponíveis em A e B, onde cada um representa uma cidade.
Pareamos a pessoa mais rápida dentre as duas cidades com a pessoa mais lenta da outra
cidade.
*/
#include <bits/stdc++.h>
using namespace std;
typedef vector<pair<int, int>> vpii;
vpii ciclistas(int A[], int B[], int n)
{
sort(A, A + n);
sort(B, B + n);
vpii duplas;
for(int i = 0; i < n; i++)
{
duplas.push_back(make_pair(A[i], B[n - i - 1]));
}
return duplas;
}
int main()
{
int n;
cin >> n;
int A[n], B[n];
for(int i = 0; i < n; i++)
cin >> A[i];
for(int i = 0; i < n; i++)
cin >> B[i];
for(auto &dupla: ciclistas(A, B, n))
cout << dupla.first << ',' << dupla.second << ' ';
cout << endl;
}
| true |
37ef179cecae9a0d71a4b524a81b8cd9156a4aa3 | C++ | Yeaseen/AngryBirds_Igraphics | /IGraphics/IGraphics/IGraphics/n.cpp | UTF-8 | 2,942 | 2.796875 | 3 | [] | no_license | /*
author: S. M. Shahriar Nirjon
last modified: August 8, 2008
*/
//#include<stdio.h>
#include<conio.h>
# include "iGraphics.h"
//# include "gl.h"
#include<math.h>
#include<time.h>
int ball_x=100, ball_y=100;
int dx, dy;
int vx,vy,t;
int vel=50,ang=0;
int x=1;
/*
function iDraw() is called again and again by the system.
*/
void iDraw()
{
//place your drawing codes here
if(x==1){
iClear();
iShowBMP(0,0,"demo1.bmp");
iShowBMP2(ball_x,ball_y,"axe.bmp",0*65536+255*256+0);
//iShowBMP(ball_x,ball_y,"a.bmp");
iSetColor(0, 0, 0);
//iFilledRectangle(ball_x, ball_y, 30,40);
iText(800,500,"Score:");
iSetColor(0, 240, 0);
iText(10,480,"velocity:");
iText(10,440,"angle:");
iFilledRectangle(100, 470+vel, 180-vel,20);
iFilledRectangle(100, 430+ang, 180-ang,20);
iSetColor(255, 0, 0);
iFilledCircle(ball_x, ball_y, 15);
//iFilledCircle(399, 399, 7);
iSetColor(255, 255, 255);
iText(400, 500, "Welcome to the world of Angry Birds!!");
}
}
/*
function iMouseMove() is called when the user presses and drags the mouse.
(mx, my) is the position where the mouse pointer is.
*/
void iMouseMove(int mx, int my)
{
}
/*
function iMouse() is called when the user presses/releases the mouse.
(mx, my) is the position where the mouse pointer is.
*/
void iMouse(int button, int state, int mx, int my)
{
if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
//place your codes here
//if(mx>=100 && mx<=280 && my>=470 && my<=490)
{
//vel= mx-100;
}
}
if(button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN)
{
//place your codes here
}
}
/*
function iKeyboard() is called whenever the user hits a key in keyboard.
key- holds the ASCII value of the key pressed.
*/
void iKeyboard(unsigned char key)
{
if(key == 'p')
{
//do something with 'q'
iPauseTimer(0);
}
if(key == 'r')
{
iResumeTimer(0);
}
//place your codes for other keys here
}
/*
function iSpecialKeyboard() is called whenver user hits special keys like-
function keys, home, end, pg up, pg down, arraows etc. you have to use
appropriate constants to detect them. A list is:
GLUT_KEY_F1, GLUT_KEY_F2, GLUT_KEY_F3, GLUT_KEY_F4, GLUT_KEY_F5, GLUT_KEY_F6,
GLUT_KEY_F7, GLUT_KEY_F8, GLUT_KEY_F9, GLUT_KEY_F10, GLUT_KEY_F11, GLUT_KEY_F12,
GLUT_KEY_LEFT, GLUT_KEY_UP, GLUT_KEY_RIGHT, GLUT_KEY_DOWN, GLUT_KEY_PAGE UP,
GLUT_KEY_PAGE DOWN, GLUT_KEY_HOME, GLUT_KEY_END, GLUT_KEY_INSERT
*/
void iSpecialKeyboard(unsigned char key)
{
if(key == GLUT_KEY_END)
{
exit(0);
}
//place your codes for other keys here
}
void ballChange(){
t=t+0.5;
ball_x = vx*t;
ball_y = vy*t-4.9*t*t;
//if(ball_x > 400 || ball_x < 0)dx = -dx;
//if(ball_y > 400 || ball_y < 0)dy= -dy;
//ball_y = -ball_y;
}
int main()
{
vx=vel*cos(50.00);
vy=vel*sin(50.00);
t=0;
//place your own initialization codes here.
iSetTimer(1000,ballChange);
//= 5;
//dy = 7;
//vx=43;
//vy=25;
iInitialize(1024, 512, "Angry Birds");
return 0;
} | true |
8398b7040c462c1c8faf57ec70e1cdf2232ae1b8 | C++ | wxxlouisa/FeatureGenerator | /fg_lite/feature/LookupFeatureSparseEncoder.h | UTF-8 | 7,491 | 2.734375 | 3 | [] | no_license | #pragma once
#include "autil/bitmap.h"
#include "autil/ConstString.h"
#include "autil/MurmurHash.h"
#include "fg_lite/feature/LookupFeatureEncoder.h"
namespace fg_lite {
template <typename KeyType, typename ValueType>
class SparseFormatter {
// format
// keyNum | key1, key2,...,keyN | offset1,...,offsetN | <bitmap1,values1>, ..., <bitmapN, valuesN>
// 4bytes | sizeof(key) * N | 4 * N |
// offset1 = 0, offset2 = bitmap1_bytes + sizeof(ValueType) * len(values1), ...
public:
typedef uint32_t KeyNumType;
typedef uint32_t OffsetType;
static constexpr size_t KEY_NUM_BYTES = sizeof(KeyNumType);
static constexpr size_t OFFSET_BYTES = sizeof(OffsetType);
static constexpr size_t KEY_BYTES = sizeof(KeyType);
static constexpr size_t VALUE_BYTES = sizeof(ValueType);
public:
SparseFormatter(const char *data, uint32_t dimension)
: _data(data)
, _dimension(dimension)
{
_keyNum = *(uint32_t *)_data;
_keys = (KeyType *)(_data + 4);
_offsets = (uint32_t *)(_keys + _keyNum);
_values = (uint8_t *)(_offsets + _keyNum);
}
public:
KeyType *getKeys() const {
return _keys;
}
uint32_t *getOffsets() const {
return _offsets;
}
uint8_t *getValues() const {
return _values;
}
size_t encodeValue(uint8_t *addr, const std::vector<float> &values) {
auto slotCount = autil::Bitmap::GetSlotCount(_dimension);
autil::Bitmap bitmap((uint32_t *)addr, _dimension, slotCount);
auto bitmapBytes = slotCount * autil::Bitmap::SLOT_BYTES;
ValueType *valueBase = (ValueType *)(addr + bitmapBytes);
uint32_t idx = 0;
for (size_t i = 0; i < std::min(values.size(), (size_t)_dimension); ++i) {
if (values[i] != 0) {
bitmap.Set(i);
valueBase[idx++] = (ValueType)values[i];
}
}
return bitmapBytes + idx * sizeof(ValueType);
}
std::pair<bool, uint32_t> find(KeyType key) const {
KeyType *end = _keys + _keyNum;
auto it = std::lower_bound(_keys, end, key);
if (it != end && *it == key) {
return std::make_pair(true, it - _keys);
}
return std::make_pair(false, (uint32_t)-1);
}
void decode(uint32_t keyIdx, float *buffer, uint32_t bufferSize) const {
assert(keyIdx < _keyNum);
uint32_t valueOffset = _offsets[keyIdx];
uint8_t *valueAddr = _values + valueOffset;
decodeValue(valueAddr, buffer, bufferSize);
}
private:
void decodeValue(uint8_t *valueAddr, float *buffer, uint32_t bufferSize) const {
auto slotCount = autil::Bitmap::GetSlotCount(_dimension);
autil::Bitmap bitmap((uint32_t *)valueAddr, _dimension, slotCount);
auto bitmapBytes = slotCount * autil::Bitmap::SLOT_BYTES;
ValueType *values = (ValueType *)(valueAddr + bitmapBytes);
uint32_t valueIdx = 0;
for (uint32_t i = 0; i < _dimension; ++i) {
if (bitmap.Test(i)) {
buffer[i] = (float)values[valueIdx++];
} else {
buffer[i] = 0.0f;
}
}
}
public:
static size_t getEncodedLength(uint32_t keyNum, uint32_t valueNum, uint32_t dimension) {
auto bitmapSlotCount = autil::Bitmap::GetSlotCount(dimension);
size_t bitmapSize = bitmapSlotCount * autil::Bitmap::SLOT_BYTES;
size_t perKeySize = KEY_BYTES + bitmapSize + OFFSET_BYTES;
size_t totalBytes = KEY_NUM_BYTES + perKeySize * keyNum + valueNum * VALUE_BYTES;
return totalBytes;
}
private:
const char *_data;
uint32_t _dimension;
uint32_t _keyNum;
KeyType *_keys;
uint32_t *_offsets;
uint8_t *_values;
};
template <typename KeyType, typename ValueType>
class SparseEncoder {
public:
using TypedSparseFormatter = SparseFormatter<KeyType, ValueType>;
public:
SparseEncoder(uint32_t keyNum, uint32_t valueNum, uint32_t dimension) {
_encodeBuffer.resize(TypedSparseFormatter::getEncodedLength(keyNum, valueNum, dimension), 0);
*(uint32_t *)_encodeBuffer.data() = keyNum;
_formatter.reset(new SparseFormatter<KeyType, ValueType>(_encodeBuffer.data(), dimension));
_currentKey = _formatter->getKeys();
_currentOffset = _formatter->getOffsets();
_currentValue = _formatter->getValues();
_encodedValueSize = 0;
}
public:
void encode(const KeyType key, const std::vector<float> &values) {
*_currentKey++ = key;
*_currentOffset++ = _encodedValueSize;
size_t bytes = _formatter->encodeValue(_currentValue, values);
_encodedValueSize += bytes;
_currentValue += bytes;
}
std::string &getEncodeBuffer() {
return _encodeBuffer;
}
private:
std::string _encodeBuffer;
std::unique_ptr<TypedSparseFormatter> _formatter;
// state for encode
KeyType *_currentKey;
uint32_t *_currentOffset;
uint8_t *_currentValue;
uint32_t _encodedValueSize;
};
template <typename KeyType, typename ValueType>
class SparseDecoder {
using TypedSparseFormatter = SparseFormatter<KeyType, ValueType>;
public:
SparseDecoder(const char *data, uint32_t dimension)
: _formatter(data, dimension)
{
}
public:
bool find(KeyType key, float *ret, uint32_t dimension) {
auto it = _formatter.find(key);
if (!it.first) {
return false;
}
_formatter.decode(it.second, ret, dimension);
return true;
}
private:
TypedSparseFormatter _formatter;
};
class LookupFeatureSparseEncoder {
public:
LookupFeatureSparseEncoder() = default;
~LookupFeatureSparseEncoder() = default;
private:
LookupFeatureSparseEncoder(const LookupFeatureSparseEncoder &) = delete;
LookupFeatureSparseEncoder& operator=(const LookupFeatureSparseEncoder &) = delete;
public:
static bool encode(const std::map<autil::ConstString, std::vector<float>> &docs,
const uint32_t dim,
std::string &output,
LookupFeatureV3KeyType hashType,
LookupFeatureV3ValueType valueType);
private:
static size_t nonZeroValueCount(const std::vector<float> &values, size_t dim) {
size_t count = 0;
auto pred = [&count](float v) { if (v != 0) count++; };
auto begin = values.begin();
auto end = begin + std::min(values.size(), dim);
std::for_each(begin, end, std::move(pred));
return count;
}
template <typename KeyType = uint64_t, typename ValueType = float>
static bool encodeSparse(const std::map<KeyType,std::vector<float>> &values,
size_t dim,
std::string &output)
{
if (values.empty()) {
output.clear();
return true;
}
size_t valueCount = 0;
for (const auto& keyVec: values) {
const auto& vec = keyVec.second;
valueCount += std::min(dim, nonZeroValueCount(vec, dim));
}
SparseEncoder<KeyType, ValueType> encoder(values.size(), valueCount, dim);
for (const auto &it : values) {
encoder.encode(it.first, it.second);
}
std::string &encodedBuffer = encoder.getEncodeBuffer();
output.swap(encodedBuffer);
return true;
}
protected:
AUTIL_LOG_DECLARE();
};
} // namespace fg_lite
| true |
17b704ba6263271cccc354b91d72807e41bdc955 | C++ | nmrodrigues/animal-shelter-file-based | /Dog.h | UTF-8 | 558 | 2.84375 | 3 | [] | no_license | //
// Created by Nicole Rodrigues on 5/3/19.
//
#ifndef ANIMALSHELTER_DOG_H
#define ANIMALSHELTER_DOG_H
#include "Animal.h"
#include <fstream>
class Dog : public Animal {
private:
static int nbrOfDogs;
string breed;
string type = "dog";
int myDogNumber;
public:
Dog();
void setBreed(string &dBreed);
string const getBreed();
const void dogSpeak(ostream &outputStream);
int getNumberOfDogs();
void const describe(ostream &outputStream);
string getDogType();
int getDogNumber();
};
#endif //ANIMALSHELTER_DOG_H
| true |
8716667dfc7abe788785d061ff81ffaa74f2c3c6 | C++ | MelvinSalcedo/topicosBaseDatosCompartida | /comparacion/Bases pequeñas y BX/Distancias.h | UTF-8 | 3,203 | 2.96875 | 3 | [] | no_license | #ifndef DISTANCIAS_H
#define DISTANCIAS_H
#include <iostream>
#include <functional>
#include "Utils.h"
typedef function<ValType(ValVec &, ValVec &)> DistanceFunction;
ValType manhattanDistance(ValVec & x, ValVec & y){
if(x.size() != y.size()) return 0;
ValType res = 0;
for(int i = 0; i < x.size(); i++){
if(x[i] == NULL_VAL or y[i] == NULL_VAL) continue;
else res += abs(x[i] - y[i]);
}
return res;
}
ValType euclideanDistance(ValVec & x, ValVec & y){
if(x.size() != y.size()) return 0;
ValType res = 0;
for(int i = 0; i < x.size(); i++){
if(x[i] == NULL_VAL or y[i] == NULL_VAL) continue;
else res += pow(x[i] - y[i], 2);
}
return (ValType) sqrt(res);
}
ValType minkowskiDistance(ValVec & x, ValVec & y, int r){
if(x.size() != y.size()) return 0;
ValType res = 0;
for(int i = 0; i < x.size(); i++){
if(x[i] == NULL_VAL or y[i] == NULL_VAL) continue;
res += pow(abs(x[i] - y[i]), r);
}
if(r == 2) return (ValType) sqrt(res);
return res;
}
ValType cosenDistance(ValVec & x, ValVec & y){
if(x.size() != y.size()) return 0;
if((vectorModule(x) * vectorModule(y)) == 0) return -1;
return dotProduct(x,y) / (vectorModule(x) * vectorModule(y));
}
ValType cosenDistanceSinM(ValVec & x, ValVec & y){
return dotProduct(x,y);
}
ValType personAproxDN(ValVec & x, ValVec & y){
ValType res = 0;
ValVec xx;
ValVec yy;
tie(xx,yy) = deleteNulls(x,y);
ValType n = xx.size();
cout<<"N->"<<n<<endl;
return (ValType) (dotProduct(xx,yy) - (sumatoria(xx) * sumatoria(yy) / n)) / (sqrt(sumatoriaCuadratica(xx) - pow(sumatoria(xx),2) / n) * sqrt(sumatoriaCuadratica(yy) - pow(sumatoria(yy),2) / n));
//ValType div = (sqrt(sumatoriaCuadratica(x) - pow(sumatoria(x),2) / n) * sqrt(sumatoriaCuadratica(y) - pow(sumatoria(y),2) / n));
//if(div == 0) return INFINITO_NEGATIVO;
//return (ValType) (dotProduct(x,y) - (sumatoria(x) * sumatoria(y) / n)) / div;
}
ValType personAprox(ValVec & x, ValVec & y){
ValType res = 0;
//tie(xx,yy) = deleteNulls(x,y);
//ValType n = xx.size();
ValType n = x.size();
//cout<<"N->"<<n<<endl;
//return (ValType) (dotProduct(xx,yy) - (sumatoria(xx) * sumatoria(yy) / n)) / (sqrt(sumatoriaCuadratica(xx) - pow(sumatoria(xx),2) / n) * sqrt(sumatoriaCuadratica(yy) - pow(sumatoria(yy),2) / n));
ValType div = (sqrt(sumatoriaCuadratica(x) - pow(sumatoria(x),2) / n) * sqrt(sumatoriaCuadratica(y) - pow(sumatoria(y),2) / n));
if(div == 0) return -1;
return (ValType) (dotProduct(x,y) - (sumatoria(x) * sumatoria(y) / n)) / div;
}
ValType cosenoAjustado(ValVec & x, ValVec & y, ValVec & proms){
ValType temp1;
ValType temp2;
ValType d = 0;
ValType t1 = 0;
ValType t2 = 0;
for(int i = 0; i < x.size(); i++){
if(x[i] == NULL_VAL or y[i] == NULL_VAL) continue;
temp1 = proms[i] - x[i];
temp2 = proms[i] - y[i];
d += temp1 * temp2;
t1 += pow(temp1, 2);
t2 += pow(temp2, 2);
}
ValType t = (sqrt(t1) * sqrt(t2));
if(t == 0){
return -1;
}
return (ValType) d / t;
}
ValType desviacionEstandar(ValVec & x, ValVec & y){
float cardinalidad = x.size();
ValType res = 0;
for(int i = 0; i < x.size(); i++){
res += (x[i] - y[i]) / cardinalidad;
}
cout<<"R->"<<res<<endl;
cout<<cardinalidad<<endl;
return res;
}
#endif
| true |
ade0d5a0ad28cd574d604fddb64cc7b7c0c32cc5 | C++ | yananfan/CodeTest | /Offer/35_DeleteStr2InStr1.cpp | UTF-8 | 763 | 3.53125 | 4 | [] | no_license | //#define _DeleteStr2InStr1_
#ifdef _DeleteStr2InStr1_
#include<iostream>
#include<cstring>
using namespace std;
char * DeleteStr2InStr1(char * const str1, const char * const str2);
int main()
{
char str1[] = "we are students.";
cout << "str1 = " << str1 << endl;
char str2[] = "aeiou";
cout << "str2 = " << str2 << endl;
char* str = DeleteStr2InStr1(str1, str2);
cout << "str = " << str << endl;
return 0;
}
char * DeleteStr2InStr1(char * const str1, const char * const str2) {
int len2 = strlen(str2);
int hashtable[256] = { 0 };
char* p = str1;
int p1 = 0;
for (int i = 0;i < len2;i++)
hashtable[str2[i]] = 1;
while (*p) {
if (hashtable[*p] == 0)
str1[p1++] = *p;
p++;
}
str1[p1] = '\0';
return str1;
}
#endif // _DeleteStr2InStr1_ | true |
d8df6955ef4fac57b097c77a2be80f453af79e75 | C++ | denis-gubar/Leetcode | /all/1056. Confusing Number.cpp | UTF-8 | 281 | 2.875 | 3 | [] | no_license | class Solution {
public:
bool confusingNumber(int N) {
vector<int> to{ 0, 1, -1, -1, -1, -1, 9, -1, 8, 6 };
int other = 0;
int x = N;
while (x)
{
int k = to[x % 10];
if (k < 0)
return false;
x /= 10;
other = other * 10 + k;
}
return N != other;
}
}; | true |
08aea13fe71a483fe18dae905221186992ad1b2e | C++ | finestgreen/qUAck | /qUAck/Game.h | UTF-8 | 845 | 2.515625 | 3 | [] | no_license | #ifndef _GAME_H_
#define _GAME_H_
#include "EDF/EDF.h"
class Game
{
public:
Game();
virtual ~Game();
virtual char *ContentType() = 0;
bool IsRunning();
bool IsEnded();
bool IsCreator();
int ServiceID();
virtual EDF *CreateOptions();
virtual EDF *JoinOptions();
virtual EDF *StartOptions();
virtual EDF *KeyOptions() = 0;
virtual bool Create(int iServiceID, EDF *pOptions);
virtual bool Join(int iServiceID, EDF *pOptions);
virtual bool Start(EDF *pOptions);
virtual bool End();
virtual bool Key(char cOption) = 0;
virtual bool Loop() = 0;
virtual bool Action(const char *szAction, EDF *pAction);
private:
enum GameState { NOT_STARTED, STARTED, ENDED };
GameState m_iState;
bool m_bIsCreator;
int m_iServiceID;
bool Subscribe(int iServiceID);
bool Request(const char *szAction, EDF *pEDF);
};
#endif
| true |
2d93e8eac5b0453d2f483894b894237209bc8fec | C++ | LaCulotte/chinko_bot | /chinko_bot/types/game/context/roleplay/HumanOptionFollowers.h | UTF-8 | 878 | 2.546875 | 3 | [] | no_license | #ifndef HUMANOPTIONFOLLOWERS_H
#define HUMANOPTIONFOLLOWERS_H
#include "HumanOption.h"
#include "IndexedEntityLook.h"
class HumanOptionFollowers : public HumanOption {
public:
// Constructor
HumanOptionFollowers() {};
// Copy constructor
HumanOptionFollowers(const HumanOptionFollowers& other) = default;
// Copy operator
HumanOptionFollowers& operator=(const HumanOptionFollowers& other) = default;
// Destructor
~HumanOptionFollowers() = default;
virtual unsigned int getId() override { return typeId; };
static const unsigned int typeId = 7484;
// Turns raw data into the usable data (type's attributes)
virtual bool deserialize(shared_ptr<MessageDataBuffer> input) override;
// Turns the type's attributes into raw data
virtual bool serialize(shared_ptr<MessageDataBuffer> output) override;
vector<IndexedEntityLook> followingCharactersLook;
};
#endif | true |
6cc966c0dee08393b9901faab86183dcfb70f78d | C++ | ArturMania/Personal_Wallet | /DateUsageMethods.cpp | UTF-8 | 7,222 | 3.203125 | 3 | [
"Unlicense"
] | permissive | #include "DateUsageMethods.h"
int DateUsageMethodes::getCurrentYear() {
time_t now =time(&now);
struct tm*dt =localtime(&now);
int currentYear =(dt->tm_year+1900);
return currentYear;
}
int DateUsageMethodes::getCurrentMonth() {
time_t now =time(&now);
struct tm*dt =localtime(&now);
int currentMonth=(dt->tm_mon+1);
return currentMonth;
}
int DateUsageMethodes::getCurrentDay() {
time_t now =time(&now);
struct tm*dt =localtime(&now);
int currentDay =(dt->tm_mday);
return currentDay;
}
int DateUsageMethodes::getFirstDayOfCurrentMonth() {
int year=getCurrentYear();
int month=getCurrentMonth();
string firstDay="01";
string firstDayOfCurrentMonth=changeYearToString(year)+changeMonthToString(month)+firstDay;
int firstDayOfCurrentMonthInt=changeDateToInt(firstDayOfCurrentMonth);
return firstDayOfCurrentMonthInt;
}
int DateUsageMethodes::getFirstDayOfPreviousMonth() {
string firstDay="01";
int year=getCurrentYear();
int month=getCurrentMonth();
if(month==1) {
month=12;
year=year-1;
} else
month--;
string firstDayOfPreviousMonth=changeYearToString(year)+changeMonthToString(month)+firstDay;
int firstDayOfPreviousMonthInt=changeDateToInt(firstDayOfPreviousMonth);
return firstDayOfPreviousMonthInt;
}
int DateUsageMethodes::getLastDayOfPreviousMonth() {
int lastDay=0;
int year=getCurrentYear();
int month=getCurrentMonth();
if(month==1) {
month=12;
year=year-1;
} else
month--;
lastDay=howManyDaysHaveMonth(month,year);
string lastDayOfPreviousMonth=changeYearToString(year)+changeMonthToString(month)+changeDayToString(lastDay);
int lastDayOfPreviousMonthInt=changeDateToInt(lastDayOfPreviousMonth);
return lastDayOfPreviousMonthInt;
}
int DateUsageMethodes::getCurrentDate() {
int year=getCurrentYear();
int month=getCurrentMonth();
int day=getCurrentDay();
string date=changeDateToString(year,month,day);
int dateInt=changeDateToInt(date);
return dateInt;
}
int DateUsageMethodes::howManyDaysHaveMonth(int month,int year) {
int days=0;
if((month==4)||(month==6)||(month==9)||(month==11)) {
days=30;
} else if(month==2) {
if(isItLeapYear(year)==true)
days=29;
else
days=28;
} else {
days=31;
}
return days;
}
string DateUsageMethodes::changeYearToString(int year) {
string yearAsString = AuxillaryMethodes::convertIntToString(year);
return yearAsString;
}
string DateUsageMethodes::changeMonthToString(int month) {
string monthAsString = AuxillaryMethodes::convertIntToString(month);
if(monthAsString.size()<2)
monthAsString.insert(0,"0");
return monthAsString;
}
string DateUsageMethodes::changeDayToString(int day) {
string dayAsString = AuxillaryMethodes::convertIntToString(day);
if(dayAsString.size()<2)
dayAsString.insert(0,"0");
return dayAsString;
}
string DateUsageMethodes::changeDateWithDashesToString(string dateDashedString) {
string year="",month="",day="",date="";
year=dateDashedString.substr(0,4);
int yearInt=AuxillaryMethodes::convertStringToInt(year);
month=dateDashedString.substr(5,2);
int monthInt=AuxillaryMethodes::convertStringToInt(month);
day=dateDashedString.substr(8,2);
int dayInt=AuxillaryMethodes::convertStringToInt(day);
string yearStr=changeYearToString(yearInt);
string monthStr=changeMonthToString(monthInt);
string dayStr=changeDayToString(dayInt);
date=yearStr+monthStr+dayStr;
return date;
}
string DateUsageMethodes::changeIntDateToDateWithDashes(int dateInt) {
string dateString=AuxillaryMethodes::convertIntToString(dateInt);
string yearStr=dateString.substr(0,4);
string monthStr=dateString.substr(4,2);
string dayStr=dateString.substr(6,2);
string dateWithDashes=yearStr+"-"+monthStr+"-"+dayStr;
return dateWithDashes;
}
string DateUsageMethodes::changeDateToString(int year,int month,int day) {
string dateAsString="";
string yearAsString=changeYearToString(year);
string monthAsString = changeMonthToString(month);
string dayAsString = changeDayToString(day);
dateAsString=yearAsString+monthAsString+dayAsString;
return dateAsString;
}
int DateUsageMethodes::changeDateToInt(string date) {
int dateAsInt=0;
dateAsInt=AuxillaryMethodes::convertStringToInt(date);
return dateAsInt;
}
bool DateUsageMethodes::checkEarlierDate(int firstDate, int secondDate) {
if(firstDate<secondDate)
cout<<"First Date is earlier."<<endl;
else
cout<<"Second Date is earlier "<<endl;
}
bool DateUsageMethodes::isItLeapYear(int year) {
return((year%4==0 && year%100!=0)||(year%400==0));
}
bool DateUsageMethodes::isYearCorrect(int year) {
time_t now =time(&now);
struct tm*dt =localtime(&now);
int currentYear =(dt->tm_year+1900);
if((year>=2000)&&(year<=currentYear))
return year;
else {
cout<<"Wrong year input!"<<endl;
system("pause");
system ("cls");
return 0;
}
}
bool DateUsageMethodes::isMonthCorrect(int month) {
if((month>=1)&&(month<=12))
return month;
else {
cout<<"Wrong month input!"<<endl;
system("pause");
system ("cls");
return 0;
}
}
bool DateUsageMethodes::isDayCorrect(int day,int month,int year) {
if((month==4)||(month==6)||(month==9)||(month==11)) {
if(day>30) {
cout<<"Wrong day input!"<<endl;
system("pause");
system ("cls");
return false;
}
} else if(month==2) {
if(isItLeapYear(year)==true) {
if(day>29) {
cout<<"Wrong day input!"<<endl;
system("pause");
system ("cls");
return false;
}
} else {
if(day>28) {
cout<<"Wrong day input!"<<endl;
system("pause");
system ("cls");
return false;
}
}
} else {
if(day>31) {
cout<<"Wrong day input!"<<endl;
system("pause");
system ("cls");
return false;
}
}
return true;
}
bool DateUsageMethodes::isDateCorrect(string dateDashedString) {
string year="",month="",day="",date="";
year=dateDashedString.substr(0,4);
int yearInt=AuxillaryMethodes::convertStringToInt(year);
month=dateDashedString.substr(5,2);
int monthInt=AuxillaryMethodes::convertStringToInt(month);
day=dateDashedString.substr(8,2);
int dayInt=AuxillaryMethodes::convertStringToInt(day);
if((isYearCorrect(yearInt)==true)&&(isMonthCorrect(monthInt)==true)&&(isDayCorrect(dayInt,monthInt,yearInt)==true)) {
return true;
} else
return false;
}
void DateUsageMethodes::setStartDate(int newStartDate) {
startDate=newStartDate;
}
void DateUsageMethodes::setEndDate(int newEndDate) {
endDate=newEndDate;
}
int DateUsageMethodes::getStartDate() {
return startDate;
}
int DateUsageMethodes::getEndDate() {
return endDate;
}
//FW
| true |
32c3ed06c68e46882907f04f114c8a2c998418d3 | C++ | thejasonfisher/voxelTerrain | /apps/math/source/blub/math/vector3int32map.hpp | UTF-8 | 3,011 | 2.921875 | 3 | [] | no_license | #ifndef VECTOR3INT32MAP_HPP
#define VECTOR3INT32MAP_HPP
#include "blub/math/axisAlignedBoxInt32.hpp"
#include "blub/core/noncopyable.hpp"
namespace blub
{
template <typename dataType>
class vector3int32map : public noncopyable
{
public:
vector3int32map()
: m_data(nullptr)
{
;
}
~vector3int32map()
{
if (m_data != nullptr)
{
delete [] m_data;
}
}
void setValue(const vector3int32& pos, const dataType& toSet)
{
const int32 index(convertToIndex(pos));
BASSERT(index < m_bounds.getVolume());
m_data[index] = toSet;
}
const dataType& getValue(const vector3int32& pos) const
{
const int32 index(convertToIndex(pos));
return m_data[index];
}
void resize(const axisAlignedBoxInt32& aabb)
{
axisAlignedBoxInt32 resizedAabb(m_bounds);
resizedAabb.extend(aabb);
if (resizedAabb == m_bounds)
{
return;
}
const axisAlignedBoxInt32 oldBounds(m_bounds);
const vector3int32 oldStart(oldBounds.getMinimum());
const vector3int32 oldEnd(oldBounds.getMaximum());
const dataType* oldData(m_data);
m_bounds = resizedAabb;
BASSERT(m_bounds.getVolume() > 0);
m_data = new dataType[m_bounds.getVolume()];
if (oldData != nullptr)
{
for (int32 indX = oldStart.x; indX < oldEnd.x; ++indX)
{
for (int32 indY = oldStart.y; indY < oldEnd.y; ++indY)
{
for (int32 indZ = oldStart.z; indZ < oldEnd.z; ++indZ)
{
m_data[convertToIndex(vector3int32(indX, indY, indZ))] = oldData[convertToIndex(vector3int32(indX, indY, indZ), oldBounds)];
}
}
}
delete [] oldData;
}
}
void extend(const vector3int32& toExtend)
{
axisAlignedBoxInt32 resizedAabb(m_bounds);
resizedAabb.extend(toExtend);
resize(resizedAabb);
}
void extend(const axisAlignedBoxInt32 &toExtend)
{
axisAlignedBoxInt32 resizedAabb(m_bounds);
resizedAabb.extend(toExtend);
resize(resizedAabb);
}
const axisAlignedBoxInt32& getBounds(void) const
{
return m_bounds;
}
protected:
int32 convertToIndex(const vector3int32& toConvert) const
{
return convertToIndex(toConvert, m_bounds);
}
static int32 convertToIndex(const vector3int32& toConvert, const axisAlignedBoxInt32& bounds)
{
BASSERT(toConvert >= bounds.getMinimum());
BASSERT(toConvert < bounds.getMaximum());
const vector3int32 size(bounds.getSize());
const vector3int32 min(bounds.getMinimum());
return (toConvert.x-min.x)*size.y*size.z + (toConvert.y-min.y)*size.z + (toConvert.z-min.z);
}
dataType *m_data;
axisAlignedBoxInt32 m_bounds;
};
}
#endif // VECTOR3INT32MAP_HPP
| true |
2d25a63c26c3a4080f5e94e18dbe867f0b12c949 | C++ | xieshiyao/SimpleSQL | /TuplePool.h | UTF-8 | 5,073 | 2.75 | 3 | [] | no_license | #pragma once
#ifndef TUPLEPOOL_H
#define TUPLEPOOL_H
#include <cstring>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "myassert.h"
#include "Tuple.h"
//template <size_t max_size = 1024>
class TuplePool {
int fd; // 表文件的描述符
size_t fs; // 表文件的大小
int last; // 最后一个元组
int cap; // 缓冲池容量
int which; // 当前遍历到哪一条元组,which >= 0
TableMeta* meta; // 所属的表的元数据
uint8_t* pool; // 缓冲池
uint8_t* mmf; // 内存映射文件,将分页管理交由OS完成,且加快了文件读写 (少了一次内核缓存)
static constexpr size_t max_size = 128;
uint8_t* ptr(int which) const {
return pool + which * meta->tupleSize;
}
off_t off(int which) const {
return which * meta->tupleSize;
}
Tuple seek(int which) const { // 在内存映射中seek
return Tuple(mmf + which * meta->tupleSize, *meta);
}
// 建立内存映射
void mmap(size_t len) {
mmf = (uint8_t*)::mmap(nullptr, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
assert(mmf != MAP_FAILED, "mmap");
/*if (mmf == MAP_FAILED)
mmf = nullptr;*/
}
// 重建内存映射,增加大小为size的空间
void mremap(size_t size) {
mmf = (uint8_t*)::mremap(mmf, fs, fs + size, MREMAP_MAYMOVE);
assert(mmf != MAP_FAILED, "mremap");
}
friend class Table;
public:
TuplePool(const std::string& name)
:fd(open(name.c_str(), O_RDWR | O_CREAT, 0644)),which(0),
last(-1), meta(nullptr), pool(nullptr), mmf(nullptr) {
assert(fd >= 0, "open");
// init fs
struct stat m;
int ret = fstat(fd, &m);
assert(ret == 0, "fstat");
fs = m.st_size;
}
// 真正可以初始化的时机是添加完所有的字段
void init(TableMeta& meta) {
this->meta = &meta;
cap = max_size / meta.tupleSize;
pool = new uint8_t[cap * meta.tupleSize]{ 0 };
if (fs)
mmap(fs);
}
~TuplePool() {
// 将pool中的元组写到磁盘,然后才可以delete以释放内存
if(meta)
save(); // TODO 为了方便,这里重用了save(),里面有mmap操作,而后面就析构了,效率有点低。
delete[] pool;
// 关闭文件描述符
close(fd);
// 同步修改到文件,并munmap
if (mmf) {
int ret = msync(mmf, fs, MS_SYNC);
assert(ret == 0, "msync");
ret = munmap(mmf, fs);
assert(ret == 0, "munmap");
}
}
// 往缓冲池中插入空元组,并返回该元组
Tuple insert() { // 不要怀疑,这里可以直接返回变量,而不用返回引用,靠编译器进行RVO优化,下同
if (size() >= cap) {
save();
last = -1;
}
last++;
return Tuple(ptr(last), *meta);
}
// 删除所有元组
void removeAll() {
last = -1;
int ret;
if (mmf) { // 这个时候可能还没有建立内存映射
ret = munmap(mmf, fs);
assert(ret == 0, "munmap");
mmf = nullptr; // !!!
}
fs = 0; // 不能在解除内存映射之前修改fs,及截断文件
ret = ftruncate(fd, 0);
assert(ret == 0, "ftruncate");
}
void remove() {
int which = this->which - 1;
if (which < size()) { // 从缓冲池中删除
if (which != last) {
memcpy(ptr(which), ptr(last), meta->tupleSize);
}
last--;
}
else { // 从内存映射中删除,即置相关标志位为空
seek(which - size()).setEmpty(true);
HoleQueue& q = meta->holeQ;
q.push(which - size());
}
}
Tuple operator[](int which) const { // 请确保 0 <= which < size()
return Tuple(ptr(which), *meta);
}
Tuple next() {
if (which < size()) { // 从pool中拿元组
return this->operator[](which++);
}
else { // 从内存映射中拿元组
int max = fs / meta->tupleSize + size();
while (which < max && seek(which - size()).isEmpty()) {
which++;
}
if(which == max) {
which = 0;
throw std::out_of_range("a23187");
}
else {
int i = which - size();
which++;
return seek(i);
}
}
}
void save() {
HoleQueue& q = meta->holeQ;
for (int i = 0; i < size(); i++) {
if (q.empty()) {
// append to db file
off_t ret1 = lseek(fd, 0, SEEK_END);
assert(ret1 != -1, "lseek");
size_t dSize = (size() - i) * meta->tupleSize; // 新增部分的大小
ssize_t ret2 = write(fd, ptr(i), dSize);
assert(ret2 == dSize, "write");
if (mmf)
mremap(dSize); // 当有append操作时,必须重建内存映射,这也是mmap方法的一个缺点
else
mmap(fs + dSize);
fs += dSize;
break; // !!!
}
else {
// reuse the hole in db file
ssize_t ret = pwrite(fd, ptr(i), meta->tupleSize, off(q.front()));
assert(ret == meta->tupleSize, "pwrite");
q.pop();
}
}
}
int size() const {
return last + 1;
}
int capacity() const {
return cap;
}
};
// TODO 不嫌麻烦的话,可以把成员函数的定义移到类模板之外进行
#endif // !TUPLEPOOL_H
| true |