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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
c2456ce710c2b91f679662202af3442e72e635e2 | C++ | azconita/worms | /server-main.cpp | UTF-8 | 701 | 2.59375 | 3 | [] | no_license | /*
* server.cpp
*
* Created on: Jun 3, 2018
* Author: gabi
*/
#include "Game.h"
#include "Logger.h"
#include "Socket.h"
logger oLog("server.log");
int main(int argc, char *argv[]) {
char * port = argv[1];
Socket socket(NULL,port);
socket.bind_and_listen();
Socket client = socket.accept_socket(); //esto despues va estar en el game una vez por cada jugador que se conecte
std::string s("file.yaml");
Game game(s, 2, client);
Socket client2 = socket.accept_socket();
game.add_player(client2);
//game.start();
//este thread espera que se ingrese "q" para terminar ejecución
while (getchar() != 'q') {
continue;
}
game.stop();
socket.shut();
return 0;
}
| true |
cacbf8a2e2e6450dd56936b973f5cf3d8d77344e | C++ | ShreyasSubhedar/Codes | /TREES/Find_pair_sum_in_BST.cpp | UTF-8 | 1,921 | 3.71875 | 4 | [] | no_license | / Initial Template for C++
// CPP program to find a pair with
// given sum using hashing
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *left, *right;
Node(int x) {
data = x;
left = right = NULL;
}
};
Node* insert(Node* root, int key) {
if (root == NULL) return new Node(key);
if (key < root->data)
root->left = insert(root->left, key);
else
root->right = insert(root->right, key);
return root;
}
bool findPair(Node* root, int sum);
// Driver code
int main() {
int t;
cin >> t;
while (t--) {
Node* root = NULL;
int n, x;
cin >> n;
int val;
for (int i = 0; i < n; i++) {
cin >> val;
root = insert(root, val);
}
cin >> x;
if (findPair(root, x))
cout << "1" << endl;
else
cout << "0" << endl;
}
return 0;
}
}
/*This is a function problem.You only need to complete the function given below*/
/* BST Node
struct Node {
int data;
struct Node *left, *right;
Node(int x) {
data = x;
left = right = NULL;
}
};
*/
// This function should return true
// if there is a pair in given BST with
// given sum.
int inorder(Node *root,int q){
if(root==NULL)
return 0;
if(q==root->data)
return 1;
if(q<root->data)
inorder(root->left,q);
else if(q>root->data)
inorder(root->right,q);
}
/*int find(Node *root,int sum,unordered_map<int,int>M){
if(root==NULL)
return false;
if(M.find(sum-root->data)!=M.end())
return true;
return find(root->left,sum,M)||find(root->right,sum,M);
}*/
bool findPair(Node* root, int sum) {
//unordered_map<int,int>M;
//return find(root,sum,M);
for(int i=0;i<=sum;i++){
if(inorder(root,i)&&inorder(root,sum-i)&&(i!=sum-i)){
return 1;
}
}
return 0;
}
| true |
92271e51d9b16313f6241f8f8040c48e21b48aa3 | C++ | yumkong/cpp_prac | /cc/cc20_2.cpp | UTF-8 | 661 | 3.84375 | 4 | [] | no_license | // make a perfect shuffle of a deck of cards
#include <iostream>
#include <cstdlib>
using namespace std;
void swap(int &a, int &b)
{
int tmp = a;
a = b;
b = tmp;
}
void RandomShuffle(int a[], int n)
{
for(int i = 0; i < n; ++i)
{
// generate random number between i to n - 1
int j = rand() % (n - i) + i;
swap(a[i], a[j]);
}
}
int main()
{
// make seed at the main func, and rand() can be used in and sub-func
srand((unsigned)time(0));
int n = 9;
int a[] = {1,2,3,4,5,6,7,8,9};
RandomShuffle(a, n);
for(int i = 0; i < n; ++i)
{
cout << a[i] << endl;
}
return 0;
}
| true |
bfbd2330f32f1d021c6ddb7408118e6d89449592 | C++ | H-Shen/Collection_of_my_coding_practice | /Hackerrank/Algorithms/Flipping_bits.cpp | UTF-8 | 615 | 2.984375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
// Complete the flippingBits function below.
long flippingBits(long n) {
const static int MAXN = 32;
bitset <MAXN> A(n);
A.flip();
return A.to_ullong();
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int q;
cin >> q;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
for (int q_itr = 0; q_itr < q; q_itr++) {
long n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
long result = flippingBits(n);
fout << result << "\n";
}
fout.close();
return 0;
}
| true |
49bc628b309dd41e5d5b5f60e8e9648d69209796 | C++ | kantuni/LeetCode | /728/self-dividing-numbers.cpp | UTF-8 | 641 | 3.6875 | 4 | [] | no_license | class Solution {
private:
bool isSelfDividingNumber(int n) {
int nc = n;
while (nc > 0) {
int d = nc % 10;
if (d == 0) {
// A self-dividing number is not
// allowed to contain the digit zero.
return false;
}
if (n % d != 0) {
return false;
}
nc /= 10;
}
return true;
}
public:
vector<int> selfDividingNumbers(int left, int right) {
vector<int> ans;
for (int i = left; i <= right; i++) {
if (isSelfDividingNumber(i)) {
ans.push_back(i);
}
}
return ans;
}
};
| true |
efc74051034b868bad35e897e876bfe0d1293cad | C++ | MatyazhV/Attestation | /Downloads/2_22.cpp | UTF-8 | 551 | 2.625 | 3 | [] | no_license |
#include <iostream>
#include <cmath>
using namespace std;
float n, a, z,max1;
bool flag = false;
int main()
{
setlocale(LC_ALL, "Rus");
cout << "Введите n" << endl;
cin >> n;
max1 = sin(n + 1 / n);
for (int i = 1; i <= n; i++)
{
if (n > 0)
{
a = sin(n + i / n);
cout << a << " ";
if (a > max1)
{
max1 = a;
z = i;
}
}
}
cout << endl;
cout << max1 << " " << z;
} | true |
22600ec2ad5f0d9499b6668b5d448966a8fa2498 | C++ | MrHug/Arduino-Simulator | /simulatorCode/BaESimulator/linesegment.h | UTF-8 | 376 | 2.578125 | 3 | [] | no_license | #ifndef LINESEGMENT_H
#define LINESEGMENT_H
#include "line.h"
class LineSegment : public Line
{
public:
LineSegment();
LineSegment(Point start, Point end);
LineSegment(double x1, double y1, double x2, double y2);
bool isIntersect(Line that);
bool containsPoint(Point p);
double length();
Point start, end;
private:
};
#endif // LINESEGMENT_H
| true |
7bfb90d3fff0e58f372f1de2aa5e358c1207d253 | C++ | datouroony/ControlsVSP | /TestingCode/SteuartPlatformTests/SteuartPlatformTests.ino | UTF-8 | 2,036 | 3 | 3 | [] | no_license | #include <Servo.h>
// What pin to connect the sensor to
#define SENSOR0 A0
#define SENSOR1 A1
#define SENSOR2 A2
Servo motor;
int motorSpeed;
float S0Length0 = 17.9; //mm
float S1Length0 = 17.8;
float S2Length0 = 17.4;
float S0Resistance0 = 70; //ohm 77
float S1Resistance0 = 71;
float S2Resistance0 = 77;
float Resistor = 76.8;
float SensorResistance0;
float SensorResistance1;
float SensorResistance2 ;
float S0V;
float S1V;
float S2V;
float S0Length;
float S1Length;
float S2Length;
void setup(void) {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
Serial.begin(9600);
}
void calculate_Lenght(){
}
void loop(void) {
S0V = (1023.0 / analogRead(SENSOR0)) - 1.0;
S1V = (1023.0 / analogRead(SENSOR1)) - 1.0;
S2V = (1023.0 / analogRead(SENSOR2)) - 1.0;
// convert the value to resistance
SensorResistance0 = Resistor / S0V;
SensorResistance1 = Resistor / S1V;
SensorResistance2 = Resistor / S2V;
S0Length = (SensorResistance0 / S0Resistance0) * S0Length0;
S1Length = (SensorResistance1 / S1Resistance0) * S1Length0;
S2Length = (SensorResistance2 / S2Resistance0) * S2Length0;
Serial.print("S0 : ");
Serial.println(S0Length);
Serial.print("S1 : ");
Serial.println(S1Length);
Serial.print("S1 : ");
Serial.println(S1Length);
//Serial.print("SENSOR LENGHT");
//Serial.println(S0Length);
//length = (.0356 * resistance) - 2.627; //2.727
for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(50); // waits 15ms for the servo to reach the position
}
for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(50); // waits 15ms for the servo to reach the position
}
}
| true |
04fdf82d174bb642f8c6892bf39a964a7176975e | C++ | s4mu313/Tensor | /include/Tensor/tensor_ref.h | UTF-8 | 12,337 | 3.234375 | 3 | [] | no_license | #ifndef TENSOR_REF_H
#define TENSOR_REF_H
#include <iostream>
#include <vector>
#include <cassert>
#include "tensor_base.h"
#include "tensor_initializer.h"
#include "tensor_f_decl.h"
#include "../macros.h"
NUM_BEGIN
template <typename T, std::size_t N>
class Tensor_iterator;
/**
* @brief The Tensor_ref class. Contains a reference to
* all values stored in N-D tensor and provide access
* to them.
*/
template <typename T, std::size_t N>
class Tensor_ref : public Tensor_base<T, N> {
public:
/// Aliases
using pointer = T*;
using reference = T&;
using const_reference = const T&;
using value_type = T;
using iterator = Tensor_iterator<T, N>;
using const_iterator = const Tensor_iterator<T, N>;
/// Deleted ctor.
Tensor_ref() = delete;
Tensor_ref& operator=(Tensor_init<T, N>&) = delete;
/// Default ctor.
Tensor_ref(Tensor_ref&&) = default;
Tensor_ref(const Tensor_ref&) = default;
~Tensor_ref() = default;
/// assignement
Tensor_ref& operator=(Tensor_ref& t) {
assert(this->_desc.extents == t.descriptor().extents);
std::copy(t.begin(), t.end(), begin());
return *this;
}
/// assignement const
Tensor_ref& operator=(const Tensor_ref& t) {
assert(this->_desc.extents == t.descriptor().extents);
std::copy(t.cbegin(), t.cend(), begin());
return *this;
}
/// ctor with param
Tensor_ref(const Tensor_slice<N>& desc, pointer elems)
: Tensor_base<T, N>{desc},
_elems{elems}
{}
/// ctor. Create Tensor_ref from Tensor.
template <typename U>
Tensor_ref& operator=(const Tensor<U, N>& t)
{
assert(this->_desc.extents == t.descriptor().extents);
std::copy(t.cbegin(), t.cend(), begin());
return *this;
}
/**
* @brief operator ().
* @param dims
* @return the elements indexed by dims.
*/
template<typename... Dims>
Enable_if<tensor_impl::_requesting_element(), reference>
operator()(Dims... dims)
{
static_assert (sizeof... (dims) == N,
"Tensor_ref<T, N>::operator(): dimension mismatch");
assert(tensor_impl::_check_bounds(this->_desc, dims...));
return *(_elems + this->_desc(dims...));
}
/**
* @brief operator () (const).
* @param dims
* @return the elements indexed by dims.
*/
template<typename... Dims>
Enable_if<tensor_impl::_requesting_element(), const_reference>
operator()(Dims... dims) const
{
static_assert (sizeof... (dims) == N,
"Tensor_ref<T, N>::operator(): dimension mismatch");
assert(tensor_impl::_check_bounds(this->_desc, dims...));
return *(_elems + this->_desc(dims...));
}
/**
* @brief slice. Get a slice of a N-dimensional
* structure by a specific dimension.
* Create a new descriptor and return a
* Tensor_ref with N - 1 dimensions.
* @param i
* @return Tensor_ref<T, N- 1>.
*/
template<std::size_t D>
Tensor_ref<T, N - 1>
slice(std::size_t i) const
{
static_assert (D < N, "Tensor_ref<T, N - 1>::Dimension of slice "
"(D) must be lower than N");
assert(i < this->_desc.extents[D]);
Tensor_slice<N - 1> t;
tensor_impl::_slice_dim<D>(i, this->_desc, t);
return {t, _elems};
}
/**
* @brief row. Only in a matrix, return a row slice.
* @param i
* @return Tensor_ref.
*/
template<std::size_t NN = N,
typename = Enable_if<NN == 2>>
Tensor_ref<T, N - 1>
row(std::size_t i) const
{ return slice<0>(i); }
/**
* @brief col. Only in a matrix, return a col slice.
* @param i
* @return Tensor_ref.
*/
template<std::size_t NN = N,
typename = Enable_if<NN == 2>>
Tensor_ref<T, N - 1>
col(std::size_t i) const
{ return slice<1>(i); }
/**
* @brief operator []. Only in a matrix, make row slice.
* @param i
* @return Tensor_ref.
*/
template<std::size_t NN = N,
typename = Enable_if<NN == 2>>
std::size_t
operator[](std::size_t i) const
{ return row(i); }
/**
* @brief operator []. Only in a vector, get i-th value.
* @param i
* @return const_reference.
*/
template <std::size_t NN = N,
typename = Enable_if<NN == 1>>
const T&
operator[] (std::size_t i) const
{ return this->operator()(i); }
/**
* @brief operator []. Only in a vector, get i-th value.
* @param i
* @return reference.
*/
template <std::size_t NN = N,
typename = Enable_if<NN == 1>>
T&
operator[] (std::size_t i)
{ return this->operator()(i); }
/**
* @brief apply. Apply the predicate F
* to all value of N-dimensional structure.
* Applyied to all specializations.
* @param f
* @return this.
*/
template<typename F>
Tensor_ref<T, N>&
apply(F f)
{
for (auto x = begin(); x != end(); ++x)
f(*x);
return *this;
}
/**
* @brief operator =. Assign b to a.
* @param value
* @return *this
*/
Tensor_ref&
operator= (const T& value)
{ return apply([&](T& a) { a = value; }); }
/**
* @brief operator +=. Sum a and b and put in a.
* @param value
* @return *this
*/
Tensor_ref&
operator+= (const T& value)
{ return apply([&](T& a) { a += value; }); }
/**
* @brief operator -=. Subtract a and b and put in a.
* @param value
* @return *this
*/
Tensor_ref&
operator-= (const T& value)
{ return apply([&](T& a) { a -= value; }); }
/**
* @brief operator *=. Multiplicate a and b and put in a.
* @param value
* @return *this
*/
Tensor_ref&
operator*= (const T& value)
{ return apply([&](T& a) { a *= value; }); }
/**
* @brief operator /=. Divide a and b and put in a.
* @param value
* @return *this
*/
Tensor_ref&
operator/= (const T& value)
{ return apply([&](T& a) { a /= value; }); }
/**
* @brief operator %=. Module a and b and put
* in a. Just for integers.
* @param value
* @return *this
*/
Tensor_ref&
operator%= (const T& value)
{ return apply([&](T& a) { a %= value; }); }
/**
* @brief apply. For each element, apply the
* predicate f, using values of another
* tensor.
* @param f
* @param value
* @return *this.
*/
template <typename F, typename M>
Enable_if<_tensor_type<M>(), Tensor_ref&>
apply(F f, M& m)
{
assert(this->_desc.extents == m.descriptor().extents);
for (auto i = begin(), j = m.cbegin(); i != end(); ++i, ++j)
f(*i, *j);
return *this;
}
/**
* @brief operator +=. Add tensor b to a
* and put result to a.
* @param b
* @return this.
*/
template <typename M>
Enable_if<_tensor_type<M>(), Tensor_ref&>
operator+= (const M& t)
{ return apply([&](T &a,
const typename M::value_type& b) { a += b; }, t); }
/**
* @brief operator -=. Subtract tensor b to a
* and put result to a.
* @param b
* @return this.
*/
template <typename M>
Enable_if<_tensor_type<M>(), Tensor_ref&>
operator-= (const M& t)
{ return apply([&](T& a,
const typename M::value_type& b) { a -= b; }, t); }
/**
* @brief data.
* @return a pointer to the first element
*/
T*
data()
{ return _elems; }
/**
* @brief data. (const)
* @return a pointer to the first element
*/
T*
data() const
{ return _elems; }
/// Iterators
/**
* @brief begin.
* @return iterator pointing to begin position.
*/
iterator begin()
{ return {_elems, this->_desc}; }
/**
* @brief end.
* @return iterator pointing to an element
* after end position.
*/
iterator end()
{ return {_elems, this->_desc, true}; }
/**
* @brief begin.
* @return const_iterator pointing to begin position.
*/
const_iterator cbegin() const
{ return {_elems, this->_desc}; }
/**
* @brief end.
* @return const_iterator pointing to an
* element after end position.
*/
const_iterator cend() const
{ return {_elems, this->_desc, true}; }
private:
T* _elems;
};
/// Specialization to avoid inconsistent type.
template <typename T>
class Tensor_ref<T, 0>;
/**
* @brief The Tensor_iterator class. It's like
* a input iterator.
*/
template<typename T, size_t N>
class Tensor_iterator {
public:
/// Aliases
using value_type = typename std::remove_const<T>::type;
using iterator_category = std::input_iterator_tag; /// THIS MUST BE CHANGED
using difference_type = std::ptrdiff_t;
using pointer = T*;
using reference = T&;
using const_reference = const T&;
/// Ctor.
Tensor_iterator(T* t, const Tensor_slice<N>& s, bool end = false)
: _desc{s}, _data_ptr{t}
{
std::fill(_pos.begin(), _pos.end(), 0);
if (end) {
_pos[0] = _desc.extents[0];
_data_ptr = t + _desc.flat_index(_pos);
} else
_data_ptr = t + _desc.start;
}
/**
* @brief descriptor. Get the descriptor.
* @return const reference to Tensor_slice<N>
*/
const Tensor_slice<N>&
descriptor() const
{ return _desc; }
/**
* @brief operator ++ (pre-increment). Make sequentially increment
* @return *this
*/
Tensor_iterator& operator++() {
std::size_t d = N - 1;
while (true) {
_data_ptr += _desc.strides[d];
++_pos[d];
if (_pos[d] != _desc.extents[d]) break;
if (d != 0) {
_data_ptr -= _desc.strides[d] * _desc.extents[d];
_pos[d] = 0;
--d;
} else {
break;
}
}
return *this;
}
/**
* @brief operator ++ (post-increment). Make sequentially increment
* @return *this
*/
Tensor_iterator operator++(int) {
Tensor_iterator tmp(*this);
++*this;
return tmp;
}
/**
* @brief operator *. To get the pointed-to.
* @return a reference to the element.
*/
reference
operator*()
{ return *_data_ptr; }
/**
* @brief const operator *. To get the pointed-to.
* @return a const_reference to the element.
*/
const_reference
operator*() const
{ return *_data_ptr; }
private:
/// Element indexes
std::array<std::size_t, N> _pos;
/// Reference to descriptor
const Tensor_slice<N>& _desc;
/// Pointer to flat data
T* _data_ptr;
};
///-----------------------------------------------------------------------------------------------------------///
/// Overloading operators
template <typename T, std::size_t N>
inline bool operator==(const Tensor_iterator<T, N>& a,
const Tensor_iterator<T, N>& b)
{
assert(a.descriptor() == b.descriptor());
return &*a == &*b;
}
template <typename T, std::size_t N>
inline bool operator!=(const Tensor_iterator<T, N>& a,
const Tensor_iterator<T, N>& b)
{ return !(a == b); }
///-----------------------------------------------------------------------------------------------------------///
/// Debug functions
template <typename T>
std::ostream &operator<<(std::ostream& os, const Tensor_ref<T, 2>& t) {
os << "{\n";
for (std::size_t i = 0; i < t.rows(); ++i) {
os << " { ";
for (std::size_t j = 0; j < t.cols() - 1; ++j)
os << t(i, j) << ", ";
os << t(i, t.cols() - 1) << " }\n";
}
os << "}";
return os;
}
template <typename T>
std::ostream &operator<<(std::ostream& os, const Tensor_ref<T, 1>& t) {
os << "{ ";
for (std::size_t i = 0; i < t.size() - 1; ++i)
os << t(i) << ", ";
os << t(t.size() - 1) << " }";
return os;
}
NUM_END
#endif // TENSOR_REF_H
| true |
bce3e9803a883a60d1c6c981cbf27de593e7b6dc | C++ | LeeNJU/LeetCode | /LeetCode/Shortest Distance from All Buildings.cpp | GB18030 | 2,235 | 3.203125 | 3 | [] | no_license | #include<vector>
#include<queue>
#include<algorithm>
//Ŀ:һάֵΪ1buildingֵΪ2obstacleֵͨΪ0free landҪѡһfree
// land,ʹfree landĵ㵽buildingĵḷ̌پ|x1 - x2| + |y1 - y2|
//ⷨ:ɨÿbuildingйѣdistance[i][j]ʾbuildingõľ룬reach[i][j]ʾԵõbuilding
int shortestDistance(std::vector<std::vector<int>>& grid)
{
const int row = grid.size();
if (row == 0)
return -1;
const int col = grid[0].size();
std::vector<std::vector<int>> distance(row, std::vector<int>(col, 0));//buildingڵľ
std::vector<std::vector<int>> reach(row, std::vector<int>(col, 0));//жٸbuildingԵýڵ
int building = 0, res = INT_MAX;
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < col; ++j)
{
// check from the building node, extend to all 0 node with distance
if (grid[i][j] == 1)
{
++building;
int dist = 0;
std::vector<std::vector<bool>> visited(row, std::vector<bool>(col, false));
std::queue<std::pair<int, int>> curLevel, nextLevel;
curLevel.emplace(i, j);
// bfs search for each current building
while (!curLevel.empty())
{
++dist;
while (!curLevel.empty())
{
std::pair<int, int> cur = curLevel.front();
curLevel.pop();
int x = cur.first, y = cur.second;
++reach[x][y];
std::vector<std::pair<int, int>> dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };//
for (auto dir : dirs)
{
int i = x + dir.first, j = y + dir.second;
if (i >= 0 && i < grid.size() && j >= 0 && j < grid[0].size()
&& grid[i][j] == 0 && !visited[i][j])
{
distance[i][j] += dist;
nextLevel.emplace(i, j);
visited[i][j] = true;
}
}
}
swap(curLevel, nextLevel);
}
}
}
}
for (int i = 0; i < row; i++)//ҵСֵ
{
for (int j = 0; j < col; j++)
{
if (0 == grid[i][j] && reach[i][j] == building)
res = std::min(res, distance[i][j]);
}
}
return res == INT_MAX ? -1 : res;
} | true |
acbe01c6ec9404f612bad9116aeea939588d3f6f | C++ | godcrampy/competitive | /problems/ctci/2-linked-list/2-6-palindrome/main.cpp | UTF-8 | 2,118 | 3.609375 | 4 | [] | no_license | #include <iostream>
#include <stack>
#include <unordered_set>
#include <vector>
using namespace std;
// ? Singly Linked List Boiler
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* arrayToList(const vector<int>& v) {
if (v.size() == 0) return NULL;
ListNode* dummy = new ListNode(0);
ListNode* itr = dummy;
for (int n : v) {
itr->next = new ListNode(n);
itr = itr->next;
}
return dummy->next;
}
void printList(ListNode* head) {
while (head != NULL) {
cout << head->val << " ";
head = head->next;
}
cout << endl;
}
// ? End of Single Linked List Boiler
ListNode* copyList(ListNode* a) {
ListNode* d = new ListNode(0);
ListNode* res = d;
while (a != NULL) {
d->next = new ListNode(a->val);
a = a->next;
d = d->next;
}
return res->next;
}
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) return head;
ListNode* a = head;
ListNode* b = head->next;
ListNode* c = b->next;
head->next = NULL;
while (c != NULL) {
b->next = a;
a = b;
b = c;
c = c->next;
}
b->next = a;
return b;
}
bool isPalindromeRev(ListNode* a) {
auto b = reverseList(copyList(a));
while (a != NULL || b != NULL) {
if (a == NULL || b == NULL) {
return false;
}
if (a->val != b->val) {
return false;
}
a = a->next;
b = b->next;
}
return true;
}
bool isPalindromeStack(ListNode* a) {
if (a == NULL || a->next == NULL) {
return true;
}
stack<int> stk;
ListNode* s = a;
ListNode* f = a->next;
while (f != NULL && f->next != NULL) {
stk.push(s->val);
s = s->next;
f = f->next->next;
}
if (f == NULL)
s = s->next;
else {
stk.push(s->val);
s = s->next;
}
while (!stk.empty() && s != NULL) {
int t = stk.top();
stk.pop();
if (t != s->val) return false;
s = s->next;
}
return stk.empty() && s == NULL;
}
int main(int argc, char const* argv[]) {
vector<int> v = {1, 2, 6, 5, 2, 1};
auto a = arrayToList(v);
cout << isPalindromeStack(a) << endl;
return 0;
}
| true |
bd4a3e3cc5155cb370d4dc9e2e9d0ca0006c67ff | C++ | OUC-MYM/Summer-training | /8-20/B.cpp | UTF-8 | 1,273 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <map>
#include <queue>
#include <stack>
#include <vector>
#include <set>
#define PI 3.1415926
#define INF 1<<30
using namespace std;
int N,M;
int fa_a[10010],fa_b[10010];
int find_a(int x)
{
if(fa_a[x]==1)
return 1;
if(x!=fa_a[x])
fa_a[x]=find_a(fa_a[x]);
return fa_a[x];
}
int find_b(int x)
{
if(fa_b[x]==1)
return 1;
if(x!=fa_b[x])
fa_b[x]=find_b(fa_b[x]);
return fa_b[x];
}
void link(int x,int y)
{
if(x!=1)
fa_a[x]=find_a(y);
if(y!=1)
fa_b[y]=find_b(x);
}
int main()
{
cin.sync_with_stdio(false);
while(cin >> N >> M && (N||M))
{
for(int i=1; i<=N; i++)
fa_a[i]=fa_b[i]=i;
while(M--)
{
int a,b;
cin >> a >> b;
link(a,b);
}
int flag=0;
for(int i=1; i<=N; i++)
if(find_a(i)!=1)
{
flag=1;
break;
}
for(int i=1; i<=N; i++)
if(find_b(i)!=1)
{
flag=1;
break;
}
cout << (flag?("No"):("Yes")) << endl;
}
return 0;
}
| true |
c1718526791cebf3dbbf275147d1bd85acf2dec4 | C++ | lollix91/robby-robot | /codiceArduino/sensori.ino | UTF-8 | 1,484 | 2.578125 | 3 | [] | no_license | #define FILTER_MOVING_NEW 0.8
#define FILTER_MOVING_OLD (1 - FILTER_MOVING_NEW)
#define FILTER_STAYING_NEW 0.2
#define FILTER_STAYING_OLD (1 - FILTER_STAYING_NEW)
void senseDistance(bool staying) {
// legge misura distanza
int actual = Sensori.distance;
if (!staying) {
Sensori.distance = (DistanceSensor.ping_cm() * FILTER_MOVING_NEW) + (actual * FILTER_MOVING_OLD);
}
else {
Sensori.distance = (DistanceSensor.ping_cm() * FILTER_STAYING_NEW) + (actual * FILTER_STAYING_OLD);
}
}
void senseTemperature(bool staying) {
// leggi misura temperatura
float actual = Sensori.temp;
if (!staying) {
Sensori.temp = (mpu6050.getTemp() * FILTER_MOVING_NEW) + (actual * FILTER_MOVING_OLD);
}
else {
Sensori.temp = (mpu6050.getTemp() * FILTER_STAYING_NEW) + (actual * FILTER_STAYING_OLD);
}
}
void mapDistance(int angle) {
// invia distanza su seriale
// dist=<valore>
Serial.print("dist=");
Serial.println(Sensori.distance);
// invia angolo direzione
// headdeg=<valore>
Serial.print("headdeg=");
Serial.println(angle);
}
void mapTemperature(int angle) {
// scala le ultime <numero> misurazioni
// aggiungi in testa la nuova misura
// invia la misura su seriale
// temp=<valore>
Serial.print("temp=");
Serial.println(Sensori.temp);
// invia l'angolo della direzione seguita
// dirdeg=<valore>
Serial.print("dirdeg=");
Serial.println(angle);
}
| true |
a27fc62a66202548f40f712333bcf6fba89b95e5 | C++ | salipshitz/Reyes | /Reyes/src/Reyes/Core/LayerStack.cpp | UTF-8 | 640 | 2.734375 | 3 | [] | no_license | #include "LayerStack.h"
namespace Reyes {
void LayerStack::PushLayer(Layer *layer) {
m_Layers.emplace(m_Layers.begin() + m_LayerInsertIndex++, layer);
layer->OnAttach();
}
void LayerStack::PushOverlay(Layer *overlay) {
m_Layers.emplace_back(overlay);
overlay->OnAttach();
}
void LayerStack::PopLayer(Layer *layer) {
auto it = std::find(begin(), end(), layer);
if (it != end()) {
m_Layers.erase(it);
m_LayerInsertIndex--;
}
layer->OnDetach();
}
void LayerStack::PopOverlay(Layer *overlay) {
auto it = std::find(begin(), end(), overlay);
if (it != end())
m_Layers.erase(it);
overlay->OnDetach();
}
} | true |
cabe69f2ee9ce7edc009f8e895d14b8ad145c349 | C++ | mbilalakmal/shoAIb | /Lecture.hpp | UTF-8 | 1,755 | 3.265625 | 3 | [
"MIT"
] | permissive | #ifndef LECTURE
#define LECTURE
#include <string> //string
#include <vector> //vector
#include <unordered_map> //unordered_map
#include "json.hpp" //nlohmann::json
typedef std::vector<std::vector<bool>> AVAILABOOL;
/*
Describes a lecture : a course, teacher(s), and section(s)
*/
class Lecture{
//creates C++ Lecture object from json Lecture object
friend void from_json(const nlohmann::json&, Lecture&);
public:
const std::string& getId() const {return id;}
int getStrength() const {return strength;}
const std::string& getCourse() const {return course;}
const std::vector<std::string>& getTeachers() const {return teachers;}
const std::vector<std::string>& getSections() const {return sections;}
const AVAILABOOL& getAvailableSlots() const {return availableSlots;}
const std::vector<std::string>& getAvailableRooms() const {return availableRooms;}
void setAvailableSlots(AVAILABOOL availableSlots){this->availableSlots = availableSlots;}
void setAvailableRooms(std::vector<std::string> availableRooms){this->availableRooms = availableRooms;}
private:
std::string id;
int strength;
std::string course;
std::vector<std::string> teachers;
std::vector<std::string> sections;
AVAILABOOL availableSlots;
std::vector<std::string> availableRooms;
};
void from_json(const nlohmann::json& jlecture, Lecture& lecture) {
jlecture.at("id").get_to(lecture.id);
jlecture.at("strength").get_to(lecture.strength);
jlecture.at("courseId").get_to(lecture.course);
jlecture.at("teacherIds").get_to(lecture.teachers);
jlecture.at("sectionIds").get_to(lecture.sections);
}
#endif | true |
e30cd76c20450f9dab74b6639c7b388652693c32 | C++ | qilip/ACMStudy | /baekjoon/11758/source.cpp | UTF-8 | 440 | 3.109375 | 3 | [
"CC-BY-4.0",
"CC-BY-3.0"
] | permissive | #include <stdio.h>
struct point{
int x, y;
point operator- (const point &o) const{
return {x - o.x, y - o.y};
}
};
int ccw(point a, point b, point c){
b = b - a;
c = c - a;
return b.x*c.y - c.x*b.y;
}
int main(void){
point p[3];
for(int i=0;i<3;i++)
scanf("%d %d", &p[i].x, &p[i].y);
int ans = ccw(p[0], p[1], p[2]);
printf("%d", ans > 0 ? 1 : (ans < 0 ? -1 : 0));
return 0;
}
| true |
7fb6a1876b5cbe88e51a8171caccc01bd24161c6 | C++ | banyi97/Prog2 | /Source.cpp | UTF-8 | 2,659 | 3.375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include "GraphStorage.hpp"
template<class T>
class BFS
{
private:
Graph<T> *place1;
Graph<T> *place2;
int _level;
std::vector<std::vector<Graph<T>*>*> *listOfGraph;
public:
BFS(GraphStorage<T> *p, T& place1, T& place2) : _level(0), listOfGraph(new std::vector<std::vector<Graph<T>*>*>())
{
int num1 = p->findElemenet(place1);
int num2 = p->findElemenet(place2);
if (num1 == -1 || num2 == -1)
throw "Place of exceptions";
std::vector<Graph<T>*> *storagep = p->getStorage();
this->place1 = (*storagep)[num1];
this->place2 = (*storagep)[num2];
auto *graph = new std::vector<Graph<T>*>();
graph->push_back(this->place1);
listOfGraph->push_back(graph);
std::cout << "BFS const" << std::endl;
}
~BFS()
{
reset();
delete listOfGraph;
std::cout << "BFS dest" << std::endl;
}
int run()
{
for (int i = 0; i < listOfGraph->size(); ++i)
{
std::vector<Graph<T>*> *p = (*listOfGraph)[i];
for(int j = 0; j < p->size(); ++j)
{
Graph<T> *graphp = (*p)[j];
if (*place2 == *graphp)
return i;
}
}
throw "Exceptions";
}
void sortGraph()
{
std::vector<Graph<T>*> *p = (*listOfGraph)[_level];
auto *actual = new std::vector<Graph<T>*>();
int newElement = 0;
for (int i = 0; i < p->size(); ++i)
{
Graph<T> *graphp = (*p)[i];
std::vector<Graph<T>*> *qlistp = graphp->getNextPoints();
for (int j = 0; j < qlistp->size(); ++j)
{
Graph<T> *p_graph = (*qlistp)[j];
if (!(elementListOfGraph(p_graph)))
{
actual->push_back(p_graph);
++newElement;
}
}
}
listOfGraph->push_back(actual);
++_level;
if (newElement > 0)
sortGraph();
}
bool elementListOfGraph(Graph<T> *point)
{
for(int i = 0; i < listOfGraph->size(); ++i)
{
std::vector<Graph<T>*> *p = (*listOfGraph)[i];
for(int j = 0; j < p->size(); ++j)
{
Graph<T> *graphp = (*p)[j];
if ((*point) == (*graphp))
return true;
}
}
return false;
}
void reset()
{
_level = 0;
int max = listOfGraph->size();
for(int i = 0; i < max; ++i)
{
std::vector<Graph<T>*> *p = (*listOfGraph)[i];
delete p;
}
}
};
int main()
{
auto *graphstorege = new GraphStorage<std::string>();
graphstorege->fileRead("Text.txt");
std::string a, b;
a = "Budapest";
b = "Kecskemet";
auto *bfs = new BFS<std::string>(graphstorege, a, b);
std::cout << "Sorted #############" << std::endl;
bfs->sortGraph();
int run = bfs->run();
std::cout << "#################" << std::endl << run << std::endl << "################" << std::endl;
delete bfs;
delete graphstorege;
int q;
std::cin >> q;
return 0;
}
| true |
6a24ccb9deeb0eab5f3df24c94d0a8118b3a730d | C++ | Lehm2000/OpenGLSuperBible | /SuperBibleExamples/src/GEControllerInputMousePositionX.h | UTF-8 | 5,367 | 2.890625 | 3 | [] | no_license | #ifndef GECONTROLLERINPUTMOUSEPOSITIONX_H
#define GECONTROLLERINPUTMOUSEPOSITIONX_H
/**
GEControllerInputMousePosition
Purpose: GEController that monitors the X position of the mouse and applies the deltaVec as a multiple of the offset.
Author: Jeff Adams
*/
#include <glm\glm.hpp>
#include "GEControllerConstant.h"
#include "InputStateHolder.h"
#include "TypeDefinitions.h"
template <class T>
class GEControllerInputMousePositionX: public GEControllerConstant<T>
{
private:
float mousePositionX; // where is the mouse
float mousePositionXPrev; // where was the mouse
public:
GEControllerInputMousePositionX();
GEControllerInputMousePositionX( const T valueDelta );
GEControllerInputMousePositionX( const GEControllerInputMousePositionX<T>& source );
virtual ~GEControllerInputMousePositionX();
// Setters
// virtual void setGameEntities( const GEObjectContainer* gameEntities ); // override from GEController
// Functions
/**
clone()
Returns a pointer to a copy of itself. Used when you need a copy of a
derived class and only have a pointer to the base class.
@return - pointer to a copy of this object
*/
virtual GEControllerInputMousePositionX<T>* clone() const;
/**
Update()
Takes objectVector and applies the deltaVec to it if this objects key is pressed.
@param startVector - starting point of the object. Could be position, rotation or scale
@param gameTime - time since the game started
@param deltaTime - time since the last frame
@return
*/
virtual T Control( const GEObject* parent, const GEObjectContainer* gameEntities, const T prevValue, const double gameTime, const double deltaTime, T max, bool useMax, T min, bool useMin );
/**
CalcTransform()
Takes a source vector and combines it with the transformedVector
@param sourceVector - vector to be combined with the controllers transformedVector.
Usually the objects original transform.
*/
virtual T CalcTransform( const T sourceValue );
/**
ProcessInput
Function for processing input from the user. Meant to be stored in the inputFunction list as a pointer.
*/
virtual void ProcessInput( const GEInputState* inputState );
};
// Structors
template <class T>
GEControllerInputMousePositionX<T>::GEControllerInputMousePositionX()
:GEControllerConstant<T>()
{
this->mousePositionX = 0.0f;
this->mousePositionXPrev = 0.0f;
}
template <class T>
GEControllerInputMousePositionX<T>::GEControllerInputMousePositionX( const T valueDelta )
:GEControllerConstant<T>( valueDelta )
{
this->mousePositionX = 0.0f;
this->mousePositionXPrev = 0.0f;
}
template <class T>
GEControllerInputMousePositionX<T>::GEControllerInputMousePositionX( const GEControllerInputMousePositionX<T>& source )
:GEControllerConstant<T>( source.valueDelta )
{
this->mousePositionX = source.mousePositionX;
this->mousePositionXPrev = source.mousePositionXPrev;
}
// Setters
/*
template <class T>
void GEControllerInputMousePositionX<T>::setGameEntities( const GEObjectContainer* gameEntities )
{
// Overloaded from GEController so that this controller grabs the current mouse position from SYS_Input_State
this->gameEntities = gameEntities;
// once the gameEntities is set... now we can get the mouse position from the input state object.
const GEObject* isObject = gameEntities->GetObject( "SYS_Input_State" );
if ( isObject != nullptr )
{
const InputStateHolder* inputStateHolder = (InputStateHolder*)isObject;
const GEInputState* inputState = inputStateHolder->getInputState();
this->mousePositionX = inputState->getMousePosition().x;
this->mousePositionXPrev = this->mousePositionX;
}
}
*/
// Functions
template <class T>
GEControllerInputMousePositionX<T>::~GEControllerInputMousePositionX()
{
}
template <class T>
GEControllerInputMousePositionX<T>* GEControllerInputMousePositionX<T>::clone() const
{
return new GEControllerInputMousePositionX<T>( *this );
}
template <class T>
T GEControllerInputMousePositionX<T>::Control( const GEObject* parent, const GEObjectContainer* gameEntities, const T prevValue, const double gameTime, const double deltaTime, T max, bool useMax, T min, bool useMin )
{
// find the change
float mousePosXDelta = this->mousePositionX - this->mousePositionXPrev;
// apply the change. x = y rotation, y = x rotation
transformedValue += valueDelta * mousePosXDelta;
transformedValue = ValidateRange( transformedValue, prevValue, max, useMax, min, useMin );
return transformedValue + prevValue;
}
template <class T>
T GEControllerInputMousePositionX<T>::CalcTransform( T sourceValue )
{
return sourceValue + transformedValue;
}
template <class T>
void GEControllerInputMousePositionX<T>::ProcessInput( const GEInputState* inputState )
{
if( inputState->getMouseMode() == GE_MOUSEMODE_LOOK )
{
//this->mousePositionXPrev = this->mousePositionX;
this->mousePositionXPrev = inputState->getMousePositionPrev().x;
this->mousePositionX = inputState->getMousePosition().x;
}
else
{
this->mousePositionXPrev = this->mousePositionX = inputState->getMousePosition().x;
}
}
typedef GEControllerInputMousePositionX<float> GEControllerInputMousePositionXf1;
typedef GEControllerInputMousePositionX<GEvec2> GEControllerInputMousePositionXv2;
typedef GEControllerInputMousePositionX<GEvec3> GEControllerInputMousePositionXv3;
#endif /* GECONTROLLERINPUTMOUSEPOSITIONX_H */ | true |
9b58ddb8db739ef3a72884cdc9792f06449cd059 | C++ | sheric98/minimax_player | /minimax.h | UTF-8 | 1,040 | 2.609375 | 3 | [] | no_license | #ifndef MINIMAX_H
#define MINIMAX_H
#include "wrap.h"
#include <future>
#include <mutex>
#include <optional>
#include <string>
#include <tuple>
#include <unordered_map>
typedef std::tuple<std::string, unsigned> MMKey;
struct MMKeyHash : public std::unary_function<MMKey, std::size_t>
{
std::size_t operator()(const MMKey &k) const
{
return std::hash<std::string>{}(std::get<0>(k)) ^ std::get<1>(k);
}
};
struct MMKeyEqual : public std::binary_function<MMKey, MMKey, bool>
{
bool operator()(const MMKey &v0, const MMKey &v1) const
{
return (std::get<0>(v0) == std::get<0>(v1) && std::get<1>(v0) == std::get<1>(v1));
}
};
class MiniMax
{
public:
unsigned depth;
game::Move *nextMove(game::Wrapper *wrap);
std::optional<int> findGame(MMKey &key);
void insertScore(MMKey &key, int score);
MiniMax(unsigned depth);
private:
std::mutex tableLock;
std::unordered_map<MMKey, int, MMKeyHash, MMKeyEqual> transTable;
};
#endif | true |
845e811a2680cbf3441a04062c7e4ea2629710a6 | C++ | google-code/atp-algo-197 | /StudentWorks/Farafonov_Gennadiy/Azv.cpp | UTF-8 | 2,568 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <algorithm>
#include <cstring>
#include <vector>
#include <set>
#include <map>
#include <bitset>
#include <queue>
#include <complex>
#include <cassert>
using namespace std;
const int inf = int(1e9);
struct point {
int x, y;
};
class Graph {
public:
vector <point> p;
vector <vector <int> > g;
Graph() {}
Graph(vector <point> points, vector <pair <int, int> > e) {
p = points;
g.resize((int)p.size());
for (int i = 0; i < (int)p.size(); i++) {
g[i].clear();
}
for (int i = 0; i < (int)e.size(); i++) {
g[e[i].first].push_back(e[i].second);
g[e[i].second].push_back(e[i].first);
}
}
int get_vertices() {
return (int)g.size();
}
pair <int, vector <int> :: iterator> get_iterator(int v) {
return make_pair(v, g[v].begin());
}
bool valid(pair <int, vector <int> :: iterator> it){
return it.second != g[it.first].end();
}
pair <int, vector <int> :: iterator> next(pair <int, vector <int> :: iterator> it){
return make_pair(it.first, it.second + 1);
}
};
double dist(point a, point b) {
return sqrt((double)(a.x - b.x) * (a.x - b.x) + (double)(a.y - b.y) * (a.y - b.y));
}
double A(Graph g, int v, int u) {
vector <double> d;
d.assign(g.get_vertices(), inf);
set <pair <double, int> > s;
vector <double> h;
h.resize(g.get_vertices());
for (int i = 0; i < (int)h.size(); i++) {
h[i] = dist(g.p[i], g.p[u]);
}
d[v] = 0;
s.insert(make_pair(d[v] + h[v], v));
while (!s.empty()) {
pair <double, int> cur = *(s.begin());
s.erase(s.begin());
if (cur.second == u) {
return d[u];
}
pair <int, vector <int> :: iterator> e = g.get_iterator(cur.second);
while (g.valid(e)) {
if (d[cur.second] + dist(g.p[cur.second], g.p[*(e.second)]) < d[*(e.second)]) {
s.erase(make_pair(d[*(e.second)] + h[*(e.second)], *(e.second)));
d[*(e.second)] = d[cur.second] + dist(g.p[cur.second], g.p[*(e.second)]);
s.insert(make_pair(d[*(e.second)] + h[*(e.second)], *(e.second)));
}
e = g.next(e);
}
}
return -1;
}
int main() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int n, m;
scanf("%d %d", &n, &m);
vector <point> points;
for (int i = 0; i < n; i++) {
point cur;
scanf("%d %d", &cur.x, &cur.y);
points.push_back(cur);
}
vector <pair <int, int> > edges;
for (int i = 0; i < m; i++) {
int a, b;
scanf("%d %d", &a, &b);
a--;
b--;
edges.push_back(make_pair(a, b));
}
Graph g(points, edges);
printf("%.18lf\n", A(g, 0, n - 1));
return 0;
}
| true |
b0bd2a1ee818f915e1aaf292b3a0981b51e0d7b0 | C++ | scottjomartin/raspberrypi | /drivers/GPIO.cpp | UTF-8 | 3,045 | 2.984375 | 3 | [] | no_license | /*
* GPIO.cpp
*
* Created on: 17/09/2016
* Author: scottm
*/
#include <string>
#include <fstream>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include "../os/PI.h"
#include "GPIO.h"
using namespace std;
const char * GPIO::exportFileName_ = "/sys/class/gpio/export";
const char * GPIO::unexportFileName_ = "/sys/class/gpio/unexport";
const char * GPIO::gpioName_ = "/sys/class/gpio/gpio";
const char * GPIO::directionName_ = "/direction";
const char * GPIO::valueName_ = "/value";
GPIO::GPIO (unsigned pin,
Direction dir)
: pin_(pin),
direction_(dir),
exported_(false)
{
if (pin > 26)
{
PI_LOG(true, "Invalid pin %d", pin);
return;
}
// Export pin
ofstream file(exportFileName_);
if (file < 0)
{
PI_LOG(true, "Failed to open export file '%s'", exportFileName_);
return;
}
// Set the direction for the pin
file << pin;
file.flush();
file.close();
PI::sleep(100);
stringstream ss;
ss << gpioName_ << pin << directionName_;
string fname = ss.str();
file.open(fname.c_str());
if (file < 0)
{
PI_LOG(true, "Failed to open file %s", fname.c_str());
return;
}
switch (dir)
{
case INPUT:
PI_LOG(false, "Setting pin %d to input (%s)", pin, fname.c_str());
file << "in";
break;
case OUTPUT:
PI_LOG(false, "Setting pin %d to output (%s)", pin, fname.c_str());
file << "out";
break;
}
file.flush();
file.close();
PI::sleep(100);
exported_ = true;
}
GPIO::~GPIO ()
{
if (exported_)
{
ofstream file(unexportFileName_);
if (file < 0)
{
PI_LOG(true, "Failed to open unexport file '%s'", unexportFileName_);
return;
}
file << pin_;
file.close();
}
}
bool
GPIO::read()
{
stringstream ss;
ss << gpioName_ << pin_ << valueName_;
string fname = ss.str();
ifstream file(fname.c_str());
if (file < 0)
{
PI_LOG(true, "Failed to open input file %s", fname.c_str());
return (false);
}
string value;
file >> value;
file.close();
int intVal = atoi(value.c_str());
return (intVal > 0);
}
void
GPIO::write(bool value)
{
stringstream ss;
ss << gpioName_ << pin_ << valueName_;
string fname = ss.str();
ofstream file(fname.c_str());
if (file < 0)
{
PI_LOG(true, "Failed to open input file %s", fname.c_str());
return;
}
string valStr = value ? "1" : "0";
file << valStr.c_str();
file.close();
}
void
GPIO::write(unsigned long frequency,
unsigned long duration)
{
unsigned long delay = frequency == 0 ? 0 : 1000000 / frequency / 2;
unsigned long cycles = frequency * duration / 1000;
for (unsigned long i = 0; i < cycles; ++i)
{
write(true);
usleep(delay);
write(false);
usleep(delay);
}
}
| true |
6d147bf080cc82b6c1a99f331e7faa31e9eb4bd9 | C++ | Hoonly/PAT- | /A1075【PAT_Judge】.cpp | GB18030 | 3,998 | 3.109375 | 3 | [] | no_license | #include<iostream>
#include<string.h>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<iterator>
#include<map>
using namespace std;
struct personal
{
int score[6];//ÿĵ÷-1δͨ룬-2δύעȫʼΪ-2
int total_score;//ܷ
int perfectly_solved;//ֵĿ
bool flag;//Ƿͨ⣬ûеϼ
};
struct handle
{
int rank;
int user_id;
int score[6];//ÿĵ÷-1δͨ룬-2δύעȫʼΪ-2
int total_score;//ܷ
int perfectly_solved;//ֵĿ
};
bool cmp(handle a,handle b)
{
if(a.total_score!=b.total_score)
return a.total_score>b.total_score;
else if(a.perfectly_solved!=b.perfectly_solved)
return a.perfectly_solved>b.perfectly_solved;
else
return a.user_id<b.user_id;
}
int main()
{
int N;//ܵû
int K;//ܵ
int M;//ܵύ
scanf("%d%d%d",&N,&K,&M);
int full_mark[6]={0};//ÿķֵܹ5
for(int i=1;i<=K;i++)
{
scanf("%d",&full_mark[i]);
}
map<int,personal> m;//ѧ-ύӳ
//Mύ¼
for(int i=0;i<M;i++)
{
int user_id,problem_id,part_score;
scanf("%d %d %d",&user_id,&problem_id,&part_score);
if(m.count(user_id)==0)//ûûύ¼
{
personal p;
//memset(p.score,-2,sizeof(p.score));
fill(p.score,p.score+6,-2);
p.score[problem_id]=part_score;
p.flag=false;//ÿû״ύĿʱȰflagΪfalse
if(part_score!=-1)//ֻҪͨģͰflagtrue
p.flag=true;
pair<int,personal> pa;
pa.first=user_id;
pa.second=p;
m.insert(pa);
}
else
{
if(part_score!=-1)
m[user_id].flag=true;
//ͬһĿύȡ߷
int prev=m[user_id].score[problem_id];
if(part_score>prev)
m[user_id].score[problem_id]=part_score;
}
}
//ύûһɾ
for(int i=1;i<N;i++)
{
if(m.count(i))
{
if(!m[i].flag)
{
map<int,personal>::iterator it=m.find(i);
m.erase(it);
}
}
}
vector<handle> v;
for(map<int,personal>::iterator i=m.begin();i!=m.end();++i)
{
handle h;
h.perfectly_solved=0;
h.total_score=0;
h.user_id=i->first;
for(int j=0;j<6;j++)
{
h.score[j]=i->second.score[j];
if(h.score[j]==full_mark[j])
h.perfectly_solved++;
}
for(int j=1;j<=K;j++)
{
if(h.score[j]>=0)
h.total_score+=h.score[j];
}
v.push_back(h);
}
sort(v.begin(),v.end(),cmp);
v[0].rank=1;
for(int i=1;i<v.size();i++)
{
if(v[i].total_score==v[i-1].total_score)
v[i].rank=v[i-1].rank;
else
v[i].rank=i+1;
}
for(int i=0;i<v.size();i++)
{
printf("%d %05d %d ",v[i].rank,v[i].user_id,v[i].total_score);
for(int j=1;j<=K;j++)
{
if(v[i].score[j]==-1)
printf("0");
else if(v[i].score[j]==-2)
printf("-");
else
printf("%d",v[i].score[j]);
if(j!=K)
printf(" ");
}
if(i!=v.size())
printf("\n");
}
return 0;
}
| true |
1f74274ad4e0fa593336aa1bc0ee371461fcfed3 | C++ | rbaygildin/algorithms-cpp | /PointArray/main.cpp | UTF-8 | 3,034 | 3.390625 | 3 | [] | no_license | #include <assert.h>
#include <iostream> // cout
#include "geometry.h"
using namespace std;
// ============== test for Point ======================
void testDefaultPointArrayConstructor(){
PointArray pointArray;
assert(pointArray.getSize() == 0);
}
void testCopyPointArrayConstructor(){
Point points[10];
for(int i = 0; i < 10; i++){
points->setX(i);
points->setY(2 * i);
}
PointArray pointArray(points, 10);
assert(pointArray.getSize() == 10);
for(int i = 0; i < 10; i++){
assert(pointArray.get(i)->getX() == points[i].getX());
assert(pointArray.get(i)->getY() == points[i].getY());
}
}
void testPushBack(){
PointArray pointArray;
for(int i = 0; i < 10; i++)
pointArray.push_back(Point(i, 2 * i));
assert(pointArray.getSize() == 10);
for(int i = 0; i < 10; i++) {
assert(pointArray.get(i)->getX() == i);
assert(pointArray.get(i)->getY() == 2 * i);
}
}
void testInsert(){
PointArray pointArray;
for(int i = 0; i < 10; i++)
pointArray.push_back(Point(i, i));
pointArray.insert(0, Point(-1, 0));
assert(pointArray.get(0)->getX() == -1);
assert(pointArray.get(0)->getY() == 0);
for(int i = 1; i < pointArray.getSize(); i++){
assert(pointArray.get(i)->getX() == (i - 1));
assert(pointArray.get(i)->getY() == (i - 1));
}
pointArray.insert(5, Point(20, -20));
assert(pointArray.get(5)->getX() == 20);
assert(pointArray.get(5)->getY() == -20);
for(int i = 6; i < pointArray.getSize(); i++){
assert(pointArray.get(i)->getX() == i - 2);
assert(pointArray.get(i)->getY() == i - 2);
}
pointArray.insert(pointArray.getSize() - 1, Point(-2, -2));
assert(pointArray.get(pointArray.getSize() - 1)->getX() == 9);
assert(pointArray.get(pointArray.getSize() - 1)->getY() == 9);
}
void testRemove(){
PointArray pointArray;
pointArray.push_back(Point(1, 1));
pointArray.push_back(Point(2, 2));
pointArray.push_back(Point(3, 3));
pointArray.push_back(Point(4, 4));
assert(pointArray.getSize() == 4);
pointArray.remove(2);
assert(pointArray.getSize() == 3);
assert(pointArray.get(2)->getX() == 4);
assert(pointArray.get(2)->getY() == 4);
}
void testClear(){
PointArray pointArray;
pointArray.push_back(Point(1, 1));
pointArray.push_back(Point(2, 2));
pointArray.push_back(Point(3, 3));
pointArray.push_back(Point(4, 4));
pointArray.clear();
assert(pointArray.getSize() == 0);
}
void testCopyConstructor(){
PointArray pa1;
pa1.push_back(Point(1, 1));
pa1.push_back(Point(2, 2));
PointArray pa2(pa1);
assert(pa2.getSize() == pa1.getSize());
assert(pa2.get(0)->getX() == 1);
assert(pa2.get(0)->getY() == 1);
}
int main(int argc, char** argv) {
testDefaultPointArrayConstructor();
testCopyPointArrayConstructor();
testPushBack();
testInsert();
testRemove();
testClear();
testCopyConstructor();
return EXIT_SUCCESS;
}
| true |
0908902e365fc4e9422a8b54ef8f844684a32146 | C++ | Kawser-nerd/CLCDSA | /Source Codes/AtCoder/arc090/A/2028060.cpp | UTF-8 | 1,266 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <utility>
#include <sys/time.h>
#include <cmath>
#include <tuple>
#include <queue>
#include <bitset>
using namespace std;
void solve(int n, vector<long long> a1, vector<long long> a2) {
long long ret = 0;
for (int i = 0; i < n; i++) {
long long s1 = 0;
for (int j = 0; j < i+1; j++) {
s1 += a1[j];
}
long long s2 = 0;
for (int j = n-1; j > i-1; j--) {
s2 += a2[j];
}
if (ret < s1+s2) {
ret = s1+s2;
}
}
std::cout << ret << std::endl;
}
int main() {
struct timeval start,end;
long long span;
int n;
gettimeofday(&start,NULL);
std::cin >> n;
vector<long long> a1(n);
vector<long long> a2(n);
for (int i = 0; i < n; i++) {
std::cin >> a1[i];
}
for (int i = 0; i < n; i++) {
std::cin >> a2[i];
}
solve(n, a1, a2);
gettimeofday(&end,NULL);
span = (end.tv_sec -start.tv_sec)*1000000LL + (end.tv_usec - start.tv_usec);
std::cerr << "--Total Time: " << span/1000 << "ms" << endl;
return 0;
} | true |
24960571b43d3a1b3a9c7d20f8c6ae998adece96 | C++ | monteiroricardo/Documentos_FATEC | /Algoritmos/Aula 8 - While-DoWhile/ExercícioExemplo02.cpp | ISO-8859-1 | 348 | 2.734375 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
#include <locale.h>
main(){
int n,qp=0,qi=0,sp=0;
setlocale(LC_ALL,"");
do{
printf("Valor: ");
scanf("%i",&n);
if(n%2==0){
sp+=n;
qp++;
} else
qi++;
}while(n!=0);
printf("\nQuantidade de pares: %i",--qp);
printf("\nQuantidade de mpares: %i",qi);
printf("\nMdia dos pares: %.2f\n",(float)sp/qp);
}
| true |
4c1fbfdb5b32c0b3e0b8b393c1d505434c7d0167 | C++ | trett/Renju | /src/controller.cpp | UTF-8 | 1,993 | 2.828125 | 3 | [
"MIT"
] | permissive | #include "controller.h"
#include <QtConcurrent/QtConcurrentRun>
Controller::Controller(QObject *parent) : QObject(parent), m_parent(parent)
{
}
void Controller::initGame(const QVariant &humanChoosenColor)
{
debug("Init game");
m_pl_hmn = new HumanPlayer(m_parent);
m_pl_ai = new SimpleAi(m_parent);
QObject::connect(m_pl_hmn, &IPlayer::move, this, &Controller::getNextMove);
auto color = static_cast<DOT_COLOR>(humanChoosenColor.toInt());
m_pl_hmn->m_color = color;
m_pl_ai->m_color = color == WHITE ? BLACK : WHITE;
debug("Human color is", m_pl_hmn->m_color);
debug("AI color is", m_pl_ai->m_color);
// inverse for first move
if (color == BLACK) {
m_currentPlayer = m_pl_ai;
} else {
m_currentPlayer = m_pl_hmn;
}
changePlayer();
if (m_state == AI) {
getNextMove();
}
}
void Controller::getNextMove() {
if (!m_currentPlayer->m_canMove) {
return;
}
debug("Retrieving next move for", m_currentPlayer->m_color);
QtConcurrent::run([this]() {
m_nextMove = m_currentPlayer->nextMove();
Table::table[m_nextMove->y()][m_nextMove->x()] = m_currentPlayer->m_color;
Table::history.push_back(m_nextMove);
changePlayer();
emit(nextMoveChanged());
});
}
void Controller::changePlayer()
{
IPlayer *previous = m_currentPlayer;
previous->m_canMove = false;
if (m_currentPlayer == m_pl_ai) {
m_currentPlayer = m_pl_hmn;
m_state = HUMAN;
} else {
m_currentPlayer = m_pl_ai;
m_state = AI;
}
m_currentPlayer->m_canMove = true;
}
bool Controller::checkWin(Dot *dot) {
return Table::checkWin(dot);
}
void Controller::end() {
debug("End game");
Table::clear();
Table::history.clear();
m_pl_hmn->deleteLater();
m_pl_ai->deleteLater();
}
Dot *Controller::nextMove() const
{
return m_nextMove;
}
Controller::GameState Controller::state() const
{
return m_state;
}
| true |
b03675b268f5dc774a5dcb9e83900f6fa29ac771 | C++ | SunMoonStar2000/examples | /code/Qt/expandable-listwidget/widgetbox.cpp | UTF-8 | 1,020 | 2.6875 | 3 | [] | no_license | #include "widgetbox.h"
#include <QVBoxLayout>
#include <QFrame>
#include <QDebug>
WidgetBox::WidgetBox(QWidget *parent)
: QWidget(parent)
{
m_frame = new QFrame(this);
m_layout = new QVBoxLayout(m_frame);
m_layout->setContentsMargins(0, 0, 0, 0);
m_frame->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
QVBoxLayout *main_layout = new QVBoxLayout(this);
main_layout->addWidget(m_frame);
}
void WidgetBox::setWidget(QWidget *widget)
{
if (m_widget) {
m_layout->removeWidget(m_widget);
m_widget->deleteLater();
}
m_widget = widget;
m_layout->addWidget(widget, 0, Qt::AlignLeft | Qt::AlignTop);
m_widget->setFixedSize((m_frame->rect() - m_layout->contentsMargins()).size());
}
QWidget *WidgetBox::widget() const
{
return m_widget;
}
void WidgetBox::resizeEvent(QResizeEvent *event)
{
if (m_widget)
m_widget->setFixedSize((m_frame->rect() - m_layout->contentsMargins()).size());
return QWidget::resizeEvent(event);
}
| true |
c90db5c55098e3f15894f9973c78f53518a66bf4 | C++ | ARFNeto-CH/chc20-0914-menu | /Teste4-CPP/menu.cpp | UTF-8 | 5,341 | 2.5625 | 3 | [] | no_license | #include <fstream>
#include <string>
#include <vector>
#include "menu.h"
Menu::Menu()
{ // padrao
argc = 0;
argv = {};
completo = false;
dflt = 1;
opt = 1;
timeout_ms = 80;
linha = 10;
coluna = 10;
};
Menu::Menu(int argc, vector<string>& argv,
int linha, int coluna, int dflt, int opt, int timeout_ms) :
linha(linha), coluna(coluna), dflt(dflt),
opt(opt), timeout_ms(timeout_ms),
argc(argc), argv(argv)
{
completo = argv.size() > 0;
};
int Menu::carrega_do_arquivo(string arquivo)
{
// antes de tudo apaga as opcoes de antes
argv.erase( argv.begin(), argv.end() ); // apaga tudo
ifstream entrada{ arquivo };
string uma;
getline(entrada, uma);
while (!entrada.eof())
{
if (uma.length() == 0)break;
if (uma[0] != '#')
argv.push_back(" " + uma + " ");
getline(entrada, uma);
}; // while()
// le os outros parametros
getline(entrada, uma, ','); linha = stoi(uma);
getline(entrada, uma, ','); coluna = stoi(uma);
getline(entrada, uma, ','); dflt = stoi(uma);
getline(entrada, uma, ','); timeout_ms = stoi(uma);
getline(entrada, uma); opt = stoi(uma);
entrada.close();
if (argv.size() == 0) return -1;
completo = true;
argc = argv.size();
return 0;
}
int Menu::carrega_opcoes(const vector<string>& V)
{
if (V.size() < 3) return -1;
argv = V;
argc = V.size();
completo = true;
return 0;
}; // carrega_do_arquivo()
int Menu::cls()
{
CONSOLE_SCREEN_BUFFER_INFO info;
HANDLE H = GetStdHandle(STD_OUTPUT_HANDLE);
COORD origem = { 0,0 };
DWORD total;
GetConsoleScreenBufferInfo(H, &info);
int r = FillConsoleOutputCharacter(H, (TCHAR)' ',
info.dwSize.X * info.dwSize.Y,
origem, &total);
int s = FillConsoleOutputAttribute(
H, info.wAttributes,
info.dwSize.X * info.dwSize.Y,
origem, &total);
SetConsoleCursorPosition(H, origem);
return 0;
}
string Menu::getopt(int opt)
{
return argv[opt];
}
void Menu::mensagem_YX(COORD Pos, const string& msg, char opt)
{
CONSOLE_SCREEN_BUFFER_INFO info;
DWORD total = 0;
HANDLE Console = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(Console, &info);
WORD Reverso = (info.wAttributes & 0xF0) | (info.wAttributes & 0xF) << 4;
SetConsoleCursorPosition(Console, Pos);
if (opt == 0)
SetConsoleTextAttribute(Console, info.wAttributes);
else
SetConsoleTextAttribute(Console, Reverso);
int res = WriteConsoleA(Console, msg.c_str(), msg.length(), &total, NULL);
SetConsoleTextAttribute(Console, info.wAttributes); // reset
return;
}
int Menu::select()
{
#define _CLS_ 0x01
// limpa a tela
// mostra o menu inicial
// usa menu_helper para navegar
// retorna a opcao para quem chamou
if (argc == 0) return -1;
if (argv.size() == 0) return -2;
char clear = opt & _CLS_;
if ( clear ) cls();
COORD Pos{ (SHORT)coluna, (SHORT)linha };
int res = 0;
mensagem_YX(Pos, argv[0], 1); // O titulo
Pos.Y += 2; // vai mostrar as opcoes
for (int i = 1; i < argc; i += 1, Pos.Y += 1)
mensagem_YX(Pos, argv[i], (i == dflt));
// navega
int opt = dflt; // a opcao selecionada
Pos.Y = linha + dflt + 1;
while ((res = helper()) != 'R')
{
if (res == 'E')
{
if ( clear ) cls();
return -1;
};
// vai mudar a opcao
mensagem_YX(Pos, argv[opt], 0);
if (res == '+') opt = (opt >= argc - 1) ? 1 : opt + 1;
else
if (res == '-') opt = (opt < 2) ? argc - 1 : opt - 1;
else
if (res == '0') opt = dflt;
Pos.Y = linha + opt + 1;
mensagem_YX(Pos, argv[opt], 1);
}; // while()
if ( clear ) cls();
return opt;
}
int Menu::helper()
{
// valores de retorno
#define _DEFAULT_ '0'
#define _DESCE_ '-'
#define _ENTER_ 'R'
#define _ESCAPE_ 'E'
#define _SOBE_ '+'
// desce e sobe no indice das opcoes
typedef struct _INPUT_RECORD Input;
Input buffer[32];
char c = 0;
HANDLE Console = GetStdHandle(STD_INPUT_HANDLE);
DWORD tempo = timeout_ms;
DWORD tem_tecla = WAIT_OBJECT_0;
DWORD total = 0;
int sem_escolha = 1;
WORD v = 0; // a tecla
do
{
FlushConsoleInputBuffer(Console);
if ( WaitForSingleObject(Console, tempo) != tem_tecla) continue;
int n = PeekConsoleInput(Console, buffer, 32, (LPDWORD)&total);
if (total == 0) break;
for (DWORD i = 0; i < total; i += 1)
{
if (buffer[i].Event.KeyEvent.bKeyDown) continue;
v = buffer[i].Event.KeyEvent.wVirtualKeyCode;
c = buffer[i].Event.KeyEvent.uChar.AsciiChar;
// todos os testes sao definitivos entao so retorna
if (v == VK_ADD) return _SOBE_;
if (v == VK_SUBTRACT) return _DESCE_;
if (v == VK_DOWN) return _SOBE_;
if (v == VK_UP) return _DESCE_;
if (v == VK_OEM_PLUS) return _SOBE_;
if (v == '0') return _DEFAULT_;
if (v == '+') return _SOBE_;
if (v == VK_ESCAPE) return _ESCAPE_;
if (v == VK_RETURN) return _ENTER_;
if (c == '+') return _SOBE_;
if (c == '-') return _DESCE_;
if (c == '0') return _DEFAULT_;
}
} while (sem_escolha);
return 0;
return 0;
}
ostream& operator<<(ostream& saida, const Menu& M)
{
saida << "\n\n" << M.argc << " argumentos\n\n";
for (int i = 0; i < M.argc; i += 1)
{
saida << setw(2) << i << " " << M.argv[i] << "\n";
};
saida <<
"\n\tDefault = " << M.dflt <<
"\n\tTimeout = " << M.timeout_ms << "ms" <<
"\n\tOpcoes = " << M.opt <<
"\n\tOrigem: (" << M.linha << ", " << M.coluna << ")" <<
"\n\tCompleto: " << M.completo << "\n";
return saida;
}; // operator<<
| true |
df38ae8fb3cc376c242889bd10c9946b8aa04d3a | C++ | iwanao731/ofxSongle | /src/ofxSongleBeats.hpp | UTF-8 | 1,258 | 2.515625 | 3 | [] | no_license | #pragma once
#include "ofMain.h"
#include "ofxJSON.h"
namespace songle
{
class Beat;
class Bar;
class ofxSongleBeats
{
public:
ofxSongleBeats() {}
~ofxSongleBeats() {}
void load(const string &url);
void loadFile(const string &filename);
int getNumBeats();
int getNumBar();
int getBeatPosition(float currentFloatTime);
int getBeatStart(float currentFloatTime);
int getBeatIndex(float currentFloatTime);
int getBarPosition(const float currentFloatTime);
int getBarStart(const float currentFloatTime);
int getBarIndex(const float currentFloatTime);
int calcBPM(float currentFloatTime);
Beat &getBeat(int index);
Bar &getBar(int index);
void clear();
private:
std::vector<Beat> mBeats;
std::vector<Bar> mBars;
};
class Beat
{
public:
void setIndex(int index);
void setStart(int start);
void setPosition(int position);
int getIndex();
int getStart();
int getPosition();
private:
int mIndex;
int mStart;
int mPosition;
};
class Bar
{
public:
void setStart(int start);
void setIndex(int index);
void setNumBeats(int num);
int getStart();
int getIndex();
int getNumBeats();
Beat &getBeat(int index);
private:
int mStart;
int mIndex;
std::vector<Beat> mBeats;
};
}
| true |
c4c6d57932d004879d6f3bf33d1cf4d9ae7384a4 | C++ | DingZhan/Group_Programming_Ladder_Tournament | /L2-002.cpp | UTF-8 | 1,965 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include <cstring>
#include <vector>
#include <cmath>
using namespace std;
struct Node
{
int key;
int next;
};
#define MAX_N 100001
#define MAX_KEY 10001
int main()
{
Node nodes[MAX_N];
bool bTakens[MAX_KEY];
int startAddress, address, key, next, N, i, dupNodeStartAddress=-1, dupNodePreAddress=-1;
bool bPrintNext;
cin>>startAddress>>N;
for(i=0; i<N; ++i)
{
cin>>address>>key>>next;
nodes[address].key = key;
nodes[address].next = next;
bTakens[key>=0?key:-key] = false;
}
if(startAddress==-1)
return 0;
bPrintNext = false;
while(true)
{
key = nodes[startAddress].key;
if(bTakens[key>=0?key:-key])
{
if(dupNodeStartAddress==-1)
dupNodeStartAddress = startAddress;
else
nodes[dupNodePreAddress].next = startAddress;
dupNodePreAddress = startAddress;
startAddress = nodes[startAddress].next;
if(dupNodePreAddress!=-1)
nodes[dupNodePreAddress].next = -1;
}
else
{
if(bPrintNext)
cout<<" "<<setw(5)<<setfill('0')<<startAddress<<endl;
bTakens[key>=0?key:-key] = true;
cout<<setw(5)<<setfill('0')<<startAddress<<" "<<nodes[startAddress].key;
bPrintNext = true;
startAddress = nodes[startAddress].next;
}
if(startAddress==-1)
break;
}
if(bPrintNext)
cout<<" -1"<<endl;
startAddress = dupNodeStartAddress;
while(startAddress!=-1)
{
cout<<setw(5)<<setfill('0')<<startAddress<<" "<<nodes[startAddress].key;
if(nodes[startAddress].next==-1)
cout<<" -1"<<endl;
else
cout<<" "<<setw(5)<<setfill('0')<<nodes[startAddress].next<<endl;
startAddress = nodes[startAddress].next;
}
return 0;
}
| true |
6be3211efef49a38f62718b41c1e62c57e8a278c | C++ | amitbanerjee1999/Lab-Assignment-3rd-Sem | /Assignments/Lab Assignment Day-10/stack.cpp | UTF-8 | 621 | 3.390625 | 3 | [] | no_license | #include<stdio.h>
#define SIZE 50
using namespace std;
class Stack
{
int arr[SIZE];
int top;
public:
Stack()
{
top=-1;
}
void push(int data)
{
if(!isfull())
arr[++top]=data;
else
throw "overflow";
}
int pop()
{
if(!isempty())
return arr[top--];
else
throw "underflow";
}
int peek()
{
if(!isempty())
return arr[top];
else
throw "underflow";
}
bool isfull()
{
return top == SIZE-1;
}
bool isempty()
{
return top == -1;
}
};
| true |
4a89ea92506401dcff62bf3a5999fb06e4a2aafd | C++ | Saroko-dnd/My_DZ | /includes/associative_array.h | UTF-8 | 1,362 | 3.3125 | 3 | [] | no_license | #ifndef ASSOCIATIVE_ARRAY_H_INCLUDED
#define ASSOCIATIVE_ARRAY_H_INCLUDED
#include <iostream>
#include <cstdlib>
#include <string>
class assot_array
{
private:
std::string* str_array;
double* double_array;
int count_;
int counter;
public:
assot_array()
{
str_array=NULL;
double_array=NULL;
count_=0;
}
assot_array(int length)
{
str_array=(std::string*)malloc(length*sizeof(std::string));
double_array=(double*)malloc(length*sizeof(double));
count_=length;
counter=0;
}
assot_array(assot_array& add)
{
str_array=(std::string*)malloc(add.count_*sizeof(std::string));
double_array=(double*)malloc(add.count_*sizeof(double));
count_=add.count_;
counter=add.counter;
int count_num=0;
while (count_num<count_)
{
str_array[count_num]=add.str_array[count_num];
double_array[count_num]=add.double_array[count_num];
++count_num;
}
}
~assot_array()
{
if (str_array!=NULL && double_array!=NULL)
{
free(str_array);
free(double_array);
}
}
double operator[](std::string);
std::string operator[](double);
void add_element(std::string,double);
};
#endif // ASSOCIATIVE_ARRAY_H_INCLUDED
| true |
d643e242adb84d3fac492c18bd5dfbcd57a242aa | C++ | smcheah/Project-SIT210 | /main.cpp | UTF-8 | 1,373 | 3 | 3 | [] | no_license | #include "mbed.h"
#include "ultrasonic.h"
DigitalOut led1(LED1);
PwmOut buzzer(p23);
void dist(int distance)
{
//put code here to happen when the distance is changed
printf("Distance changed to %dmm\r\n", distance);
//closest
if (distance < 80)
{
led1 = 1;
wait(0.1);
led1 = 0;
wait(0.1);
buzzer = 1;
}
//close
if (distance > 80 and distance < 120)
{
led1 = 1;
wait(0.2);
led1 = 0;
wait(0.2);
while(1)
{
buzzer.period(1.0f); // 2 second period
buzzer.write(0.50f); // 50% duty cycle
}
}
//far
if (distance > 120 and distance < 150)
{
led1 = 1;
buzzer = 0;
}
}
ultrasonic mu(p21, p9, .2, 2, &dist); //Set the trigger pin to p21 and the echo pin to p9
//have updates every .1 seconds and a timeout after 1
//second, and call dist when the distance changes
int main()
{
mu.startUpdates();//start measuring the distance
while(1)
{
//Do something else here
mu.checkDistance(); //call checkDistance() as much as possible, as this is where
//the class checks if dist needs to be called.
}
}
| true |
e44abb0b1c6956f61926d49395a530a0c711e7d0 | C++ | AnTr24/CaveStoryRemake | /CaveStoryRemake/globals.h | UTF-8 | 1,110 | 3.09375 | 3 | [] | no_license | /*************************************************************************
File name: globals.h
Description: Holds global variables for the game. SPOOKY STUFF
**************************************************************************/
//#include guard. Prevents double definitions
#ifndef GLOBALS_H
#define GLOBALS_H
//includes
//declarations
namespace globals {
const int SCREEN_WIDTH = 640; //Cavestory's default window is 640 x 480
const int SCREEN_HEIGHT = 480;
const float SPRITE_SCALE = 2.0f; //sprites in cavestory seem to be scaled by x2
}
namespace sides {
enum Side {
TOP,
BOTTOM,
LEFT,
RIGHT,
NONE
};
const inline Side GetOppositeSide(Side side) {
return
side == TOP ? BOTTOM :
side == BOTTOM ? TOP :
side == LEFT ? RIGHT :
side == RIGHT ? LEFT :
NONE;
}
}
//represents the direction the character is facing
enum Direction {
LEFT,
RIGHT,
UP,
DOWN
};
//for pairs of data
struct Vector2 {
int x, y;
Vector2() :x(0), y(0) {}
Vector2(int x, int y) : x(x), y(y) {}
static Vector2 Zero() {
return Vector2(0, 0);
}
};
#endif //end of #include guard | true |
a3d374a723cac90977c80313822f9458609d1893 | C++ | faburaya/3fd | /3fd/isam/isam_impl_database.cpp | UTF-8 | 16,907 | 2.53125 | 3 | [
"MS-PL"
] | permissive | #include "pch.h"
#include "isam_impl.h"
#include <cassert>
#include <codecvt>
namespace _3fd
{
namespace isam
{
///////////////////////////
// Database Class
///////////////////////////
/// <summary>
/// Finalizes an instance of the <see cref="DatabaseImpl"/> class.
/// </summary>
DatabaseImpl::~DatabaseImpl()
{
CALL_STACK_TRACE;
auto rcode = JetCloseDatabase(m_jetSession, m_jetDatabase, 0);
ErrorHelper::LogError(NULL, m_jetSession, rcode, "Failed to close ISAM database", core::Logger::PRIO_ERROR);
}
/// <summary>
/// Opens a table from the ISAM database.
/// </summary>
/// <param name="name">The table name.</param>
/// <param name="throwTableNotFound">Whether an exception must be thrown in case the table is not found in the schema.</param>
/// <returns>
/// A <see cref="ITable" /> interface for the opened table.
/// If 'throwTableNotFound' is set to 'false' and the table is not found, returns a null pointer.
/// </returns>
ITable * DatabaseImpl::OpenTable(const string &name, bool throwTableNotFound)
{
CALL_STACK_TRACE;
try
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> transcoder;
const auto ucs2tableName = transcoder.from_bytes(name);
JET_TABLEID jetTable;
auto rcode = JetOpenTableW(m_jetSession,
m_jetDatabase,
ucs2tableName.data(),
nullptr, 0, 0,
&jetTable);
if (rcode == JET_errObjectNotFound && throwTableNotFound == false)
return nullptr;
else
{
ErrorHelper::HandleError(NULL, m_jetSession, rcode, [&name]()
{
std::ostringstream oss;
oss << "Failed to open table \'" << name << "\' from ISAM database";
return oss.str();
});
return dbg_new Table(this, jetTable, name);
}
}
catch (core::IAppException &)
{
throw; // just forward exceptions regarding errors known to have been previously handled
}
catch (std::exception &ex)
{
std::ostringstream oss;
oss << "Generic failure when opening table in ISAM database: " << ex.what();
throw core::AppException<std::runtime_error>(oss.str());
}
}
/// <summary>
/// Creates a new table in the ISAM database.
/// </summary>
/// <param name="name">The table name.</param>
/// <param name="isTemplate">Whether it is a template for creation of other similar tables.</param>
/// <param name="columns">The set of column definitions.</param>
/// <param name="indexes">The set of index definitions.</param>
/// <param name="sparse">Whether the table is sparse, which will tell the backend to expect a 20% density.</param>
/// <param name="reservedPages">The amount of pages to reserve for this table.</param>
/// <returns>A <see cref="ITable" /> interface for the newly created table.</returns>
ITable * DatabaseImpl::CreateTable(
const string &name,
bool isTemplate,
const std::vector<ITable::ColumnDefinition> &columns,
const std::vector<ITable::IndexDefinition> &indexes,
bool sparse,
unsigned long reservedPages)
{
CALL_STACK_TRACE;
try
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> transcoder;
const auto ucs2tableName = transcoder.from_bytes(name);
#ifndef _3FD_PLATFORM_WINRT
typedef JET_TABLECREATE2_W JET_TABLECREATE_X;
#else
typedef JET_TABLECREATE4_W JET_TABLECREATE_X;
#endif
// Set the table specs:
JET_TABLECREATE_X jetTable = {};
jetTable.cbStruct = sizeof jetTable;
jetTable.szTableName = const_cast<wchar_t *> (ucs2tableName.c_str());
jetTable.szTemplateTableName = nullptr;
jetTable.ulPages = reservedPages;
jetTable.ulDensity = sparse ? 20 : 0; // 0 forces the default value which is normally 80%
jetTable.grbit = isTemplate ? JET_bitTableCreateTemplateTable : 0;
std::vector<JET_COLUMNCREATE_W> jetColumns;
jetColumns.reserve(columns.size());
// Translated the columns definitions into the ESENT API expected structures:
for (auto &col : columns)
{
/* Default value type must match the column data type. Take into consideration, however,
that auxiliary functions such as 'AsInputParam' will consider a blob and a large blob as
the same, so a default parameter which is a large blob might be truncated to fit into a
regular one. The same goes for text and large text. */
_ASSERTE(
col.dataType == col.defaultValue.dataType
|| ((col.dataType == DataType::Blob || col.dataType == DataType::LargeBlob)
&& (col.defaultValue.dataType == DataType::Blob || col.defaultValue.dataType == DataType::LargeBlob))
|| ((col.dataType == DataType::Text || col.dataType == DataType::LargeText)
&& (col.defaultValue.dataType == DataType::Text || col.defaultValue.dataType == DataType::LargeText))
);
/* Multi-valued columns not null are currently not supported because they are not well handled
by Microsoft ESE. Everything works, except for the removal of a value, which must happen setting
it to NULL, which is not allowed. */
_ASSERTE((col.multiValued && col.notNull) == false);
JET_COLUMNCREATE_W jetCol = {};
jetCol.cbStruct = sizeof jetCol;
jetCol.szColumnName = const_cast<wchar_t *> (col.name.c_str());
jetCol.coltyp = static_cast<decltype(jetCol.coltyp)> (col.dataType);
jetCol.cbMax = Table::GetMaxLength(col.dataType);
jetCol.pvDefault = col.defaultValue.data;
jetCol.cbDefault = col.defaultValue.qtBytes;
jetCol.cp = static_cast<decltype(jetCol.cp)> (col.codePage);
jetCol.grbit = 0;
// Not null?
if (col.notNull)
jetCol.grbit |= JET_bitColumnNotNULL;
// Multi-valued?
if (col.multiValued)
jetCol.grbit |= JET_bitColumnMultiValued | JET_bitColumnTagged;
// Sparse?
if (col.sparse)
jetCol.grbit |= JET_bitColumnTagged;
// Automatic increment?
if (col.autoIncrement)
{
if (col.dataType == DataType::Int32 || col.dataType == DataType::Currency)
jetCol.grbit |= JET_bitColumnAutoincrement;
else
{
std::ostringstream oss;
oss << "Failed to create table \'" << name
<< "\' in ISAM database: column type can only be 'Int32' or 'Currency' in order to use automatic increment";
throw core::AppException<std::invalid_argument>(oss.str());
}
}
// Can use escrow update optimization?
if (col.dataType == DataType::Int32
&& col.defaultValue.qtBytes > 0
&& col.sparse == false
&& col.autoIncrement == false)
{
jetCol.grbit |= JET_bitColumnEscrowUpdate;
}
jetColumns.emplace_back(jetCol);
}
jetTable.rgcolumncreate = jetColumns.data();
jetTable.cColumns = jetColumns.size();
// Index definitions:
std::vector<JET_INDEXCREATE_X> jetIndexes;
TranslateStructures(indexes, jetIndexes);
jetTable.rgindexcreate = jetIndexes.data();
jetTable.cIndexes = jetIndexes.size();
// Finally invoke API to create the table:
#ifndef _3FD_PLATFORM_WINRT
auto rcode = JetCreateTableColumnIndex2W(m_jetSession, m_jetDatabase, &jetTable);
#else
auto rcode = JetCreateTableColumnIndex4W(m_jetSession, m_jetDatabase, &jetTable);
#endif
if (rcode != JET_errSuccess) // Failed to create the table:
{
// Log an error for each column that might have caused the error:
for (auto &jetCol : jetColumns)
{
if (jetCol.err != JET_errSuccess)
{
ErrorHelper::LogError(NULL, m_jetSession, jetCol.err, [&transcoder, &name, &jetCol]()
{
std::ostringstream oss;
oss << "Failed to create column \'" << transcoder.to_bytes(jetCol.szColumnName)
<< "\' in table \'" << name
<< "\' of ISAM database";
return oss.str();
}, core::Logger::PRIO_ERROR);
}
}
// Log an error for each index that might have caused the error:
for (auto &jetIdx : jetIndexes)
{
if (jetIdx.err != JET_errSuccess)
{
ErrorHelper::LogError(NULL, m_jetSession, jetIdx.err, [&transcoder, &name, &jetIdx]()
{
std::ostringstream oss;
oss << "Failed to create index \'" << transcoder.to_bytes(jetIdx.szIndexName)
<< "\' in table \'" << name
<< "\' of ISAM database";
return oss.str();
}, core::Logger::PRIO_ERROR);
}
}
// Throw an exception for the error:
ErrorHelper::HandleError(NULL, m_jetSession, rcode, [&name]()
{
std::ostringstream oss;
oss << "Failed to create table \'" << name << "\' in ISAM database";
return oss.str();
});
}
return dbg_new Table(this, jetTable.tableid, name);
}
catch (core::IAppException &)
{
throw; // just forward exceptions regarding errors known to have been previously handled
}
catch (std::exception &ex)
{
std::ostringstream oss;
oss << "Generic failure when creating table in ISAM database: " << ex.what();
throw core::AppException<std::runtime_error>(oss.str());
}
}
/// <summary>
/// Creates a new table from a template.
/// </summary>
/// <param name="name">The table name.</param>
/// <param name="templateName">Name of the template.</param>
/// <param name="sparse">Whether the table is sparse, which will tell the backend to expect a 20% density.</param>
/// <param name="reservedPages">The amount of pages to reserve for this table.</param>
/// <returns>A <see cref="ITable" /> interface for the newly created table.</returns>
ITable * DatabaseImpl::CreateTable(
const string &name,
const string &templateName,
bool sparse,
unsigned long reservedPages)
{
CALL_STACK_TRACE;
try
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> transcoder;
const auto ucs2tableName = transcoder.from_bytes(name);
const auto ucs2templateName = transcoder.from_bytes(templateName);
#ifndef _3FD_PLATFORM_WINRT
typedef JET_TABLECREATE_W JET_TABLECREATE_X;
#else
typedef JET_TABLECREATE4_W JET_TABLECREATE_X;
#endif
// Set the table specs:
JET_TABLECREATE_X jetTable = {};
jetTable.cbStruct = sizeof jetTable;
jetTable.szTableName = const_cast<wchar_t *> (ucs2tableName.c_str());
jetTable.szTemplateTableName = const_cast<wchar_t *> (ucs2templateName.c_str());
jetTable.ulPages = reservedPages;
jetTable.ulDensity = sparse ? 20 : 0; // 0 forces the default value which is normally 80%
jetTable.rgcolumncreate = nullptr;
jetTable.cColumns = 0;
jetTable.rgindexcreate = nullptr;
jetTable.cIndexes = 0;
jetTable.grbit = 0;
// Finally invoke API to create the table:
#ifndef _3FD_PLATFORM_WINRT
auto rcode = JetCreateTableColumnIndexW(m_jetSession, m_jetDatabase, &jetTable);
#else
auto rcode = JetCreateTableColumnIndex4W(m_jetSession, m_jetDatabase, &jetTable);
#endif
ErrorHelper::HandleError(NULL, m_jetSession, rcode, [&name]()
{
std::ostringstream oss;
oss << "Failed to create table \'" << name << "\' from template in ISAM database";
return oss.str();
});
return dbg_new Table(this, jetTable.tableid, name);
}
catch (core::IAppException &)
{
throw; // just forward exceptions regarding errors known to have been previously handled
}
catch (std::exception &ex)
{
std::ostringstream oss;
oss << "Generic failure when creating table from template in ISAM database: " << ex.what();
throw core::AppException<std::runtime_error>(oss.str());
}
}
/// <summary>
/// Deletes a table.
/// </summary>
/// <param name="name">The table name.</param>
void DatabaseImpl::DeleteTable(const string &name)
{
CALL_STACK_TRACE;
try
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> transcoder;
const auto ucs2tableName = transcoder.from_bytes(name);
auto rcode = JetDeleteTableW(m_jetSession, m_jetDatabase, ucs2tableName.c_str());
ErrorHelper::HandleError(NULL, m_jetSession, rcode, [&name]()
{
std::ostringstream oss;
oss << "Failed to delete table \'" << name << "\' in ISAM database";
return oss.str();
});
}
catch (core::IAppException &)
{
throw; // just forward exceptions regarding errors known to have been previously handled
}
catch (std::exception &ex)
{
std::ostringstream oss;
oss << "Generic failure when deleting table from ISAM database: " << ex.what();
throw core::AppException<std::runtime_error>(oss.str());
}
}
/// <summary>
/// Gets a cursor for the table.
/// </summary>
/// <param name="table">The table for which a cursor must be retrieved.</param>
/// <param name="prefetch">Whether the table data should be prefetched in cache for optimized sequential access.</param>
/// <returns>
/// A private implementation for table cursor.
/// </returns>
TableCursorImpl * DatabaseImpl::GetCursorFor(const ITable &table, bool prefetch)
{
CALL_STACK_TRACE;
try
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> transcoder;
const auto ucs2tableName = transcoder.from_bytes(table.GetName());
JET_TABLEID jetTable;
auto rcode = JetOpenTableW(m_jetSession,
m_jetDatabase,
ucs2tableName.data(),
nullptr, 0,
prefetch ? JET_bitTableSequential : 0,
&jetTable);
ErrorHelper::HandleError(NULL, m_jetSession, rcode, [&table]()
{
std::ostringstream oss;
oss << "Failed to get cursor for table \'" << table.GetName() << "\' from ISAM database";
return oss.str();
});
return dbg_new TableCursorImpl(table, jetTable, m_jetSession);
}
catch (core::IAppException &)
{
throw; // just forward exceptions regarding errors known to have been previously handled
}
catch (std::exception &ex)
{
std::ostringstream oss;
oss << "Generic failure when creating cursor for table in ISAM database: " << ex.what();
throw core::AppException<std::runtime_error>(oss.str());
}
}
}// end namespace isam
}// end namespace _3fd
| true |
96d421b7b8def8f3d0d9f0622986addeeb2f243e | C++ | kronosaur/TranscendenceDev | /Mammoth/Include/Painters.h | UTF-8 | 10,592 | 2.625 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | // Painters.h
//
// Transcendence UI Engine
// Copyright (c) 2010 by George Moromisato. All Rights Reserved.
#pragma once
class CHoverDescriptionPainter
{
public:
CHoverDescriptionPainter (const CVisualPalette &VI);
inline void Hide (void) { m_cxWidth = 0; }
inline bool IsVisible (void) const { return (m_cxWidth > 0); }
void Paint (CG32bitImage &Dest) const;
inline void SetBackColor (const CG32bitPixel rgbValue) { m_rgbBack = rgbValue; }
void SetDescription (const CString &sValue);
inline void SetDescriptionColor (const CG32bitPixel rgbValue) { m_rgbDescription = rgbValue; }
inline void SetItem (const CItem &Item) { m_Item = Item; Invalidate(); }
inline void SetTitle (const CString &sValue) { m_sTitle = sValue; m_Item = CItem(); Invalidate(); }
inline void SetTitleColor (const CG32bitPixel rgbValue) { m_rgbTitle = rgbValue; }
void Show (int x, int y, int cxWidth, const RECT &rcContainer);
private:
void InitRects (int cxWidth, int cyHeight) const;
inline void Invalidate (void) { m_rcRect = { 0, 0, 0, 0 }; }
inline bool IsInvalid (void) const { return (m_rcRect.left == 0 && m_rcRect.right == 0); }
void FormatText (void) const;
void PaintItem (CG32bitImage &Dest) const;
void PaintText (CG32bitImage &Dest) const;
const CVisualPalette &m_VI;
CString m_sTitle; // Title to paint
CString m_sDescription; // Description
CItem m_Item; // Item to show (may be empty)
CG32bitPixel m_rgbBack; // Background color
CG32bitPixel m_rgbTitle; // Title color
CG32bitPixel m_rgbDescription; // Description color
int m_xPos; // Draw the description at this position, but
int m_yPos; // adjust to fit in the container
int m_cxWidth; // Desired width of description box (0 = hidden)
RECT m_rcContainer; // Position description inside this container
// Initialized in Format
mutable RECT m_rcRect; // Rect of entire background
mutable RECT m_rcText; // Rect of text area
mutable CTextBlock m_DescriptionRTF; // Rich text to draw
};
class CTilePainter
{
public:
struct SInitOptions
{
int cyDefaultRow = 0; // Default row height
int cxImage = 96; // Force icon to fit
int cyImage = 96; // Force icon to fit
Metric rImageScale = 1.0; // If not 1.0, then use this to scale icon
const CG16bitFont *pTitleFont = NULL;
const CG16bitFont *pDescFont = NULL;
};
struct SPaintOptions
{
CG32bitPixel rgbTitleColor = RGB_NORMAL_TITLE;
CG32bitPixel rgbDescColor = RGB_NORMAL_DESC;
};
CTilePainter (const CVisualPalette &VI = g_pHI->GetVisuals()) :
m_VI(VI)
{ }
int GetHeight (void) const { return m_cyHeight; }
void Init (const CTileData &Entry, int cxWidth, const SInitOptions &Options);
bool IsEmpty (void) const { return (m_cxWidth == 0);}
void Paint (CG32bitImage &Dest, int x, int y, const SPaintOptions &Options) const;
private:
static constexpr int PADDING_X = 8;
static constexpr int PADDING_Y = 8;
static constexpr CG32bitPixel RGB_NORMAL_DESC = CG32bitPixel(128,128,128);
static constexpr CG32bitPixel RGB_NORMAL_TITLE = CG32bitPixel(220,220,220); // H:0 S:0 B:86
void PaintImage (CG32bitImage &Dest, int x, int y) const;
const CVisualPalette &m_VI;
CTileData m_Entry;
SInitOptions m_Options;
// Computed after Init
int m_cxWidth = 0;
int m_cyHeight = 0;
RECT m_rcText = { 0 };
};
class CItemPainter
{
public:
static constexpr int ATTRIB_PADDING_X = 4;
static constexpr int ATTRIB_PADDING_Y = 1;
static constexpr int ATTRIB_SPACING_X = 2;
static constexpr int ATTRIB_SPACING_Y = 2;
static constexpr int DAMAGE_ADJ_ICON_WIDTH = 16;
static constexpr int DAMAGE_ADJ_ICON_HEIGHT = 16;
static constexpr int DAMAGE_ADJ_ICON_SPACING_X = 2;
static constexpr int DAMAGE_ADJ_SPACING_X = 6;
static constexpr int DAMAGE_TYPE_ICON_WIDTH = 16;
static constexpr int DAMAGE_TYPE_ICON_HEIGHT = 16;
static constexpr int DEFAULT_WIDTH = 200;
static constexpr int ENHANCEMENT_ICON_HEIGHT = 40;
static constexpr int ENHANCEMENT_ICON_WIDTH = 40;
static constexpr int ICON_HEIGHT = 96;
static constexpr int ICON_WIDTH = 96;
static constexpr int ITEM_DEFAULT_HEIGHT = 96;
static constexpr int ITEM_LEFT_PADDING = 8;
static constexpr int ITEM_RIGHT_PADDING = 8;
static constexpr int ITEM_TEXT_MARGIN_Y = 4;
static constexpr int ITEM_TEXT_MARGIN_X = 4;
static constexpr int ITEM_TEXT_MARGIN_BOTTOM = 10;
static constexpr int ITEM_TITLE_EXTRA_MARGIN = 4;
static constexpr int LAUNCHER_ICON_HEIGHT = 16;
static constexpr int LAUNCHER_ICON_WIDTH = 16;
static constexpr int SMALL_ICON_HEIGHT = 64;
static constexpr int SMALL_ICON_WIDTH = 64;
static constexpr DWORD OPTION_DISPLAY_AS_KNOWN = 0x00000001;
static constexpr DWORD OPTION_NO_ARMOR_SPEED = 0x00000002;
static constexpr DWORD OPTION_NO_ICON = 0x00000004;
static constexpr DWORD OPTION_NO_PADDING = 0x00000008;
static constexpr DWORD OPTION_SMALL_ICON = 0x00000020;
static constexpr DWORD OPTION_TITLE = 0x00000040;
static constexpr CG32bitPixel RGB_NORMAL_TEXT = CG32bitPixel(220,220,220); // H:0 S:0 B:86
static constexpr CG32bitPixel RGB_MODIFIER_NORMAL_BACKGROUND = CG32bitPixel(101,101,101); // H:0 S:0 B:40
static constexpr CG32bitPixel RGB_MODIFIER_NORMAL_TEXT = CG32bitPixel(220,220,220); // H:0 S:0 B:86
struct SOptions
{
SOptions (void) { }
SOptions (DWORD dwOptions) :
bDisplayAsKnown((dwOptions & OPTION_DISPLAY_AS_KNOWN) ? true : false),
bNoArmorSpeed((dwOptions & OPTION_NO_ARMOR_SPEED) ? true : false),
bNoIcon((dwOptions & OPTION_NO_ICON) ? true : false),
bNoPadding((dwOptions & OPTION_NO_PADDING) ? true : false),
bSmallIcon((dwOptions & OPTION_SMALL_ICON) ? true : false),
bTitle((dwOptions & OPTION_TITLE) ? true : false)
{ }
bool bDisplayAsKnown = false;
bool bNoArmorSpeed = false;
bool bNoIcon = false;
bool bNoPadding = false;
bool bSmallIcon = false;
bool bTitle = false;
};
CItemPainter (const CVisualPalette &VI = g_pHI->GetVisuals()) :
m_VI(VI)
{ }
int GetHeight (void) const { return m_cyHeight; }
void Init (const CItem &Item, int cxWidth, const SOptions &Options);
static constexpr DWORD OPTION_SELECTED = 0x00000010;
static constexpr DWORD OPTION_DISABLED = 0x00000080;
void Paint (CG32bitImage &Dest, int x, int y, CG32bitPixel rgbTextColor = RGB_NORMAL_TEXT, DWORD dwOptions = 0) const;
private:
int CalcItemEntryHeight (int cxWidth) const;
void InitMetrics (int cxWidth);
static void FormatDisplayAttributes (const CVisualPalette &VI, TArray<SDisplayAttribute> &Attribs, const RECT &rcRect, CCartoucheBlock &retBlock, int *retcyHeight = NULL);
static void FormatLaunchers (const CVisualPalette &VI, const CMissileItem &MissileItem, const TArray<CItem> &Launchers, const RECT &rcRect, CIconLabelBlock &retLaunchers);
static void PaintItemEnhancement (const CVisualPalette &VI, CG32bitImage &Dest, CSpaceObject *pSource, const CItem &Item, const CItemEnhancement &Enhancement, const RECT &rcRect, CG32bitPixel rgbText, DWORD dwOptions, int *retcyHeight = NULL);
static void PaintReferenceDamageAdj (const CVisualPalette &VI, CG32bitImage &Dest, int x, int y, int iLevel, int iHP, const int *iDamageAdj, CG32bitPixel rgbText, DWORD dwOptions);
static void PaintReferenceDamageType (const CVisualPalette &VI, CG32bitImage &Dest, int x, int y, int iDamageType, const CString &sRef, CG32bitPixel rgbText, DWORD dwOptions);
const CVisualPalette &m_VI;
const CItem *m_pItem = NULL;
SOptions m_Options;
// Computed after Init
CCartoucheBlock m_AttribBlock; // Formatted attributes
CIconLabelBlock m_Launchers; // Formatted list of launchers
int m_cxWidth = 0;
int m_cyHeight = 0;
int m_cxIcon = 0;
int m_cyIcon = 0;
RECT m_rcDraw = { 0 }; // Rect where text goes
};
class CStargateEffectPainter
{
public:
CStargateEffectPainter (void);
void Paint (CG32bitImage &Dest, const RECT &rcRect);
void Update (void);
private:
struct SWormholePos
{
Metric rAngle;
Metric rRadius;
Metric rDepth;
};
struct STracer
{
STracer (void) : Points(0)
{ }
TQueue<SWormholePos> Points;
SWormholePos Vel;
CG32bitPixel Color;
};
struct SPaintCtx
{
CG32bitImage *pDest;
Metric xCenter;
Metric yCenter;
Metric cxHalfWidth;
Metric cyHalfHeight;
};
void InitGradientColorTable (int iRadius);
void InitTracer (STracer &Tracer);
void PaintTracer (SPaintCtx &Ctx, const STracer &Tracer);
void TransformPos(SPaintCtx &Ctx, const SWormholePos &Pos, int *retx, int *rety);
int m_iInitialUpdates; // Number of ticks to update before first paint
int m_iMaxTracerCount; // Max number of tracers
int m_iMaxTracerLength; // Max number of segments per tracer
int m_iNewTracerCount; // Number of new tracers per tick
BYTE m_byTracerOpacity; // Max opacity of tracers
Metric m_rMaxDepth; // Max depth of tracers
Metric m_rRotationVel; // Effect rotation in radians per tick
Metric m_rGlowAccel; // Glow acceleration (pixels per tick)
TArray<CG32bitPixel> m_GradientColorTable;
TArray<STracer> m_Tracers;
Metric m_rRotation;
Metric m_rGlowVel;
Metric m_rGlowRadius;
};
class CAutomataEffectPainter
{
public:
CAutomataEffectPainter (int width, int height);
int CountLiveNeighbors (int x, int y);
void InitGradientColorTable (void);
bool IsAlive(int x, int y);
void Paint (CG32bitImage &Dest, const RECT &rcRect);
void Update (void);
private:
struct SCell
{
SCell(void) : iOpacity(0), bAlive(false) {}
SCell(bool alive) : iOpacity(0), bAlive(alive) {}
BYTE iOpacity; // A value from 0 to 255. Increases while the cell is alive and decreases while the cell is dead
bool bAlive; // Whether the cell is alive or dead
bool bAliveNext; // Whether the cell will be alive or dead on the next tick. Used only during Update()
};
struct SPaintCtx
{
CG32bitImage *pDest;
Metric xCenter;
Metric yCenter;
Metric cxHalfWidth;
Metric cyHalfHeight;
};
int m_iTicks; // Number of ticks passed
int m_iInitialUpdates; // Number of ticks to update before first paint
int m_iOpacityInc; // The rate at which a cell changes its opacity
int m_iWidth; // Width of the grid
int m_iHeight; // Height of the grid
TArray<CG32bitPixel> m_GradientColorTable;
TArray< TArray<SCell> > m_Grid;
};
| true |
92de4a8be9a38e3f490dee13a1b9c417b6fd5617 | C++ | lanking520/CYTON_VETA_FILE | /Bridge_model/Arduino_servo_test/Arduino_servo_test.ino | UTF-8 | 523 | 2.65625 | 3 | [] | no_license | #include <VarSpeedServo.h>
VarSpeedServo myservo; // create servo object to control a servo
//Servo myservo_2;
int servo_pos=9;
void setup()
{
Serial.begin(115200);
myservo.attach(servo_pos); // attaches the servo on pin 9 to the servo object
}
void loop()
{
for (int j = 40; j <= 255; j +=20)
{
Serial.print("Now Step to Velocity");
Serial.println(j);
for (int i = 30; i <= 80; i+=10)
{
myservo.write(i,j,true);
delay(30);
}
}
delay(3000);
}
| true |
7bb76129f33e0026281694dafbbd28c5ae9c5faa | C++ | ZeroCoolX/KeyLogger | /KeyLogger/Timer.h | UTF-8 | 2,473 | 3.671875 | 4 | [] | no_license | #ifndef TIMER_H
#define TIMER_H
#include <thread>
#include <chrono>
class Timer{
private:
std::thread Thread; // non main blocking thread instance
bool Alive {false}; // thread status
std::function<void(void)> funct = nullptr; // reference to a function to call
std::chrono::milliseconds interval {std::chrono::milliseconds(0)}; // interval between function calls.
long CallCount {-1L}; // determine how many we want to call a certain function
long repeat_count {-1L}; // count number of times a function is called from max -> 0
void SleepAndRun(){
std::this_thread::sleep_for(interval);
if(Alive){
GetFunction()();
}
}
void ThreadFunc(){
if(CallCount == INFINITY){
while(Alive){
this->SleepAndRun();
}
}else{
while(repeat_count--){
this->SleepAndRun();
}
}
}
public:
static const long INFINITY{-1L};
Timer(){}
Timer(const std::function<void(void)> &f)
: funct(f){}
Timer(const std::function<void(void)> &f, const unsigned long &interval, const long callCnt = Timer::INFINITY)
: funct(f), interval(std::chrono::milliseconds(interval)), CallCount(callCnt){}
void Start(bool async = true){
if(IsAlive()){
return;
}
Alive = true;
repeat_count = CallCount;
if(async){
Thread = std::thread(ThreadFunc, this);
}else{
this->ThreadFunc();
}
}
void Stop(){
Alive = false;
Thread.join();
}
void SetFunction(const std::function<void(void)> &f){
funct = f;
}
bool IsAlive() const { return Alive; }
long GetRepeatCount() const { return CallCount; }
void SetRepeatCount(const long rptCnt){
if(Alive){ return; }
CallCount = rptCnt;
}
long GetRemainingCount() const {return repeat_count;}
unsigned long GetInterval() const {return interval.count();}
void SetInterval(const unsigned long &intv){
if(Alive){return;}
interval = std::chrono::milliseconds(intv);
}
const std::function<void(void)> &GetFunction() const {return funct;}
};
#endif // TIMER_H
| true |
1fda7c66ef80ae33f598b6e087f4706c0cdb2302 | C++ | FrankMuti/LearningAlgorithms | /katcl/data_structures/_seg_tree.cc | UTF-8 | 982 | 2.96875 | 3 | [] | no_license | /**
* author: stein
* created: 2020.09.24 19:20:10
**/
#include <bits/stdc++.h>
using namespace std;
struct Tree {
typedef int T;
static constexpr T unit = INT_MIN;
T f (T a, T b) { return max(a, b); }
vector<T> s;
int n;
Tree (int n = 0, T def = unit) : s (2*n, def) , n (n) {}
void update(int pos, T val) {
for (s[pos += n] = val; pos /= 2; ) {
s[pos] = f(s[pos * 2], s[pos * 2 + 1]);
}
}
T query(int b, int e) {
T ra = unit, rb = unit;
for (b += n, e += n; b < e; b /= 2, e /= 2) {
if (b % 2) ra = f (ra, s[b++]);
if (e % 2) rb = f (s[--e], rb);
}
return f (ra,rb);
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
Tree tree;
tree.s = {0,39, 22, 17, 13, 9, 9, 8, 5, 8, 6, 3, 2, 7, 2, 6};
tree.n = tree.s.size();
vector<int> arr {tree.s};
int sum = 0;
for (int i = 0; i < tree.n; i++) {
sum += arr[i];
cout << tree.query(0, i) << " " << sum << endl;
}
return 0;
}
| true |
d07258f93452c2b9fd958754dccd29d67d2a2175 | C++ | VisionAerie/vision | /software/src/master/src/backend/DSC_Pointer.h | UTF-8 | 67,962 | 2.671875 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef DSC_Pointer_Interface
#define DSC_Pointer_Interface
/************************
***** Components *****
************************/
#include "DSC_Scalar.h"
/**************************
***** Declarations *****
**************************/
#include "RTlink.h"
/*************************
***** Definitions *****
*************************/
/*---------------------------------------------------------------------------
* Pointers select elements from a positional structure. Pointers attempt to
* consolidate in one abstraction three concepts:
*
* - scalars versus collections
* - values versus positions
* - ordered versus unordered positional collections
*
* (More will be said about these concepts when time pressures are fewer...)
*
* Pointers which can be replaced by equivalent ordered positional collections
* (i.e., links) are termed link equivalent. The only pointer type which is
* NOT link equivalent is 'Reference'. Two different pointer type names are
* provided to preserve this distinction notionally in the programs which use
* pointers; however, the use of common macros precludes the creation of
* physically distinct types.
*---------------------------------------------------------------------------
*/
/*---------------------------------------------------------------------------
* In all discussions of 'Pointers', the terms 'ordered collection' and
* 'ordered' refer to 'user' defined and controlled orderings. These
* orderings impose no implicit content based constraints on the order in
* which two or more elements can appear in a collection.
*
* A pointer is termed link equivalent if it can be translated into an
* equivalent link for purposes of positional access to a structure.
*---------------------------------------------------------------------------
*/
/***************************
***** Pointer Types *****
***************************/
/*---------------------------------------------------------------------------
* Pointer Types (Definitions found in 'VkScalar.h'):
* Empty - the nil pointer - no positional relationship
* is defined or implied by this pointer type.
* Scalar - an optimization of 'Link/Reference' and
* 'Values' for singletons. Scalars of R-Type
* 'RefUV' behave like a 'Link/Reference' of
* one element. Scalars of all other R-Types
* behave like one element 'Value's. Scalars
* are link equivalent.
* Value - an ordered collection of information bearing
* values. Values typically represent ordered
* collections of integers, reals, dates, and
* other infinite types. All elements of a
* 'Value' translate into reference 'nil'
* when interpreted as references; consequently,
* 'Value's are link equivalent.
* Identity - a collection in one-to-one correspondence to
* another collection. 'Identity's are link
* equivalent.
* Link - an sorted collection of positions. Links are
* link equivalent (surprise!).
* Reference - an ordered collection of positions.
* References are NOT link equivalent.
*---------------------------------------------------------------------------
*/
/********************
***** VALUES *****
********************/
/*---------------------------------------------------------------------------
* Values represent ordered non-positional collections. Values are directly
* represented by u-vectors.
*---------------------------------------------------------------------------
*/
/*********************************
* Value CPD and R-Type Access *
*********************************/
/*---------------------------------------------------------------------------
***** Macro to return a standard CPD for a 'Value'.
*
* Arguments:
* value - the value to be converted into a container.
*
* Syntactic Context:
* M_CPD *Expression - a CPD for an instance of the least
* general R-Type required to represent this
* value. This CPD must be freed when no
* longer needed.
*
* Notes:
* The semantics of descriptor values requires that this macro
* manufacture a new container to hold the value. With a suitable
* change in P-Token, that container may be used to instantiate a new
* V-Store (provided the container returned is NOT a reference u-vector).
*
*****/
/*---------------------------------------------------------------------------
***** Macro to return the R-Type of the 'Value' component of a descriptor.
*
* Arguments:
* value - the value whose R-Type is desired.
*
* Syntactic Context:
* RType_Type Expression
*
*****/
/*************************
* Value P-Token Query *
*************************/
/*---------------------------------------------------------------------------
***** Macro to obtain a reference (i.e., CPD/Index pair) to the positional
***** P-Token of a value.
*
* Arguments:
* value - the value whose positional P-Token is
* desired.
* pPTokenRef/Index - 'lval's which will be set to a CPD and index
* pair referencing the POP of the positional
* P-Token of 'value'. 'pPTokenRef' must be
* freed when no longer needed.
*
* Syntactic Context:
* Compound Statement
*
*****/
/*---------------------------------------------------------------------------
***** Macro to obtain a reference (i.e., CPD/Index pair) to the referential
***** P-Token of a value.
*
* Arguments:
* value - the value whose referential P-Token is
* desired.
* pPTokenRef/Index - 'lval's which will be set to a CPD and index
* pair referencing the POP of the referential
* P-Token of 'value'. 'pPTokenRef' must be
* freed when no longer needed.
*
* Syntactic Context:
* Compound Statement
*
*****/
/*********************************
* Value Initialization Macros *
*********************************/
/***** Macros to Initialize a Value from a Value and index *****/
/*---------------------------------------------------------------------------
***** Macro to initialize a Value from a link constructor and a source
***** Value.
*
* Arguments:
* target - the Value to be initialized.
* linkc - a pointer to a link constructor which will be
* used to extract from the source Value.
* source - the Value to use as the source of the
* extract.
*
* Syntactic Context:
* Compound Statement
*
****/
/*---------------------------------------------------------------------------
***** Macro to initialize a Value from a reference uvector and a source
***** Value.
*
* Arguments:
* target - the Value to be initialized.
* cpd - a standard CPD for a reference uvector which
* will be used to extract from the source
* Value.
* source - the Value to use as the source of the
* extract.
*
* Syntactic Context:
* Compound Statement
*
****/
/*******************************************
* Value Duplication and Clearing Macros *
*******************************************/
/*---------------------------------------------------------------------------
***** Macro to duplicate a 'Value'
*
* Arguments:
* target - a location whose contents will be replaced
* by the duplicated Value. This location
* is assumed to NOT contain a currently valid
* Value.
* source - a location containing the Value to be
* duplicated.
*
* Syntactic Context:
* Compound Statement
*
*****/
/*---------------------------------------------------------------------------
***** Macro to clear a 'Value'
*
* Arguments:
* value - the Value to be cleared.
*
* Syntactic Context:
* Compound Statement
*
*****/
/****************************
* Value Class Definition *
****************************/
class DSC_Value {
// Exception Generation
protected:
enum ExceptionSource {
ExceptionSource_ConstructComposition
};
void raiseTypeException (ExceptionSource xExceptionSource) const;
// Construction
public:
void construct (DSC_Value const &rSource) {
m_pValues = rSource;
m_pValues->retain ();
}
void construct (M_CPD *pValues) {
m_pValues = pValues;
}
void constructComposition (rtLINK_CType *pSubscript, M_CPD *pSource);
void constructComposition (M_CPD *pSubscript, M_CPD *pSource);
void constructSet (M_ASD *pContainerSpace, M_CPD *&enumeration, M_CPD *source);
// Destruction
public:
void clear () {
m_pValues->release ();
}
// Component Realization
public:
M_CPD *realizedValues () const {
return m_pValues;
}
// Access
public:
unsigned int cardinality () const {
return UV_CPD_ElementCount (m_pValues);
}
rtPTOKEN_Handle *PPT () const {
return static_cast<rtUVECTOR_Handle*>(m_pValues->containerHandle ())->pptHandle ();
}
rtPTOKEN_Handle *RPT () const {
return static_cast<rtUVECTOR_Handle*>(m_pValues->containerHandle ())->rptHandle ();
}
RTYPE_Type RType () const {
return m_pValues->RType ();
}
operator M_CPD* () const {
return m_pValues;
}
M_CPD *operator-> () const {
return m_pValues;
}
// Query
public:
bool isACoercedScalar () const;
// Container Creation
public:
M_CPD *asContainer (rtPTOKEN_Handle *pPPT) const {
return UV_BasicCopy (m_pValues, pPPT);
}
// Modification
public:
void distribute (M_CPD *pDistribution);
// State
protected:
M_CPD *m_pValues;
};
/************************
***** IDENTITIES *****
************************/
/*---------------------------------------------------------------------------
* Identities represent a positional collection in one-to-one correspondence
* with another collection. Identities are represented by a p-token.
*
* Identity Field Descriptions:
* m_pPToken - a handle for the P-Token denoting this identity.
*---------------------------------------------------------------------------
*/
/**********************************************
* Identity: PToken, CPD, and R-Type Access *
**********************************************/
/*---------------------------------------------------------------------------
***** Macro to return a standard CPD for a 'Identity'.
*
* Arguments:
* identity - the identity to be converted into a
* container.
*
* Syntactic Context:
* M_CPD *Expression - a CPD for an instance of the least
* general R-Type required to represent this
* value. This CPD must be freed when no
* longer needed.
*
* Notes:
* The semantics of descriptor identities requires that this macro
* manufacture a new container to hold the identity. With a suitable
* change in P-Token, that container may be used to instantiate a new
* V-Store (provided the container returned is NOT a reference u-vector).
*
*****/
/*---------------------------------------------------------------------------
***** Macro to return the R-Type of the 'Identity' component of a descriptor.
*
* Arguments:
* identity - the identity whose R-Type is desired.
*
* Syntactic Context:
* RTYPE_Type Expression
*
*****/
/****************************
* Identity P-Token Query *
****************************/
/*---------------------------------------------------------------------------
***** Macro to obtain a reference (i.e., CPD/Index pair) to the positional
***** P-Token of an identity.
*
* Arguments:
* identity - the identity whose positional P-Token is
* desired.
* pPTokenRef/Index - 'lval's which will be set to a CPD and index
* pair referencing the POP of the positional
* P-Token of 'identity'. 'pPTokenRef' must
* be freed when no longer needed.
*
* Syntactic Context:
* Compound Statement
*
*****/
/*---------------------------------------------------------------------------
***** Macro to obtain a reference (i.e., CPD/Index pair) to the referential
***** P-Token of an identity.
*
* Arguments:
* identity - the identity whose referential P-Token is
* desired.
* pPTokenRef/Index - 'lval's which will be set to a CPD and index
* pair referencing the POP of the referential
* P-Token of 'identity'. 'pPTokenRef' must
* be freed when no longer needed.
*
* Syntactic Context:
* Compound Statement
*
*****/
/************************************
* Identity Initialization Macros *
************************************/
/*---------------------------------------------------------------------------
***** Macro to initialize an 'Identity'
*
* Arguments:
* identity - the Pointer to be initialized.
* pToken - a CPD for the P-Token denoting the identity.
* ASSIGNED directly into the identity.
*
* Syntactic Context:
* Compound Statement
*
*****/
/*---------------------------------------------------------------------------
***** Macro to initialize a set Reference and an enumeration from a source
***** Identity.
*
* Arguments:
* target - the set Reference to be initialized.
* enumeration - an 'lval' of type 'M_CPD*' which will
* be set to a standard CPD for a reference
* u-vector specifying the ordering factored
* from 'source'.
* source - the Identity to use as the source of the
* set.
*
* Syntactic Context:
* Compound Statement
*
****/
/**********************************************
* Identity Duplication and Clearing Macros *
**********************************************/
/*---------------------------------------------------------------------------
***** Macro to duplicate an 'Identity'
*
* Arguments:
* target - a location whose contents will be replaced
* by the duplicated Identity. This location
* is assumed to NOT contain a currently valid
* Identity.
* source - a location containing the Identity to be
* duplicated.
*
* Syntactic Context:
* Compound Statement
*
*****/
/*---------------------------------------------------------------------------
***** Macro to clear an 'Identity'
*
* Arguments:
* identity - the Identity to be cleared.
*
* Syntactic Context:
* Compound Statement
*
*****/
/*******************************
* Identity Class Definition *
*******************************/
class DSC_Identity {
// Construction
public:
void construct (DSC_Identity const &rSource) {
m_pPToken = rSource.m_pPToken;
m_pPToken->retain ();
}
void construct (rtPTOKEN_Handle *pPToken) {
pPToken->retain ();
m_pPToken = pPToken;
}
// Destruction
public:
void clear () {
m_pPToken->release ();
m_pPToken = 0;
}
// Access
public:
unsigned int cardinality () const {
return m_pPToken->cardinality ();
}
rtPTOKEN_Handle *PPT () const {
return m_pPToken;
}
rtPTOKEN_Handle *RPT () const {
return m_pPToken;
}
rtPTOKEN_Handle *PToken () const {
return m_pPToken;
}
static RTYPE_Type RType () {
return RTYPE_C_Link;
}
// Query
public:
bool isScalar () const {
return m_pPToken->NamesTheScalarPToken ();
}
// Container Creation
public:
M_CPD *asContainer (rtPTOKEN_Handle *pPPT) const {
return rtLINK_NewRefLink (pPPT, m_pPToken);
}
M_CPD *asUVector () const {
M_CPD *pResult = rtREFUV_New (m_pPToken, m_pPToken);
unsigned int *pResultArray = (unsigned int*)rtREFUV_CPD_Array (pResult);
unsigned int cElements = UV_CPD_ElementCount (pResult);
for (unsigned int xElement = 0; xElement < cElements; xElement++)
pResultArray[xElement] = xElement;
return pResult;
}
// State
private:
rtPTOKEN_Handle *m_pPToken;
};
/*******************
***** LINKS *****
*******************/
/*---------------------------------------------------------------------------
* Link are sorted collections of positions. Links are represented by either
* a link constructor or a link or both.
*
* Link Field Descriptions:
* m_pConstructor - the address of a link constructor or Nil.
* m_pContainer - the address of a link CPD or Nil.
*
*---------------------------------------------------------------------------
*/
/********************************
* Link CPD and R-Type Access *
********************************/
/*---------------------------------------------------------------------------
***** Macro to return a standard CPD for a 'Link'.
*
* Arguments:
* link - the link to be converted into a
* container.
*
* Syntactic Context:
* M_CPD *Expression - a CPD for an instance of the least
* general R-Type required to represent this
* value. This CPD must be freed when no
* longer needed.
*
* Notes:
* The semantics of descriptor links requires that this macro
* manufacture a new container to hold the link. With a suitable
* change in P-Token, that container may be used to instantiate a new
* V-Store (provided the container returned is NOT a reference u-vector).
*
*****/
/*---------------------------------------------------------------------------
***** Macro to return the R-Type of the 'Link' component of a descriptor.
*
* Arguments:
* link - the link whose R-Type is desired.
*
* Syntactic Context:
* RTYPE_Type Expression
*
*****/
/************************
* Link P-Token Query *
************************/
/*---------------------------------------------------------------------------
***** Macro to obtain a reference (i.e., CPD/Index pair) to the positional
***** P-Token of a link.
*
* Arguments:
* link - the link whose positional P-Token is
* desired.
* pPTokenRef/Index - 'lval's which will be set to a CPD and index
* pair referencing the POP of the positional
* P-Token of 'link'. 'pPTokenRef' must
* be freed when no longer needed.
*
* Syntactic Context:
* Compound Statement
*
*****/
/*---------------------------------------------------------------------------
***** Macro to obtain a reference (i.e., CPD/Index pair) to the referential
***** P-Token of a link.
*
* Arguments:
* link - the link whose referential P-Token is
* desired.
* pPTokenRef/Index - 'lval's which will be set to a CPD and index
* pair referencing the POP of the referential
* P-Token of 'link'. 'pPTokenRef' must
* be freed when no longer needed.
*
* Syntactic Context:
* Compound Statement
*
*****/
/*****************************
* Link Realization Macros *
*****************************/
/*---------------------------------------------------------------------------
***** Macro to make the 'linkc' of the link present.
*
* Arguments:
* link - the link whose 'linkc' is to be
* made present.
*
* Syntactic Context:
* Compound Statement
*
*****/
/*---------------------------------------------------------------------------
***** Macro to make the 'linkCPD' of the link present.
*
* Arguments:
* link - the link whose 'linkCPD' is to be
* made present.
*
* Syntactic Context:
* Compound Statement
*
*****/
/********************************
* Link Initialization Macros *
********************************/
/*---------------------------------------------------------------------------
***** Macro to initialize a 'Link'.
*
* Arguments:
* link - the link descriptor to initialize.
* linkc - an optional ('Nil' if absent) link
* constructor which will be
* ASSIGNED into the 'Link'.
* linkCPD - an optional ('Nil' if absent) standard CPD
* for the link which will
* be ASSIGNED into the 'link'.
*
* Syntactic Context:
* Compound Statement
*
* Notes:
* Either the 'linkc', the 'linkCPD', or both must not be 'Nil'.
*
*****/
/*---------------------------------------------------------------------------
***** Macro to initialize a Link from a link constructor and a source
***** Link.
*
* Arguments:
* target - the Link to be initialized.
* linkc - a pointer to a link constructor which will be
* used to extract from the source Link.
* source - the Link to use as the source of the
* extract.
*
* Syntactic Context:
* Compound Statement
*
****/
/*---------------------------------------------------------------------------
***** Macro to initialize a set Reference and an enumeration from a source
***** Link.
*
* Arguments:
* target - the set Reference to be initialized.
* enumeration - an 'lval' of type 'M_CPD*' which will
* be set to a standard CPD for a reference
* u-vector specifying the ordering factored
* from 'source'.
* source - the Link to use as the source of the
* set.
*
* Syntactic Context:
* Compound Statement
*
****/
/******************************************
* Link Duplication and Clearing Macros *
******************************************/
/*---------------------------------------------------------------------------
***** Macro to duplicate a 'Link'
*
* Arguments:
* target - a location whose contents will be replaced
* by the duplicated Link. This location
* is assumed to NOT contain a currently valid
* Link.
* source - a location containing the Link to be
* duplicated.
*
* Syntactic Context:
* Compound Statement
*
*****/
/*---------------------------------------------------------------------------
***** Macro to clear a 'Link'
*
* Arguments:
* link - the Link to be cleared.
*
* Syntactic Context:
* Compound Statement
*
*****/
/***************************
* Link Class Definition *
***************************/
class DSC_Link {
// Construction
public:
void construct (DSC_Link const &rSource) {
if (m_pConstructor = rSource.m_pConstructor)
m_pConstructor->retain ();
if (m_pContainer = rSource.m_pContainer)
m_pContainer->retain ();
}
void construct (M_CPD *pContainer) {
m_pConstructor = NilOf (rtLINK_CType*);
m_pContainer = pContainer;
}
void construct (rtLINK_CType *pConstructor) {
m_pConstructor = pConstructor;
m_pContainer = NilOf (M_CPD*);
}
void constructComposition (rtLINK_CType *pSubscript, DSC_Link const &rSource) {
m_pConstructor = rSource.m_pConstructor
? rSource.m_pConstructor->Extract (pSubscript)
: rtLINK_LCExtract (rSource.m_pContainer, pSubscript);
m_pContainer = NilOf (M_CPD*);
}
// Destruction
public:
void clear () {
if (m_pConstructor) {
m_pConstructor->release ();
m_pConstructor = NilOf (rtLINK_CType*);
}
if (m_pContainer) {
m_pContainer->release ();
m_pContainer = NilOf (M_CPD*);
}
}
// Component Realization
public:
rtLINK_CType *realizedConstructor () {
if (!m_pConstructor)
m_pConstructor = rtLINK_ToConstructor (rtLINK_Align (m_pContainer));
return m_pConstructor;
}
M_CPD *realizedContainer () {
if (!m_pContainer)
m_pContainer = m_pConstructor->Align ()->ToLink (false);
return m_pContainer;
}
// Access
public:
unsigned int cardinality () const {
return m_pConstructor ? m_pConstructor->ElementCount () : rtLINK_CPD_ElementCount (
m_pContainer
);
}
rtPTOKEN_Handle *PPT () const {
return m_pConstructor ? m_pConstructor->PPT () : static_cast<rtLINK_Handle*>(
m_pContainer->containerHandle ()
)->pptHandle ();
}
rtPTOKEN_Handle *RPT () const {
return m_pConstructor ? m_pConstructor->RPT () : static_cast<rtLINK_Handle*>(
m_pContainer->containerHandle ()
)->rptHandle ();
}
static RTYPE_Type RType () {
return RTYPE_C_Link;
}
operator rtLINK_CType* () {
return realizedConstructor ();
}
rtLINK_CType *operator-> () {
return realizedConstructor ();
}
// Container Creation
public:
M_CPD *asContainer (rtPTOKEN_Handle *pPPT) const {
return m_pConstructor
? m_pConstructor->Align ()->ToLink (pPPT, false)
: rtLINK_Copy (m_pContainer, pPPT);
}
M_CPD *asUVector () const {
return m_pConstructor ? m_pConstructor->ToRefUV () : rtLINK_LinkToRefUV (
m_pContainer
);
}
// Use
public:
rtLINK_CType *Extract (rtLINK_CType *pSubscript) const {
return m_pConstructor ? m_pConstructor->Extract (pSubscript) : rtLINK_LCExtract (
m_pContainer, pSubscript
);
}
M_CPD *Extract (M_CPD *pSubscript) const {
return m_pConstructor ? m_pConstructor->Extract (pSubscript) : rtLINK_UVExtract (
m_pContainer, pSubscript
);
}
// State
protected:
rtLINK_CType *m_pConstructor;
M_CPD *m_pContainer;
};
/************************
***** REFERENCES *****
************************/
/*---------------------------------------------------------------------------
* References are explicitly ordered collections of positions. References have
* multiple, concurrently saved representations to afford different algorithms
* the different perspectives on references they require. All components of a
* reference are optional; however, not all components can be missing.
*
* Reference Field Descriptions:
* m_pValues - a standard reference U-Vector CPD enumerating
* the positions referenced by this reference.
* m_pReordering - a standard reference U-Vector CPD specifying
* how the elements selected by 'm_pSubset' should
* be reordered. In the absence of 'm_pSubset',
* 'm_pReordering' and 'positions' are
* synonomous.
* m_pRedistribution - a standard reference U-Vector CPD specifying
* how the elements selected by 'm_pSubset' should
* be redistributed.
* m_pSubset - a link constructor enumerating in optimal
* (i.e., positional) order the positions
* referenced by this reference.
*---------------------------------------------------------------------------
*/
/*************************************
* Reference CPD and R-Type Access *
*************************************/
/*---------------------------------------------------------------------------
***** Macro to return a standard CPD for a 'Reference'.
*
* Arguments:
* reference - the reference to be converted into a
* container.
* cpd - an 'lval' of type 'M_CPD*' which will
* be set to a CPD for an instance of the least
* general R-Type required to represent this
* reference. This CPD must be freed when no
* longer needed.
*
* Syntactic Context:
* Compound Statement
*
* Notes:
* The semantics of descriptor references requires that this macro
* manufacture a new container to hold the reference. With a suitable
* change in P-Token, that container may be used to instantiate a new
* V-Store (provided the container returned is NOT a reference u-vector).
*
*****/
/*---------------------------------------------------------------------------
***** Macro to return the R-Type of a 'Reference'.
*
* Arguments:
* reference - the reference whose R-Type is desired.
*
* Syntactic Context:
* RType_Type Expression
*
*****/
/*****************************
* Reference P-Token Query *
*****************************/
/*---------------------------------------------------------------------------
***** Macro to obtain a reference (i.e., CPD/Index pair) to the positional
***** P-Token of a reference.
*
* Arguments:
* reference - the reference whose positional P-Token is
* desired.
* pPTokenRef/Index - 'lval's which will be set to a CPD and index
* pair referencing the POP of the positional
* P-Token of 'reference'. 'pPTokenRef' must
* be freed when no longer needed.
*
* Syntactic Context:
* Compound Statement
*
*****/
/*---------------------------------------------------------------------------
***** Macro to obtain a reference (i.e., CPD/Index pair) to the referential
***** P-Token of a reference.
*
* Arguments:
* reference - the reference whose referential P-Token is
* desired.
* pPTokenRef/Index - 'lval's which will be set to a CPD and index
* pair referencing the POP of the referential
* P-Token of 'reference'. 'pPTokenRef' must
* be freed when no longer needed.
*
* Syntactic Context:
* Compound Statement
*
*****/
/**********************************
* Reference Realization Macros *
**********************************/
/*---------------------------------------------------------------------------
***** Macro to make the 'values' uvector of the reference present.
*
* Arguments:
* reference - the reference whose 'values' are to be
* made present.
*
* Syntactic Context:
* Compound Statement
*
*****/
/*---------------------------------------------------------------------------
***** Macro to make the 'Redistribution' u-vector of a reference present.
*
* Arguments:
* reference - the reference whose 'm_pRedistribution'
* is to be made present.
*
* Syntactic Context:
* Compound Statement
*
*****/
/*************************************
* Reference Initialization Macros *
*************************************/
/*---------------------------------------------------------------------------
***** General macro to initialize a Reference.
*
* Arguments:
* reference - the reference to be initialized.
* values - an optional ('Nil' if absent) standard CPD
* for the 'm_pValues' reference u-vector of the
* reference. Will be ASSIGNED directly into
* the reference.
* reordering - an optional ('Nil' if absent) standard CPD
* for the 'm_pReordering' component of a
* Reference. Will be ASSIGNED directly into
* the reference.
* redistribution - an optional ('Nil' if absent) standard CPD
* for the 'm_pRedistribution' component of a
* Reference. Will be ASSIGNED directly into
* the reference.
* subset - an optional ('Nil' if absent) link
* constructor pointer for the 'm_pSubset'
* component of the Reference. Will be ASSIGNED
* directly into the reference.
*
* Syntactic Context:
* Compound Statement
*
*****/
/*---------------------------------------------------------------------------
***** Macro to initialize a Reference from a link constructor and a source
***** Reference.
*
* Arguments:
* target - the Reference to be initialized.
* linkc - a pointer to a link constructor which will be
* used to extract from the source Reference.
* source - the Reference to use as the source of the
* extract.
*
* Syntactic Context:
* Compound Statement
*
****/
/*---------------------------------------------------------------------------
***** Macro to initialize a Reference from a reference uvector and a source
***** Reference.
*
* Arguments:
* target - the Reference to be initialized.
* cpd - a standard CPD for a reference uvector
* which will be used to extract from the
* source Reference.
* source - the Reference to use as the source of the
* extract.
*
* Syntactic Context:
* Compound Statement
*
****/
/*---------------------------------------------------------------------------
***** Macro to initialize a Reference from a reference uvector and a source
***** Link.
*
* Arguments:
* target - the Reference to be initialized.
* cpd - a standard CPD for a reference uvector which
* will be used to extract from the source Link.
* source - the Link to use as the source of the
* extract.
*
* Syntactic Context:
* Compound Statement
*
****/
/*---------------------------------------------------------------------------
***** Macro to initialize a set Reference and an enumeration from a source
***** Reference.
*
* Arguments:
* target - the set Reference to be initialized.
* enumeration - an 'lval' of type 'M_CPD*' which will
* be set to a standard CPD for a reference
* u-vector specifying the ordering factored
* from 'source'.
* source - the Reference to use as the source of the
* set.
*
* Syntactic Context:
* Compound Statement
*
****/
/***********************************************
* Reference Duplication and Clearing Macros *
***********************************************/
/*---------------------------------------------------------------------------
***** Macro to duplicate a 'Reference'
*
* Arguments:
* target - a location whose contents will be replaced
* by the duplicated Reference. This location
* is assumed to NOT contain a currently valid
* Reference.
* source - a location containing the Reference to be
* duplicated.
*
* Syntactic Context:
* Compound Statement
*
*****/
/*---------------------------------------------------------------------------
***** Macros to clear parts of a 'Reference'
*
* Argument:
* reference - the reference whose component(s) are to be
* cleared.
*
* Syntactic Context:
* Compound Statement
*
*****/
/*---------------------------------------------------------------------------
***** Macro to clear a 'Reference'
*
* Arguments:
* reference - the Reference to be cleared.
*
* Syntactic Context:
* Compound Statement
*
*****/
/*************************************************
* Reference Factoring and Distribution Macros *
*************************************************/
/*---------------------------------------------------------------------------
***** Macro to factor a reference into its 'Subset' and 'Redistribution'
***** components.
*
* Arguments:
* reference - the reference to be factored.
* linkc - an 'lval' of type 'rtLINK_CType*' which
* will be set to the 'Subset' of the Reference.
* cpd - an 'lval' of type 'M_CPD*' which will
* be set to the 'Redistribution' of the
* Reference.
*
* Syntactic Context:
* Compound Statement
*
*****/
/*---------------------------------------------------------------------------
***** Macro to distribute a 'Reference'
*
* Arguments:
* reference - the Reference to be 'distributed'.
* cpd - a standard CPD for a reference u-vector
* specifying the 'distribution' to be
* applied to Reference.
*
* Syntactic Context:
* Compound Statement
*
*****/
/********************************
* Reference Class Definition *
********************************/
class DSC_Reference {
// Exception Generation
protected:
enum ExceptionSource {
ExceptionSource_Distribute,
ExceptionSource_Factor,
ExceptionSource_GetPPTReference,
ExceptionSource_GetRPTReference,
ExceptionSource_RealizeValues
};
void raiseMissingComponentException (ExceptionSource xExceptionSource) const;
// Construction/Initialization
public:
void construct (DSC_Reference const &rSource) {
*this = rSource;
if (m_pValues)
m_pValues->retain ();
if (m_pReordering)
m_pReordering->retain ();
if (m_pRedistribution)
m_pRedistribution->retain ();
if (m_pSubset)
m_pSubset->retain ();
}
void construct (M_CPD *pValues) {
m_pValues = pValues;
m_pReordering = m_pRedistribution = NilOf (M_CPD*);
m_pSubset = NilOf (rtLINK_CType*);
}
void construct (M_CPD *pDistribution, rtLINK_CType *pSubset) {
m_pValues = m_pReordering = NilOf (M_CPD*);
m_pRedistribution = pDistribution;
m_pSubset = pSubset;
}
void constructComposition (rtLINK_CType *pSubscript, DSC_Reference &rSource) {
m_pValues = rtREFUV_LCExtract (rSource, pSubscript);
m_pReordering = 0;
m_pRedistribution = 0;
m_pSubset = 0;
}
void constructComposition (M_CPD *pSubscript, DSC_Reference &rSource) {
m_pValues = rtREFUV_UVExtract (rSource, pSubscript);
m_pReordering = 0;
m_pRedistribution = 0;
m_pSubset = 0;
}
void constructComposition (M_CPD *pSubscript, DSC_Link const &rSource) {
m_pValues = rSource.Extract (pSubscript);
m_pReordering = 0;
m_pRedistribution = 0;
m_pSubset = 0;
}
void constructSet (
M_ASD *pContainerSpace, M_CPD *&rpEnumeration, DSC_Identity const &rSource
) {
m_pValues = 0;
m_pReordering = 0;
m_pRedistribution = 0;
m_pSubset = 0;
M_CPD *refuv = rSource.asUVector ();
rtREFUV_ToSetUV (pContainerSpace, refuv, &m_pValues, &rpEnumeration);
refuv->release ();
}
void constructSet (
M_ASD *pContainerSpace, M_CPD *&rpEnumeration, DSC_Link const &rSource
) {
m_pValues = 0;
m_pReordering = 0;
m_pRedistribution = 0;
m_pSubset = 0;
M_CPD *refuv = rSource.asUVector ();
rtREFUV_ToSetUV (pContainerSpace, refuv, &m_pValues, &rpEnumeration);
refuv->release ();
}
void constructSet (
M_ASD *pContainerSpace, M_CPD *&rpEnumeration, DSC_Reference &rSource
) {
m_pValues = 0;
m_pReordering = 0;
m_pRedistribution = 0;
m_pSubset = 0;
rtREFUV_ToSetUV (pContainerSpace, rSource, &m_pValues, &rpEnumeration);
}
// Destruction
protected:
void clearValues () {
if (m_pValues) {
m_pValues->release ();
m_pValues = NilOf (M_CPD*);
}
}
void clearReordering () {
if (m_pReordering) {
m_pReordering->release ();
m_pReordering = NilOf (M_CPD*);
}
}
void clearRedistribution () {
if (m_pRedistribution) {
m_pRedistribution->release ();
m_pRedistribution = NilOf (M_CPD*);
}
}
void clearSubset () {
if (m_pSubset) {
m_pSubset->release ();
m_pSubset = NilOf (rtLINK_CType*);
}
}
public:
void clear () {
clearValues ();
clearReordering ();
clearRedistribution ();
clearSubset ();
}
// Component Realization
public:
M_CPD *realizedValues () {
if (m_pValues) {
}
else if (m_pRedistribution) {
m_pValues = m_pSubset ? m_pSubset->ToRefUV (
m_pRedistribution
) : rtREFUV_Flip (m_pRedistribution);
}
else if (m_pReordering) {
m_pRedistribution = rtREFUV_Flip (m_pReordering);
m_pValues = m_pSubset->ToRefUV (m_pRedistribution);
}
else raiseMissingComponentException (ExceptionSource_RealizeValues);
return m_pValues;
}
// Access
public:
unsigned int cardinality () const {
return UV_CPD_ElementCount (
m_pValues ? m_pValues : m_pRedistribution ? m_pRedistribution : m_pReordering
);
}
rtPTOKEN_Handle *PPT () const {
rtPTOKEN_Handle *pResult = 0;
if (m_pValues) {
pResult = static_cast<rtUVECTOR_Handle*>(m_pValues->containerHandle ())->pptHandle ();
}
else if (m_pRedistribution) {
pResult = static_cast<rtUVECTOR_Handle*>(m_pRedistribution->containerHandle ())->rptHandle ();
}
else if (m_pReordering) {
pResult = static_cast<rtUVECTOR_Handle*>(m_pReordering->containerHandle ())->pptHandle ();
}
else {
raiseMissingComponentException (ExceptionSource_GetPPTReference);
}
return pResult;
}
rtPTOKEN_Handle *RPT () const {
rtPTOKEN_Handle *pResult = 0;
if (m_pSubset) {
pResult = m_pSubset->RPT ();
}
else if (m_pValues) {
pResult = static_cast<rtUVECTOR_Handle*>(m_pValues->containerHandle ())->rptHandle ();
}
else if (m_pRedistribution) {
pResult = static_cast<rtUVECTOR_Handle*>(m_pRedistribution->containerHandle ())->pptHandle ();
}
else {
raiseMissingComponentException (ExceptionSource_GetRPTReference);
}
return pResult;
}
static RTYPE_Type RType () {
return RTYPE_C_RefUV;
}
operator M_CPD * () {
return realizedValues ();
}
M_CPD *operator-> () {
return realizedValues ();
}
// Container Creation
public:
M_CPD *asContainer (rtPTOKEN_Handle *pPPT) {
return UV_BasicCopy (realizedValues (), pPPT);
}
// Modification
public:
M_CPD *factor (rtLINK_CType **ppLink) {
if (m_pRedistribution) {
}
else if (m_pReordering)
m_pRedistribution = rtREFUV_Flip (m_pReordering);
else if (m_pValues) {
clearSubset ();
m_pSubset = rtLINK_RefUVToConstructor (m_pValues, &m_pRedistribution);
}
else
raiseMissingComponentException (ExceptionSource_Factor);
if (m_pSubset)
m_pSubset->retain ();
*ppLink = m_pSubset;
if (m_pRedistribution)
m_pRedistribution->retain ();
return m_pRedistribution;
}
void distribute (M_CPD *pDistribution) {
if (m_pRedistribution) {
M_CPD *newuv = rtREFUV_UVExtract (pDistribution, m_pRedistribution);
clearRedistribution ();
m_pRedistribution = newuv;
clearReordering ();
clearValues ();
}
else if (m_pReordering) {
M_CPD *newuv = rtREFUV_Distribute (m_pReordering, pDistribution);
clearRedistribution ();
m_pRedistribution = newuv;
clearReordering ();
clearValues ();
}
else if (m_pValues) {
M_CPD *newuv = rtREFUV_Distribute (pDistribution, m_pValues);
clear ();
m_pValues = newuv;
}
else raiseMissingComponentException (ExceptionSource_Distribute);
}
// State
protected:
M_CPD *m_pValues;
M_CPD *m_pReordering;
M_CPD *m_pRedistribution;
rtLINK_CType *m_pSubset;
};
/***********************************
***** Pointer Access Macros *****
***********************************/
/*********************************
* Pointer Direct State Access *
*********************************/
#define DSC_Pointer_Type(pointer) ((pointer).m_xType)
#define DSC_Pointer_Content(pointer) ((pointer).m_iContent)
#define DSC_Pointer_Scalar(pointer) (DSC_Pointer_Content(pointer).as_iScalar)
#define DSC_Pointer_Scalar_Char(pointer)\
DSC_Scalar_Char (DSC_Pointer_Scalar (pointer))
#define DSC_Pointer_Scalar_Double(pointer)\
DSC_Scalar_Double (DSC_Pointer_Scalar (pointer))
#define DSC_Pointer_Scalar_Float(pointer)\
DSC_Scalar_Float (DSC_Pointer_Scalar (pointer))
#define DSC_Pointer_Scalar_Int(pointer)\
DSC_Scalar_Int (DSC_Pointer_Scalar (pointer))
#define DSC_Pointer_Scalar_Unsigned64(pointer)\
DSC_Scalar_Unsigned64 (DSC_Pointer_Scalar (pointer))
#define DSC_Pointer_Scalar_Unsigned96(pointer)\
DSC_Scalar_Unsigned96 (DSC_Pointer_Scalar (pointer))
#define DSC_Pointer_Scalar_Unsigned128(pointer)\
DSC_Scalar_Unsigned128 (DSC_Pointer_Scalar (pointer))
#define DSC_Pointer_Value(pointer) (DSC_Pointer_Content(pointer).as_iValue)
#define DSC_Pointer_Identity(pointer) (DSC_Pointer_Content(pointer).as_iIdentity)
#define DSC_Pointer_Link(pointer) (DSC_Pointer_Content(pointer).as_iLink)
#define DSC_Pointer_Reference(pointer) (DSC_Pointer_Content(pointer).as_iReference)
/****************************************************************
* Pointer Content Predicates and Derived State Access Macros *
****************************************************************/
/***********************************
* Pointer CPD and R-Type Access *
***********************************/
/*---------------------------------------------------------------------------
***** Macro to return a standard CPD for a 'Pointer'.
*
* Arguments:
* pointer - the pointer to be converted into a container.
* cpd - an 'lval' of type 'M_CPD*' which will
* be set to a CPD for an instance of the least
* general R-Type required to represent this
* pointer. This CPD must be freed when no
* longer needed.
*
* New Identity:
* M_CPD *DSC_Pointer::pointerCPD ()
*
* Notes:
* The semantics of descriptor pointers requires that this macro return
* a container distinct from the one used to internally represent the
* pointer. As a consequence, each application of this macro to a
* pointer will produce a new instance representing the descriptor.
* With a suitable change in P-Token, that container may be used to
* instantiate a new V-Store (provided the container returned is NOT
* a reference u-vector).
*
*****/
/*---------------------------------------------------------------------------
***** Macro to return the R-Type of the 'Pointer' component of a descriptor.
*
* Arguments:
* pointer - the descriptor whose store CPD is desired.
* rtype - an 'lval' of type 'RTYPE_Type' which will
* be set to the least general R-Type required
* to represent the pointer component of this
* descriptor.
*
* Syntactic Context:
* RTYPE_Type pointerRType () const
*
*****/
/***************************
* Pointer P-Token Query *
***************************/
/*---------------------------------------------------------------------------
***** Macro to obtain a reference (i.e., CPD/Index pair) to the positional
***** P-Token of a pointer.
*
* Arguments:
* pointer - the pointer whose positional P-Token is
* desired.
* pPTokenRef/Index - 'lval's which will be set to a CPD and index
* pair referencing the POP of the positional
* P-Token of 'pointer'. 'pPTokenRef' must be
* freed when no longer needed.
*
* Syntactic Context:
* Compound Statement
*
*****/
/*---------------------------------------------------------------------------
***** Macro to obtain a reference (i.e., CPD/Index pair) to the referential
***** P-Token of a pointer.
*
* Arguments:
* pointer - the pointer whose referential P-Token is
* desired.
* pPTokenRef/Index - 'lval's which will be set to a CPD and index
* pair referencing the POP of the referential
* P-Token of 'pointer'. 'pPTokenRef' must be
* freed when no longer needed.
*
* Syntactic Context:
* Compound Statement
*
*****/
/******************************************
***** Pointer Management Utilities *****
******************************************/
/***********************************
* Pointer Initialization Macros *
***********************************/
/*---------------------------------------------------------------------------
***** Macros to initialize various flavors of value scalar pointer.
*
* Arguments:
* pointer - the Pointer to initialize.
* pPPT - the position P-Token of 'pointer'.
* pRPT - a standard CPD for the reference P-Token of
* the scalar. Will be ASSIGNED directly into
* the scalar pointer.
* value - the value of the scalar. This parameter is
* omitted for undefined scalars.
*
* Syntactic Context:
* Compound Statement
*
*****/
/*---------------------------------------------------------------------------
***** Macro to initialize a pointer with a U-Vector element.
*
* Arguments:
* pointer - the pointer to initialize.
* uvector - a standard CPD for the u-vector supplying
* the element.
* subscript - the subscript of the u-vector element to be
* installed in this pointer.
*
* Syntactic Context:
* Compound Statement
*
*****/
/*---------------------------------------------------------------------------
***** Macro to initialize a 'Value' pointer.
*
* Arguments:
* pointer - the Pointer to be initialized.
* cpd - a standard CPD for the U-Vector to be
* installed in the Value. Will be ASSIGNED
* directly into the value.
*
* Syntactic Context:
* Compound Statement
*
*****/
/*---------------------------------------------------------------------------
***** Macro to initialize an 'Identity' pointer.
*
* Arguments:
* pointer - the Pointer to be initialized.
* pToken - a handle for the P-Token denoting the identity.
*
* Syntactic Context:
* See DSC_Pointer::constructIdentity (rtPTOKEN_Handle *pPToken)
*
*****/
/*---------------------------------------------------------------------------
***** Macro to initialize a 'Link' Pointer.
*
* Arguments:
* pointer - the pointer to initialize.
* linkc - an optional ('Nil' if absent) link
* constructor which will be
* ASSIGNED into the 'Link'.
* linkCPD - an optional ('Nil' if absent) standard CPD
* for the link which will
* be ASSIGNED into the 'link'.
*
* Syntactic Context:
* Compound Statement
*
* Notes:
* Either the 'linkc', the 'linkCPD', or both must not be 'Nil'.
*
*****/
/*---------------------------------------------------------------------------
***** General macro to initialize a Reference Pointer.
*
* Arguments:
* pointer - the Pointer to be initialized.
* values - an optional ('Nil' if absent) standard CPD
* for the 'm_pValues' reference u-vector of the
* reference. Will be ASSIGNED directly into
* the reference pointer.
* reordering - an optional ('Nil' if absent) standard CPD
* for the 'm_pReordering' component of a
* Reference. Will be ASSIGNED directly into
* the reference pointer.
* redistribution - an optional ('Nil' if absent) standard CPD
* for the 'm_pRedistribution' component of a
* Reference. Will be ASSIGNED directly into
* the reference pointer.
* subset - an optional ('Nil' if absent) link
* constructor pointer for the 'm_pSubset'
* component of the Reference. Will be ASSIGNED
* directly into the reference pointer.
*
* Syntactic Context:
* Compound Statement
*
*****/
/******************************************************
* Macro to Initialize a Pointer from a Pointer CPD *
******************************************************/
/*---------------------------------------------------------------------------
***** Macro to initialize a pointer from a pointer CPD.
*
* Arguments:
* pointer - the pointer to be initialized.
* cpd - a CPD for a pointer container (i.e., link
* or u-vector) which will be used to initialize
* the descriptor. Unlike other macros which
* always ASSIGN their CPD arguments into a
* descriptor, this macro reserves the right
* NOT to assign this CPD into the descriptor
* it initializes. As a consequence, this
* macro will duplicate this CPD pointer
* itself if it needs to keep a CPD for this
* container.
*
* New Identity:
* DSC_Pointer::construct (M_CPD *pMonotype)
*
*****/
/*---------------------------------------------------------------------------
***** Macro to initialize a pointer from a link constructor and a source
***** pointer.
*
* Arguments:
* target - the pointer to be initialized.
* linkc - a pointer to a link constructor which will be
* used to extract from the source pointer.
* source - the pointer to use as the source of the
* extract.
*
* Syntactic Context:
* See DSC_Pointer::constructComposition (rtLINK_CType*, DSC_Pointer const&)
*
****/
/*---------------------------------------------------------------------------
***** Macro to initialize a pointer from a reference uvector and a source
***** pointer.
*
* Arguments:
* target - the pointer to be initialized.
* cpd - a pointer to a reference uvector which will
* be used to extract from the source pointer.
* source - the pointer to use as the source of the
* extract.
*
* Syntactic Context:
* See DSC_Pointer::constructComposition (M_CPD*, DSC_Descriptor const&)
*
****/
/*---------------------------------------------------------------------------
***** Macro to initialize a pointer from a reference and a source
***** pointer.
*
* Arguments:
* target - the pointer to be initialized.
* ref - a pointer to a object of type:
* 'rtREFUV_Type_Reference' which will be
* used to extract from the source pointer.
* source - the pointer to use as the source of the
* extract.
*
* Syntactic Context:
* See DSC_Pointer::constructComposition (DSC_Scalar&, DSC_Descriptor const&)
*
****/
/*---------------------------------------------------------------------------
***** Macro to initialize a pointer from a 'Pointer' and a source
***** pointer.
*
* Arguments:
* target - the pointer to be initialized.
* pointer - a Pointer which will be used to extract
* from the source pointer.
* source - the pointer to use as the source of the
* extract.
*
* Syntactic Context:
* See DSC_Pointer::constructComposition (DSC_Pointer&, DSC_Descriptor const&)
*
****/
/*---------------------------------------------------------------------------
***** Macro to initialize a set pointer and an enumeration from a source
***** pointer.
*
* Arguments:
* target - the set pointer to be initialized.
* enumeration - an 'lval' of type 'M_CPD*' which will
* be set to a standard CPD for a reference
* u-vector specifying the ordering factored
* from 'source'.
* source - the pointer to use as the source of the
* set.
*
* Syntactic Context:
* Compound Statement
*
****/
/*********************************************
* Pointer Duplication And Clearing Macros *
*********************************************/
/*-----------------------------------------------------------------------
***** Macro to duplicate a 'Pointer'
*
* Arguments:
* target - a location whose contents will be replace
* by the duplicated Pointer. This location
* is assumed to NOT contain a currently valid
* Pointer.
* source - a location containing the Pointer to be
* duplicated.
*
* New Identity:
* DSC_Pointer::construct (DSC_Pointer const &rSource)
*
*****/
/************************************************************
* Pointer Factoring, Distribution, and Reordering Macros *
************************************************************/
/*---------------------------------------------------------------------------
***** Macro to factor a Pointer.
*
* Arguments:
* pointer - the pointer to factor.
* cpd - an 'lval' of type 'M_CPD*' which
* be set to either 'Nil' if no 'distribution'
* can be factored from this pointer (i.e., the
* Pointer is not a Reference Pointer) or a
* standard CPD for a reference u-vector which
* contains the distribution factored from a
* 'Reference' Pointer.
*
*****/
/*---------------------------------------------------------------------------
***** Macro to distribute a 'Pointer'
*
* Arguments:
* pointer - the Pointer to be 'distributed'.
* cpd - a standard CPD for a reference u-vector
* specifying the 'distribution' to be
* applied to Pointer.
*
* New Identity:
* void DSC_Pointer::distribute (M_CPD *distribution)
*
*****/
/*---------------------------------------------------------------------------
***** Macro to reorder a 'Pointer'
*
* Arguments:
* pointer - the Pointer to be 'reordered'.
* reordering - a standard CPD for a reference u-vector
* specifying the 'reordering' to be
* applied to Pointer.
*
* New Identity:
* void DSC_Pointer::reorder (M_CPD *reordering)
*
*****/
/*************************
* U-Vector Assignment *
*************************/
/***** Macro to Assign values to a U-Vector given a link constructor and a
***** Pointer.
*
* Arguments:
* uvector - the address of a standard CPD for the U-Vector
* to be modified.
* linkc - an address of a link constructor specifying the
* elements in the U-Vector to be modified.
* pointer - the Pointer supplying the source values for
* the assign.
*
*****/
/**************************************
* Macro To Coerce a Scalar Pointer *
**************************************/
/*---------------------------------------------------------------------------
***** Macro to coerce a Scalar Pointer.
*
* Arguments:
* pointer - the pointer to be coerced. MUST be a
* scalar pointer.
* pPPT - the new positional ptoken (Not Assigned).
*
* New Identity:
* void DSC_Pointer::coerce (rtPTOKEN_Handle *pPPT)
*
*****/
/*---------------------------------------------------------------------------
***** Macro to determine if the pointer is a coerced Scalar Pointer.
*
* Arguments:
* pointer - the pointer to be checked.
* result - an integer to be set to either true or false.
*
* Syntactic Context:
* Compound Statement
*
*****/
/**********************
* Class Definition *
**********************/
class DSC_Pointer {
// Construction
public:
void construct () {
m_xType = DSC_PointerType_Empty;
}
void construct (M_CPD *pMonotype);
void construct (rtLINK_CType *pMonotype);
void construct (DSC_Pointer const &rSource);
void constructComposition (rtLINK_CType *pSubscript, DSC_Pointer &rSource);
void constructComposition (M_CPD *pSubscript, DSC_Pointer &rSource);
void constructComposition (DSC_Scalar &rSubscript, DSC_Pointer &rSource);
void constructComposition (DSC_Pointer &rSubscript, DSC_Pointer &rSource);
void constructSet (
M_ASD *pContainerSpace, M_CPD *&rpEnumeration, DSC_Pointer &rSource
);
void constructCorrespondence (rtPTOKEN_Handle *pPPT, Vdd::Store *pStore);
void constructIdentity (rtPTOKEN_Handle *pPToken) {
m_iContent.as_iIdentity.construct (pPToken);
m_xType = DSC_PointerType_Identity;
}
void constructLink (M_CPD *pLink) {
m_iContent.as_iLink.construct (pLink);
m_xType = DSC_PointerType_Link;
}
void constructLink (rtLINK_CType *pLink) {
m_iContent.as_iLink.construct (pLink);
m_xType = DSC_PointerType_Link;
}
void constructReference (M_CPD *pValues) {
m_iContent.as_iReference.construct (pValues);
m_xType = DSC_PointerType_Reference;
}
void constructReference (M_CPD *pDistribution, rtLINK_CType *pSubset) {
m_iContent.as_iReference.construct (pDistribution, pSubset);
m_xType = DSC_PointerType_Reference;
}
void constructValue (M_CPD *pValue) {
m_iContent.as_iValue.construct (pValue);
m_xType = DSC_PointerType_Value;
}
void constructScalarComposition (unsigned int xSubscript, M_CPD *pSource) {
m_iContent.as_iScalar.constructComposition (xSubscript, pSource);
m_xType = DSC_PointerType_Scalar;
}
void constructScalarComposition (unsigned int xSubscript, VContainerHandle *pSource) {
m_iContent.as_iScalar.constructComposition (xSubscript, pSource);
m_xType = DSC_PointerType_Scalar;
}
void constructScalar (DSC_Scalar const &rValue) {
m_iContent.as_iScalar = rValue;
m_xType = DSC_PointerType_Scalar;
}
void constructConstant (rtPTOKEN_Handle *pPPT, DSC_Scalar const &rValue) {
constructScalar (rValue);
coerce (pPPT);
}
void constructScalar (rtPTOKEN_Handle *pRPT) {
m_iContent.as_iScalar.constructValue (pRPT);
m_xType = DSC_PointerType_Scalar;
}
void constructScalar (M_KOTE const &rKOTE) {
constructScalar (rKOTE.PTokenHandle ());
}
void constructConstant (rtPTOKEN_Handle *pPPT, rtPTOKEN_Handle *pRPT) {
constructScalar (pRPT);
coerce (pPPT);
}
void constructConstant (rtPTOKEN_Handle *pPPT, M_KOTE const &rKOTE) {
constructScalar (rKOTE);
coerce (pPPT);
}
void constructScalar (rtPTOKEN_Handle *pRPT, char iValue) {
m_iContent.as_iScalar.constructValue (pRPT, iValue);
m_xType = DSC_PointerType_Scalar;
}
void constructScalar (M_KOTE const &rKOTE, char iValue) {
constructScalar (rKOTE.PTokenHandle (), iValue);
}
void constructScalar (M_KOT *pKOT, char iValue) {
constructScalar (pKOT->TheCharacterClass, iValue);
}
void constructConstant (rtPTOKEN_Handle *pPPT, rtPTOKEN_Handle *pRPT, char iValue) {
constructScalar (pRPT, iValue);
coerce (pPPT);
}
void constructConstant (rtPTOKEN_Handle *pPPT, M_KOTE const &rKOTE, char iValue) {
constructScalar (rKOTE, iValue);
coerce (pPPT);
}
void constructConstant (rtPTOKEN_Handle *pPPT, M_KOT *pKOT, char iValue) {
constructConstant (pPPT, pKOT->TheCharacterClass, iValue);
}
void constructScalar (rtPTOKEN_Handle *pRPT, double iValue) {
m_iContent.as_iScalar.constructValue (pRPT, iValue);
m_xType = DSC_PointerType_Scalar;
}
void constructScalar (M_KOTE const &rKOTE, double iValue) {
constructScalar (rKOTE.PTokenHandle (), iValue);
}
void constructScalar (M_KOT *pKOT, double iValue) {
constructScalar (pKOT->TheDoubleClass, iValue);
}
void constructConstant (rtPTOKEN_Handle *pPPT, rtPTOKEN_Handle *pRPT, double iValue) {
constructScalar (pRPT, iValue);
coerce (pPPT);
}
void constructConstant (rtPTOKEN_Handle *pPPT, M_KOTE const &rKOTE, double iValue) {
constructScalar (rKOTE, iValue);
coerce (pPPT);
}
void constructConstant (rtPTOKEN_Handle *pPPT, M_KOT *pKOT, double iValue) {
constructConstant (pPPT, pKOT->TheDoubleClass, iValue);
}
void constructScalar (rtPTOKEN_Handle *pRPT, float iValue) {
m_iContent.as_iScalar.constructValue (pRPT, iValue);
m_xType = DSC_PointerType_Scalar;
}
void constructScalar (M_KOTE const &rKOTE, float iValue) {
constructScalar (rKOTE.PTokenHandle (), iValue);
}
void constructScalar (M_KOT *pKOT, float iValue) {
constructScalar (pKOT->TheFloatClass, iValue);
}
void constructConstant (rtPTOKEN_Handle *pPPT, rtPTOKEN_Handle *pRPT, float iValue) {
constructScalar (pRPT, iValue);
coerce (pPPT);
}
void constructConstant (rtPTOKEN_Handle *pPPT, M_KOTE const &rKOTE, float iValue) {
constructScalar (rKOTE, iValue);
coerce (pPPT);
}
void constructConstant (rtPTOKEN_Handle *pPPT, M_KOT *pKOT, float iValue) {
constructConstant (pPPT, pKOT->TheFloatClass, iValue);
}
void constructScalar (rtPTOKEN_Handle *pRPT, int iValue) {
m_iContent.as_iScalar.constructValue (pRPT, iValue);
m_xType = DSC_PointerType_Scalar;
}
void constructScalar (M_KOTE const &rKOTE, int iValue) {
constructScalar (rKOTE.PTokenHandle (), iValue);
}
void constructScalar (M_KOT *pKOT, int iValue) {
constructScalar (pKOT->TheIntegerClass, iValue);
}
void constructConstant (rtPTOKEN_Handle *pPPT, rtPTOKEN_Handle *pRPT, int iValue) {
constructScalar (pRPT, iValue);
coerce (pPPT);
}
void constructConstant (rtPTOKEN_Handle *pPPT, M_KOTE const &rKOTE, int iValue) {
constructScalar (rKOTE, iValue);
coerce (pPPT);
}
void constructConstant (rtPTOKEN_Handle *pPPT, M_KOT *pKOT, int iValue) {
constructConstant (pPPT, pKOT->TheIntegerClass, iValue);
}
void constructScalar (rtPTOKEN_Handle *pRPT, VkUnsigned64 const &iValue) {
m_iContent.as_iScalar.constructValue (pRPT, iValue);
m_xType = DSC_PointerType_Scalar;
}
void constructConstant (rtPTOKEN_Handle *pPPT, rtPTOKEN_Handle *pRPT, VkUnsigned64 const &iValue) {
constructScalar (pRPT, iValue);
coerce (pPPT);
}
void constructScalar (rtPTOKEN_Handle *pRPT, VkUnsigned96 const &iValue) {
m_iContent.as_iScalar.constructValue (pRPT, iValue);
m_xType = DSC_PointerType_Scalar;
}
void constructConstant (rtPTOKEN_Handle *pPPT, rtPTOKEN_Handle *pRPT, VkUnsigned96 const &iValue) {
constructScalar (pRPT, iValue);
coerce (pPPT);
}
void constructScalar (rtPTOKEN_Handle *pRPT, VkUnsigned128 const &iValue) {
m_iContent.as_iScalar.constructValue (pRPT, iValue);
m_xType = DSC_PointerType_Scalar;
}
void constructConstant (rtPTOKEN_Handle *pPPT, rtPTOKEN_Handle *pRPT, VkUnsigned128 const &iValue) {
constructScalar (pRPT, iValue);
coerce (pPPT);
}
void constructReferenceScalar (rtPTOKEN_Handle *pRPT, unsigned int iValue) {
m_iContent.as_iScalar.constructReference (pRPT, iValue);
m_xType = DSC_PointerType_Scalar;
}
void constructReferenceConstant (rtPTOKEN_Handle *pPPT, rtPTOKEN_Handle *pRPT, unsigned int iValue) {
constructReferenceScalar (pRPT, iValue);
coerce (pPPT);
}
// Access
public:
void assignToUV (rtLINK_CType *pSubscript, M_CPD *pTarget);
unsigned int cardinality () const {
switch (m_xType) {
case DSC_PointerType_Scalar:
return 1;
case DSC_PointerType_Value:
return m_iContent.as_iValue.cardinality ();
case DSC_PointerType_Identity:
return m_iContent.as_iIdentity.cardinality ();
case DSC_PointerType_Link:
return m_iContent.as_iLink.cardinality ();
case DSC_PointerType_Reference:
return m_iContent.as_iReference.cardinality ();
default:
return 0;
}
}
rtPTOKEN_Handle *getPPT () const {
return PPT ();
}
rtPTOKEN_Handle *getRPT () const {
return RPT ();
}
bool isACoercedScalar () const;
RTYPE_Type pointerRType () const;
rtPTOKEN_Handle *PPT () const;
rtPTOKEN_Handle *RPT () const;
DSC_PointerType Type () const {
return m_xType;
}
protected:
void const *valueArrayOfType (RTYPE_Type const xExpectedType) const;
public:
operator char const* () const {
return (char const*)valueArrayOfType (RTYPE_C_CharUV);
}
operator float const* () const {
return (float const*)valueArrayOfType (RTYPE_C_FloatUV);
}
operator double const* () const {
return (double const*)valueArrayOfType (RTYPE_C_DoubleUV);
}
operator int const* () const {
return (int const*)valueArrayOfType (RTYPE_C_IntUV);
}
operator unsigned int const* () const {
return (unsigned int const*)valueArrayOfType (RTYPE_C_IntUV);
}
operator VkUnsigned64 const* () const {
return (VkUnsigned64 const*)valueArrayOfType (RTYPE_C_Unsigned64UV);
}
operator VkUnsigned96 const* () const {
return (VkUnsigned96 const*)valueArrayOfType (RTYPE_C_Unsigned96UV);
}
operator VkUnsigned128 const* () const {
return (VkUnsigned128 const*)valueArrayOfType (RTYPE_C_Unsigned128UV);
}
// Query
public:
bool isEmpty () const {
return m_xType == DSC_PointerType_Empty;
}
bool isntEmpty () const {
return m_xType != DSC_PointerType_Empty;
}
bool isScalar () const {
return m_xType == DSC_PointerType_Scalar;
}
bool isntScalar () const {
return m_xType != DSC_PointerType_Scalar;
}
bool holdsAScalarValue () const {
return isScalar () && m_iContent.as_iScalar.holdsAValue ();
}
bool holdsAScalarReference () const {
return isScalar () && m_iContent.as_iScalar.holdsAReference ();
}
bool holdsNonScalarValues () const {
return m_xType == DSC_PointerType_Value;
}
bool holdsValuesInAnyForm () const {
return holdsAScalarValue () || holdsNonScalarValues ();
}
bool holdsAnIdentity () const {
return m_xType == DSC_PointerType_Identity;
}
bool holdsAScalarIdentity () const {
return holdsAnIdentity () && m_iContent.as_iIdentity.isScalar ();
}
bool holdsALink () const {
return m_xType == DSC_PointerType_Link;
}
bool holdsNonScalarReferences () const {
return m_xType == DSC_PointerType_Reference;
}
// Update
public:
void clear ();
void coerce (rtPTOKEN_Handle *pPPT);
M_CPD *factor ();
void distribute (M_CPD *distribution);
void reorder (M_CPD *reordering);
void setTo (M_CPD *pMonotype) {
clear ();
construct (pMonotype);
}
void setTo (rtLINK_CType *pMonotype) {
clear ();
construct (pMonotype);
}
void setToCopied (DSC_Pointer const& rSource) {
clear ();
construct (rSource);
}
void setToMoved (DSC_Pointer &rSource) {
clear ();
*this = rSource;
rSource.construct ();
}
// Container Creation
public:
M_CPD *pointerCPD (rtPTOKEN_Handle *PPT);
// Returns true if the u-vector must be freed by the caller
bool getUVector (M_CPD *&rpUVector);
M_CPD *asUVector () {
M_CPD *pUVector;
if (getUVector (pUVector))
return pUVector;
pUVector->retain ();
return pUVector;
}
// Exception Generation
public:
void complainAboutBadPointerType (char const* pText) const;
// State
public:
DSC_PointerType m_xType;
union content_t {
DSC_Scalar as_iScalar;
DSC_Value as_iValue;
DSC_Identity as_iIdentity;
DSC_Link as_iLink;
DSC_Reference as_iReference;
} m_iContent;
};
#endif
| true |
8ce46175e133b04e9574ef2ea32ab965ebc208b5 | C++ | Abhinav1997/cpp_playground | /print_enum_names.cpp | UTF-8 | 258 | 2.9375 | 3 | [] | no_license | #include "Axis.hpp"
#include <array>
int main()
{
std::array<Axis, 3> const values { Axes::kX,
Axes::kY,
Axes::kZ };
for (auto&& value : values)
std::cout << value << '\n';
}
| true |
5e82c05314610603bcbee31100a3012d843b57d9 | C++ | cup2of2tea/CompetitiveProgramming | /codeforces/Codeforces_Round_#316_(Div_2)/A_Elections.cpp | ISO-8859-1 | 796 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int N,M;
cin>>N>>M;
vector<vector<int> > v(M,vector<int>(N));
for(int c=0;c<v.size();c++) for(int c2=0;c2<v[c].size();c2++) cin>>v[c][c2];
vector<int> byCities(M,1);
for(int c=0;c<v.size();c++) for(int c2=0;c2<v[c].size();c2++) if(v[c][c2] > v[c][byCities[c]-1]) byCities[c] = c2+1;
sort(byCities.begin(),byCities.end());
int act = 0;
int idAct = -1;
int winner = -1;
int best = 0;
for(int c=0;c<byCities.size();c++)
{
if(idAct == byCities[c]) act++;
else {
idAct = byCities[c];
act=1;
}
if(best < act) {
best = act;
winner = idAct;
}
}
cout<<winner;
} | true |
fc7c629a51dad5503aae42c1ad1dcc3c11cba47e | C++ | geoo993/OpenGLProject | /Modern_Open_GL_Tutorial/Modern_Open_GL_Tutorial/Camera.h | UTF-8 | 8,167 | 2.875 | 3 | [] | no_license | //
// Camera.h
// ModernOpenGL_Basic
//
// Created by GEORGE QUENTIN on 26/02/2017.
// Copyright © 2017 LEXI LABS. All rights reserved.
//
#ifndef Camera_h
#define Camera_h
#include "Common.h"
// Defines several possible options for camera movement. Used as abstraction to stay away from window-system specific input methods
enum CameraMovement
{
FORWARD,
BACKWARD,
LEFT,
RIGHT
};
// Default camera values
const GLfloat YAW = -90.0f;
const GLfloat PITCH = 0.1f;
const GLfloat ROLL = 0.1f;
const GLfloat SPEED = 10.0f;
const GLfloat SENSITIVTY = 0.25f;
const GLfloat ZOOM = 45.0f;
//Camera setup
class Camera{
public:
Camera(){};
virtual ~Camera(){}
void Create(
const glm::vec3 &position = glm::vec3( 0.0f, 0.0f, -15.0f ),
const glm::vec3 &worldUp = glm::vec3( 0.0f, 1.0f, 0.0f ),
const GLfloat &pitch = PITCH,
const GLfloat &yaw = YAW,
const GLfloat &roll = ROLL,
const GLfloat &fieldOfView = 45.0f,
const GLfloat &width = (float)SCREEN_WIDTH,
const GLfloat &height = (float)SCREEN_HEIGHT,
const GLfloat &zNear = 0.1f,
const GLfloat &zFar = 1000.0f) {
this->m_position = position;
this->m_worldUp = worldUp;
this->m_fieldOfView = fieldOfView;
this->SetPerspectiveProjectionMatrix(fieldOfView, (width/height), zNear, zFar);
this->SetOrthographicProjectionMatrix(width,height,zNear, zFar );
this->m_pitch = pitch;
this->m_yaw = yaw;
this->m_roll = roll;
this->m_movementSpeed = SPEED;
this->m_mouseSensitivity = SENSITIVTY;
this->m_zoom = ZOOM;
this->UpdateCameraVectors();
}
void Create(
const glm::vec3 &position,
const glm::vec3 &worldUp,
const GLfloat &fieldOfView,
const GLfloat &width,
const GLfloat &height,
const GLfloat &zNear,
const GLfloat &zFar) {
this->m_position = position;
this->m_worldUp = worldUp;
this->m_fieldOfView = fieldOfView;
this->SetPerspectiveProjectionMatrix(fieldOfView, (width/height), zNear, zFar);
this->SetOrthographicProjectionMatrix(width,height,zNear, zFar );
this->m_pitch = PITCH;
this->m_yaw = YAW;
this->m_roll = ROLL;
this->m_movementSpeed = SPEED;
this->m_mouseSensitivity = SENSITIVTY;
this->m_zoom = ZOOM;
this->UpdateCameraVectors( );
}
void SetPerspectiveProjectionMatrix(const GLfloat &fieldOfView, const GLfloat &aspect, const GLfloat &zNear = 0.1f, const GLfloat &zFar = 5000.0f){
this->m_fieldOfView = fieldOfView;
this->m_perspectiveProjectionMatrix = glm::perspective(fieldOfView, aspect, zNear, zFar);
}
void SetOrthographicProjectionMatrix(const GLfloat &width, const GLfloat height, const GLfloat &zNear = 0.1f, const GLfloat &zFar = 5000.0f){
this->m_orthographicProjectionMatrix = glm::ortho(0.0f, width, 0.0f, height, zNear, zFar);
}
inline glm::mat4 GetViewProjection() const { return this->m_perspectiveProjectionMatrix * this->m_viewMatrix; }
inline glm::mat4 GetPerspectiveProjectionMatrix() const { return this->m_perspectiveProjectionMatrix; }
inline glm::mat4 GetOrthographicProjectionMatrix() const {
return this-> m_orthographicProjectionMatrix; }
inline glm::mat4 GetViewMatrix() const { return this->m_viewMatrix; }
inline glm::vec3 GetPosition() const { return this->m_position; }
inline glm::vec3 GetView() const { return this->m_view; }
inline glm::vec3 GetForward() const { return this->m_front; }
inline glm::vec3 GetUp() const { return this->m_up; }
inline glm::vec3 GetRight() const { return this->m_right; }
inline GLfloat GetZoom( ){ return this->m_zoom; }
// Processes input received from any keyboard-like input system. Accepts input parameter in the form of camera defined ENUM (to abstract it from windowing systems)
void ProcessKeyboard( const CameraMovement &direction, const GLfloat &deltaTime )
{
GLfloat velocity = this->m_movementSpeed * deltaTime;
if ( direction == FORWARD )
{
this->m_position += this->m_front * velocity;
}
if ( direction == BACKWARD )
{
this->m_position -= this->m_front * velocity;
}
if ( direction == LEFT )
{
this->m_position -= this->m_right * velocity;
}
if ( direction == RIGHT )
{
this->m_position += this->m_right * velocity;
}
}
// Processes input received from a mouse input system. Expects the offset value in both the x and y direction.
void ProcessMouseMovement( GLfloat &xOffset, GLfloat &yOffset, GLboolean constrainPitch = true )
{
xOffset *= this->m_mouseSensitivity;
yOffset *= this->m_mouseSensitivity;
this->m_pitch += yOffset; // up down
this->m_yaw += xOffset; //left right
//this->m_roll += yOffset; // up down
// Make sure that when pitch is out of bounds, screen doesn't get flipped
if ( constrainPitch )
{
if ( this->m_pitch > 89.0f )
{
this->m_pitch = 89.0f;
this->m_roll = 0;
}
if ( this->m_pitch < -89.0f )
{
this->m_pitch = -89.0f;
}
}
// Update Front, Right and Up Vectors using the updated Eular angles
this->UpdateCameraVectors( );
}
private:
Camera(const Camera &other){}
void operator=(const Camera &other){}
//view and projection matrix
glm::mat4 m_perspectiveProjectionMatrix;
glm::mat4 m_orthographicProjectionMatrix;
glm::mat4 m_viewMatrix;
// Camera Attributes
glm::vec3 m_view;
glm::vec3 m_position;
glm::vec3 m_front;
glm::vec3 m_back;
glm::vec3 m_left;
glm::vec3 m_right;
glm::vec3 m_up;
glm::vec3 m_down;
glm::vec3 m_worldUp;
// Eular Angles
GLfloat m_fieldOfView;
GLfloat m_yaw;
GLfloat m_pitch;
GLfloat m_roll;
// Camera options
GLfloat m_movementSpeed;
GLfloat m_mouseSensitivity;
GLfloat m_zoom;
// Calculates the front vector from the Camera's (updated) Eular Angles
void UpdateCameraVectors( )
{
// Calculate the new Front vector
glm::vec3 front;
front.x = cos( glm::radians( this->m_yaw ) ) * cos( glm::radians( this->m_pitch ) );
front.y = sin( glm::radians( this->m_pitch ) );
front.z = sin( glm::radians( this->m_yaw ) ) * cos( glm::radians( this->m_pitch ) );
this->m_front = glm::normalize( front );
//this->m_front = glm::vec3(0.0f, 0.0f, 1.0f);
// Also re-calculate the Right and Up vector
this->m_right = glm::normalize( glm::cross( this->m_front, this->m_worldUp ) ); // Normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement.
this->m_up = glm::normalize( glm::cross( this->m_right, this->m_front ) );
//this->m_up = glm::vec3(0.0f, 1.0f, 0.0f);
this->m_view = m_position + m_front;
this->m_viewMatrix = glm::lookAt(
m_position, // what position you want the camera to be at when looking at something in World Space
m_view, // // what position you want the camera to be looking at in World Space, meaning look at what(using vec3) ? // meaning the camera view point
m_up //which direction is up, you can set to (0,-1,0) to look upside-down
);
}
};
#endif /* Camera_h */
| true |
8bbc21f4811e16c3f11d37e6bf70b15c518892ab | C++ | SeanStarkey/map-utilities | /src/IMGUnknownSubfileException.cpp | UTF-8 | 380 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive |
#include "IMGUnknownSubfileException.h"
IMGUnknownSubfileException::IMGUnknownSubfileException(const std::string message_in) : message(message_in) {
}
IMGUnknownSubfileException::~IMGUnknownSubfileException() throw() {
}
const char* IMGUnknownSubfileException::what() const throw() {
std::string ret = std::string("Unknown subfile: ") + message;
return ret.c_str();
}
| true |
006138dbf1b052b0af3f0ca4302478c49cf1e92d | C++ | Overlesss/KalkFigure | /Figure/Model/square.h | UTF-8 | 771 | 3.140625 | 3 | [] | no_license | #ifndef SQUARE_H
#define SQUARE_H
#include "regularpolygon.h"
class Square : public RegularPolygon
{
private:
void createShape(double); //function that builds a square starting from the length of its side
public:
Square(double =1.0); //constructor with one double type parameter, with default value, which represents the length of the side
double diagonal() const; //function that returns the length of the diagonal
virtual Point2* centreOfSymmetry() const;
virtual void expand(double);
virtual void reduce(double);
Square* operator+(const Plane&) const;
Square* operator-(const Plane&) const;
Square* operator*(const Plane&) const;
Square* operator/(const Plane&) const;
};
#endif // SQUARE_H
| true |
0e337a02b52ed7566b3d125b56064b15a3402dee | C++ | jeatdeam/PC2 | /pregunta 1.cpp | UTF-8 | 1,240 | 3.375 | 3 | [] | no_license | #include<iostream>
#include<conio.h>
#include<stdio.h>
#include<time.h>
using namespace std;
void Factorial(int n) {
int fac = 1;
for (int i = n;i > 0;i--) {
fac = fac*i;
}
cout << "El factorial de " << n << " es : " << fac << endl;
}
void Graficar(int n) {
int *y;
y = new int[n];
y[0] = 0;
for (int i = 1; i <= n; i++) {
y[i] = y[i-1]+i;
cout << y[i] << " ";
}
cout << endl ;
for (int j = 0; j < n; j++) {
for (int i = 0; i < n-(j+1); i++) {
cout << " ";
}
for (int i = 1; i < j+2; i++) {
cout << y[i] << " ";
}
cout << endl;
}
}
int main() {
int a,n;
cout << "====Menu de opciones====" << endl;
cout << "1.Hallar el factorial " << endl;
cout << "2.Graficar " << endl;
cout << "3.Fin " << endl;
cin >> a;
switch (a) {
case 1:
do {
cout << "Ingrese el valor de n: ";
cin >> n;
}while(n<1 || n>10);
Factorial(n);
break;
case 2:
do {
cout << "Ingrese el numero de filas n: ";
cin >> n;
} while (n < 1);
Graficar(n);
break;
case 3:
break;
default:
break;
}
_getch();
return 0;
}
| true |
7277e86d3919dd2f5767c7215aabd89569b1a0f3 | C++ | tetris0k/Univercity-projects | /Matrix_solve_Choletsky/input_from_file.cpp | UTF-8 | 1,485 | 3.078125 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "functions.h"
#define EPS 10E-10
int file_input(FILE* f, int n, double* A, double* A1, double* b){
for (int i = 0; i < n; i++){
for (int j = 0 ; j < i ; j++){
if (fscanf(f, "%lf", &A1[i*n+j]) == 0){
printf("Problem with elements in matrix.\n");
return -1;
}
}
for (int j = i; j < n; j++){
if(fscanf(f, "%lf", &A[i*n+j-i*(i+1)/2]) == 0){
printf("Problem with elements in matrix.\n");
return -1;
}
A1[i*n+j]=A[i*n+j-i*(i+1)/2];
}
if ( fabs(A[i*n + i - i*(i+1)/2]) < EPS ){
printf("There are zero elements on diagonal.\n");
return -1;
}
if(fscanf(f, "%lf", &b[i]) == 0){
printf("Problem with elements in matrix.\n");
return -1;
}
}
return 0;
}
void file_output(FILE* g, int n, int max, double* Y){
printf("Solution:\n");
for (int i = 0; i < n; i++){
fprintf(g, "%f ", Y[i]);
if (i < max){
printf("%f ", Y[i]);
}
}
printf("\n");
}
void PrintMatrix(int n, double * A, double * b, int max_size){
int i;
int j;
int nPrint;
if (n > max_size){
nPrint = max_size;
} else {
nPrint = n;
}
for (i = 0; i < nPrint; ++i) {
printf("| ");
for (j = 0; j < nPrint; ++j)
if (j<i){
printf("%5.3g ", A[j * n + i-j*(j+1)/2]);
} else {
printf("%5.3g ", A[i * n + j-i*(i+1)/2]);
}
if (nPrint < n)
printf("\t...\t");
printf("|");
printf("%5.3g\n", b[i]);
}
}
| true |
a3dc8cffd8ced6600174e3f9afcd94ed0330ea5b | C++ | WeightScale/CorrectorSE8R01 | /Sketch2/ButtonsClass.h | WINDOWS-1251 | 1,384 | 2.609375 | 3 | [] | no_license | // ButtonClass.h
#ifndef _BUTTONCLASS_h
#define _BUTTONCLASS_h
#if defined(ARDUINO) && ARDUINO >= 100
#include "arduino.h"
#else
#include "WProgram.h"
#endif
#define PLUS_CALIBRATION 12 ///< C and A
#define MINUS_CALIBRATION 9 ///< C and B
#define OFFSET_CALIBRATION 10 ///< C and D
#define ACTION_BUTTON_LEFT 23 ///<
#define ACTION_BUTTON_RIGHT 29 ///<
#define ACTION_BUTTON_UP 30 ///<
#define ACTION_BUTTON_DOWN 27 ///<
#define ACTION_BUTTON_CENTER 15 ///<
enum BUTTON{
NONE,
B_LEFT,
B_RIGHT,
B_UP,
B_DOWN,
B_CENTER,
B_LEFT_delay,
B_RIGHT_delay,
B_UP_delay,
B_DOWN_delay,
B_CENTER_delay
};
class ButtonsClass{
protected:
bool _isDelay;
bool _isPress;
byte _button;
uint16_t _timePressed;
public:
void init(byte button, bool isPress,bool isDelay, uint16_t pressed_time);
BUTTON getCommand(long t = 4000);
bool isPressed(){return _isPress;};
void setPressed(bool p){_isPress = p;};
void clearPress(){_isPress = false;};
uint16_t getTime(){return _timePressed;};
byte getButton(){return _button;};
};
extern ButtonsClass Buttons;
#endif
| true |
2ca2d4add0679c60a2a7836853d46766634b8595 | C++ | SadSock/acm-template | /poj/POJ_1321/src/POJ_1321.cpp | WINDOWS-1252 | 1,371 | 2.75 | 3 | [] | no_license | //============================================================================
// Name : POJ_1321.cpp
// Author :
// Version :
// Copyright : 2012-7-8
// Description : DFS
//============================================================================
#include <stdio.h>
#include <string.h>
#define H 15
#define W 15
int DFS(int depth,int count);
char chess[H][W],wflag[W],hflag[H];
int rx[H*W],w,h,n,num;
//int x[H],y[H];
int main()
{
while(scanf("%d%d",&w,&n)!=EOF&&!(w==-1&&n==-1))
{
getchar();
h=w,memset(wflag,0,sizeof(wflag)),memset(hflag,0,sizeof(hflag)),num=0;
for(int i=0;i<h;i++)gets(chess[i]);
DFS(0,0);
printf("%d\n",num);
}
return 0;
}
int DFS(int depth,int count)
{
if(count==n)
{
//for(int i = 0 ; i<16 ;i++) printf("%d ",x[i]);
//printf("\n");
//for(int i = 0 ; i<16 ;i++) printf("%d ",y[i]);
//printf("\n");
num++;
return 0;
}
if(depth==w*h) return 0;
if(chess[depth/w][depth%w]=='.')
{
DFS(depth+1,count);
}
else
{
for(int i = 0 ; i<=1 ;i++)
{
if(i==0){DFS(depth+1,count);}
else
{
if(hflag[depth/w]==0&&wflag[depth%w]==0)
{
hflag[depth/w]=1;
wflag[depth%w]=1;
//x[count]=depth/w;
//y[count]=depth%w;
DFS(depth+1,count+1);
hflag[depth/w]=0;
wflag[depth%w]=0;
}
}
}
}
return 0;
}
| true |
66bcfd1bd7ea21ed65ce45651c08577ca306c6d1 | C++ | shane-martinez/Shay | /PortalEngine/Cam.cpp | UTF-8 | 3,134 | 3.171875 | 3 | [] | no_license | #include "Cam.h"
Cam::Cam()
{
// Camera Position
pos.x = 0;
pos.y = 5;
pos.z = 0;
// Look at
look.x = 0;
look.y = 0;
look.z = 0;
// Up Vector
upVector.x = 0;
upVector.y = 1;
upVector.z = 0;
moveSpeed = 0;
dirLR = 0;
dirFB = 0;
// variables for rotation
rotateSpeed = 0;
rotateAngle = 0;
rotateUD = 0;
}
void Cam::CallGluLookatTesting()
{
gluLookAt( pos.x, pos.y, pos.z,
pos.x + look.x, pos.y + look.y, pos.z + look.z,
0, 1, 0);
}
void Cam::CallGluLookat()
{
gluLookAt(pos.x, pos.y, pos.z,
look.x, look.y, look.z,
0, 1, 0);
}
void Cam::DirectionLeftRight(const int dir)
{
dirLR = dir;
}
void Cam::DirectionForwardBack(const int dir)
{
dirFB = dir;
}
void Cam::DirectionUpDown(const int dir)
{
dirUD = dir;
}
bool Cam::CanMoveLR()
{
if (dirLR < 0 || dirLR > 0)
{
return true;
}
else
{
return false;
}
}
bool Cam::CanMoveFB()
{
if (dirFB < 0 || dirFB > 0)
{
return true;
}
else
{
return false;
}
}
bool Cam::CanMoveUD()
{
if (dirUD < 0 || dirUD > 0)
{
return true;
}
else
{
return false;
}
}
void Cam::MoveLeftRight()
{
pos.z += (dirLR * (upVector.z) * moveSpeed);
pos.x += (dirLR * (upVector.x) * moveSpeed);
}
void Cam::MoveForwardBack()
{
pos.z += (dirFB * (look.z) * moveSpeed);
pos.x += (dirFB * (look.x) * moveSpeed);
}
void Cam::MoveUpDown()
{
pos.y += dirUD * moveSpeed;
}
void Cam::Rotate(const int deltaX, const int deltaY)
{
rotateAngle += deltaX * rotateSpeed;
if (rotateUD > 1.7f) { //Stops camera from looking to high
rotateUD = 1.7f;
}
if (rotateUD < -1.7f) { // Stops camera from looking to low
rotateUD = -1.7f;
}
rotateUD -= deltaY * rotateSpeed;
// left and right
look.x = (float)sin(rotateAngle);
look.z = (float)-cos(rotateAngle);
// up and down
look.y = (float)sin(rotateUD);
// used to allow strafing
upVector.x = (float)sin(rotateAngle+ (float)PI / 2.0f);
upVector.z = (float)-cos(rotateAngle + (float)PI / 2.0f);
}
void Cam::Update()
{
if (CanMoveLR())
{
MoveLeftRight();
}
if (CanMoveFB())
{
MoveForwardBack();
}
if (CanMoveUD())
{
MoveUpDown();
}
CallGluLookatTesting();
}
void Cam::SetMoveSpeed(const GLfloat speed)
{
moveSpeed = speed;
}
void Cam::SetRotateSpeed(const GLfloat speed)
{
rotateSpeed = speed;
}
Coordinates & Cam::GetPosition()
{
return pos;
}
void Cam::SetMenuPosition()
{
// position
pos.x = 10;
pos.y = 50;
pos.z = 60;
upVector.x = 0;
upVector.y = 1;
upVector.z = 0;
look.x = 360;
look.y = 50;
look.z = 75;
CallGluLookat();
}
void Cam::SetPosition(const GLfloat xyz[3], const GLfloat upVec[3], const GLfloat angle)
{
// position
pos.x = xyz[0];
pos.y = xyz[1];
pos.z = xyz[2];
// up vector
upVector.x = upVec[0];
upVector.y = upVec[1];
upVector.z = upVec[2];
// looking at
rotateAngle = angle * (float)(PI / 180.0f);
// left and right
look.x = (float)sin(rotateAngle);
look.z = (float)-cos(rotateAngle);
CallGluLookat();
}
void Cam::Follow(const Coordinates posF)
{
pos.x = posF.x + -40.0f;
pos.y = posF.y + 0.0f;
pos.z = posF.z + 40.0f;
look.x = posF.x;
look.y = posF.y;
look.z = posF.z;
CallGluLookat();
}
| true |
05c7c8a75b0ee43d63cc7cf3dc4a05df51a7b6ea | C++ | ritikadhawan/CSES-problemset-solutions | /Introductory Problems/palindromeReorder.cpp | UTF-8 | 1,102 | 2.859375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main() {
string s;
cin>>s;
vector<long> freq(26, 0);
for(int i=0; i<s.length(); i++) {
char ch = s[i];
int index = ch - 'A';
freq[index]++;
}
bool oddValueExists = false, solPresent = true;
char oddFreqChar = '.';
for(int i=0; i<26; i++) {
if(freq[i]% 2 != 0 && !oddValueExists) {
oddValueExists = true;
oddFreqChar = 'A' + i;
} else if(freq[i]% 2!= 0 && oddValueExists) {
solPresent = false;
break;
}
}
if(solPresent) {
string ans = "";
for(char ch = 'A'; ch <= 'Z'; ch++) {
if(freq[ch - 'A'] > 0 && freq[ch - 'A'] % 2 == 0) {
ans.append((freq[ch - 'A'])/2u,ch);
}
}
cout<<ans;
if(oddValueExists) {
for(int i=0; i<freq[oddFreqChar - 'A']; i++)
cout<<oddFreqChar;
}
reverse(ans.begin(), ans.end());
cout<<ans;
} else {
cout<<"NO SOLUTION";
}
return 0;
} | true |
3a4ba9247e5bf6e1106fd3c74f5457bec775422c | C++ | SMin1620/OpenCV-C- | /Geometric_Processing/2.cpp | UTF-8 | 510 | 2.609375 | 3 | [] | no_license | #include "opencv2/opencv.hpp"
#include <iostream>
using namespace cv;
using namespace std;
int main() {
Mat src = imread("D:/ch2/city1.jpg", IMREAD_GRAYSCALE);
Mat dst;
Mat noise_img = Mat::zeros(src.rows, src.cols, CV_8U);
randu(noise_img, 0, 255);
Mat black_img = noise_img < 10;
Mat white_img = noise_img > 255;
Mat src1 = src.clone();
src1.setTo(255, white_img);
src1.setTo(0, black_img);
medianBlur(src1, dst, 5);
imshow("input", src1);
imshow("output", dst);
waitKey(0);
return 0;
}
| true |
b03e5bac9c9a4debced2d95a85371c557ef86eb0 | C++ | izoodeh/Lotus-GF | /CliExt/Memory.h | UTF-8 | 961 | 2.578125 | 3 | [] | no_license | #pragma once
class CSLock
{
CRITICAL_SECTION m_lock;
UINT m_lockCount;
public:
CSLock(): m_lockCount(0) { InitializeCriticalSection(&m_lock); };
~CSLock() { DeleteCriticalSection(&m_lock); };
inline void Enter() { EnterCriticalSection(&m_lock); m_lockCount++; };
inline void Leave() { m_lockCount--; LeaveCriticalSection(&m_lock); };
inline UINT GetLockCount() { return m_lockCount; };
};
namespace Memory
{
void Write(UINT address, LPVOID lpMemory, SIZE_T size);
void Nop(UINT address, SIZE_T size);
void WriteBYTE(UINT address, BYTE value);
void WriteDWORD(UINT address, DWORD value);
void WriteCall(UINT address, PVOID function, SIZE_T nops = 0);
void WriteJump(UINT address, PVOID function, SIZE_T nops = 0);
void WriteJump(UINT address, UINT jumpAddress, SIZE_T nops = 0);
UINT WriteRelative(UINT nOrgAddress, UINT nWriteFrom, VOID *pArray, UINT nOffsetIndex);
LPBYTE OpenSharedMemory(HANDLE& hMapFile, const WCHAR* wName, UINT size);
};
| true |
067569dd6bb013976170c3e9ee34e8cd398f244d | C++ | karlphillip/GraphicsProgramming | /qtLogoBlurGL/GLwindow.cpp | UTF-8 | 9,572 | 2.671875 | 3 | [] | no_license | /* Copyright (C) 2012-2020 Karl Phillip Buhr <karlphillip@gmail.com>
*
* This work is licensed under the Creative Commons Attribution-ShareAlike License.
* To view a copy of this license, visit:
* https://creativecommons.org/licenses/by-sa/2.5/legalcode
*
* Or to read the human-readable summary of the license:
* https://creativecommons.org/licenses/by-sa/2.5/
*
*
* Ingress logo with glowing effect, based on Nehe lesson 36.
*/
#include "GLwindow.h"
#include <GL/glu.h>
#include <iostream>
#include <QKeyEvent>
#include <QTimer>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
GLwindow::GLwindow(QWidget *parent)
: QGLWidget(parent)
{
_width = 0;
_height = 0;
}
GLwindow::~GLwindow()
{
glDeleteTextures(1, &_blur_texture);
}
void GLwindow::_tick()
{
update(); // triggers paintGL()
QTimer::singleShot(33, this, SLOT(_tick()));
}
void GLwindow::initializeGL()
{
_blur_texture = _gen_empty_texture();
GLfloat global_ambient[4]={0.2f, 0.2f, 0.2f, 1.0f};
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, global_ambient);
glEnable(GL_LIGHTING);
GLfloat light0pos[4] = { 0.0f, 2.0f, 10.0f, 1.0f };
GLfloat light0ambient[4] = { 0.2f, 0.2f, 0.2f, 1.0f };
GLfloat light0diffuse[4] = { 0.3f, 0.3f, 0.3f, 1.0f };
GLfloat light0specular[4] = { 0.8f, 0.8f, 0.8f, 1.0f };
glLightfv(GL_LIGHT0, GL_POSITION, light0pos);
glLightfv(GL_LIGHT0, GL_AMBIENT, light0ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light0diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light0specular);
glEnable(GL_LIGHT0);
glMateriali(GL_FRONT, GL_SHININESS, 128);
glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
glShadeModel(GL_SMOOTH);
glEnable(GL_LINE_SMOOTH);
_tick();
}
GLuint GLwindow::_gen_empty_texture()
{
// Create storage space for texture data (256x256x4)
unsigned int* data = (unsigned int*) new GLuint[((256 * 256)* 4 * sizeof(unsigned int))];
memset(data, 0, ((256 * 256)* 4 * sizeof(unsigned int)));
GLuint txtnumber = 0;
glGenTextures(1, &txtnumber);
glBindTexture(GL_TEXTURE_2D, txtnumber);
glTexImage2D(GL_TEXTURE_2D, 0, 4, 256, 256, 0,
GL_RGBA, GL_UNSIGNED_BYTE, data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
if (data)
delete[] data;
return txtnumber;
}
void GLwindow::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
_render_to_texture();
_draw_ingress_logo();
_draw_blur(6, 0.006f);
}
void GLwindow::_render_to_texture()
{
glViewport(0, 0, 256, 256);
_draw_ingress_logo();
glBindTexture(GL_TEXTURE_2D, _blur_texture);
glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, 0, 0, 256, 256, 0);
glClearColor(0.0f, 0.0f, 0.0f, 0.5);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(0, 0, _width ,_height);
}
void GLwindow::_draw_ingress_logo()
{
GLfloat material_color[] = { 0.5f, 0.5f, 1.0f, 1.0f }; // Set the material color
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, material_color);
GLfloat specular[] = { 0.5f, 0.5f, 1.0f, 1.0f }; // Sets the specular lighting
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular);
glMaterialf(GL_FRONT, GL_SHININESS, 20.0f);
_draw_quad();
_draw_triangle();
}
void GLwindow::_draw_blur(int times, float inc)
{
glDisable(GL_TEXTURE_GEN_S);
glDisable(GL_TEXTURE_GEN_T);
glEnable(GL_TEXTURE_2D); // Enable 2D Texture Mapping
glDisable(GL_DEPTH_TEST); // Disable Depth Testing
glBlendFunc(GL_SRC_ALPHA, GL_ONE); // Set Blending Mode
glEnable(GL_BLEND); // Enable Blending
glBindTexture(GL_TEXTURE_2D, _blur_texture); // Bind To The Blur Texture
_view_ortho(); // Switch To An Ortho View
float alpha = 0.2f; // Starting Alpha Value
float alphainc = alpha / times; // alphainc=0.3f / Times To Render Blur
int num; // Starting Alpha Value
float spost = 0.0f; // Starting Texture Coordinate Offset
glBegin(GL_QUADS); // Begin Drawing Quads
for (num = 0; num < times; num++) // Number Of Times To Render Blur
{
glColor4f(1.0f, 1.0f, 1.0f, alpha); // Set The Alpha Value (Starts At 0.2)
glTexCoord2f(0+spost, 1-spost); // Texture Coordinate ( 0, 1 )
glVertex2f(0,0); // First Vertex ( 0, 0 )
glTexCoord2f(0+spost, 0+spost); // Texture Coordinate ( 0, 0 )
glVertex2f(0, _height); // Second Vertex ( 0, _height )
glTexCoord2f(1-spost, 0+spost); // Texture Coordinate ( 1, 0 )
glVertex2f(_width, _height); // Third Vertex ( _width, _height )
glTexCoord2f(1-spost, 1-spost); // Texture Coordinate ( 1, 1 )
glVertex2f(_width, 0); // Fourth Vertex ( _width, 0 )
spost += inc; // Gradually Increase spost (Zooming Closer To Texture Center)
alpha = alpha - alphainc; // Gradually Decrease alpha (Gradually Fading Image Out)
}
glEnd(); // Done Drawing Quads
_view_perspective(); // Switch To A Perspective View
glEnable(GL_DEPTH_TEST); // Enable Depth Testing
glDisable(GL_TEXTURE_2D); // Disable 2D Texture Mapping
glDisable(GL_BLEND); // Disable Blending
glBindTexture(GL_TEXTURE_2D,0); // Unbind The Blur Texture
}
void GLwindow::_draw_triangle()
{
glPushMatrix();
glTranslatef(0.0f, 4.0f, -9.0f);
glScalef(2.f, 2.f, 2.f);
glLineWidth(5.0f);
glColor3f(1.0f, 1.0f, 1.0f); // White
glBegin(GL_LINES);
glVertex3f(-1.4f, -1.5f, -1.0f); // Top
glVertex3f( 1.4f, -1.5f, -1.0f);
glVertex3f( 1.4f, -1.5f, -1.0f); // Right
glVertex3f( 0.0f, -3.8f, -1.0f);
glVertex3f(-1.4f, -1.5f, -1.0f); // Left
glVertex3f( 0.0f, -3.8f, -1.0f);
glVertex3f( 0.0f, -2.3f, -1.0f); // Right diagonal
glVertex3f( 1.4f, -1.5f, -1.0f);
glVertex3f( 0.0f, -2.3f, -1.0f); // Left diagonal
glVertex3f(-1.4f, -1.5f, -1.0f);
glVertex3f( 0.0f, -2.3f, -1.0f); // Bottom diagonal
glVertex3f( 0.0f, -3.8f, -1.0f);
glEnd();
glPopMatrix();
}
void GLwindow::_draw_quad()
{
glPushMatrix();
glTranslatef(0.0f, 4.0f, -9.0f);
glScalef(2.f, 2.f, 2.f);
glLineWidth(5.0f);
glColor3f(1.0f, 1.0f, 1.0f); // White
glBegin(GL_LINES);
glVertex3f( 0.0f, 0.0f, -1.0f); // Top vertical line
glVertex3f( 0.0f, -1.0f, -1.0f);
glVertex3f( 1.9f, -3.2f, -1.0f); // Right diagonal line
glVertex3f( 1.1f, -2.7f, -1.0f);
glVertex3f(-1.9f, -3.2f, -1.0f); // Left diagonal line
glVertex3f(-1.1f, -2.7f, -1.0f);
glVertex3f( 0.0f, 0.0f, -1.0f); // Right Of The Quad (Top)
glVertex3f( 2.0f, -1.2f, -1.0f);
glVertex3f( 2.0f, -1.2f, -1.0f); // Right Of The Quad (Center)
glVertex3f( 2.0f, -3.2f, -1.0f);
glVertex3f( 2.0f, -3.2f, -1.0f); // Right Of The Quad (Bottom)
glVertex3f( 0.0f, -4.4f, -1.0f);
glVertex3f( 0.0f, 0.0f, -1.0f); // Left Of The Quad (Top)
glVertex3f(-2.0f, -1.2f, -1.0f);
glVertex3f(-2.0f, -1.2f, -1.0f); // Left Of The Quad (Center)
glVertex3f(-2.0f, -3.2f, -1.0f);
glVertex3f(-2.0f, -3.2f, -1.0f); // Left Of The Quad (Bottom)
glVertex3f( 0.0f, -4.4f, -1.0f);
glEnd();
glPopMatrix();
}
void glPerspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar)
{
GLdouble ymax = zNear * tan( fovy * M_PI / 360.0 );
GLdouble ymin = -ymax;
GLdouble xmin = ymin * aspect;
GLdouble xmax = ymax * aspect;
glFrustum( xmin, xmax, ymin, ymax, zNear, zFar );
}
void GLwindow::resizeGL( int w, int h)
{
_width = w;
_height = h;
glViewport(0, 0, _width, _height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// compute aspect ratio of the window
if (_height == 0)
glPerspective (60, (float) _width, 1.0, 50.0);
else
glPerspective (60, (float) _width / (float) _height, 1.0, 50.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void GLwindow::_view_ortho() // Set Up An Ortho View
{
glMatrixMode(GL_PROJECTION); // Select Projection
glPushMatrix(); // Push The Matrix
glLoadIdentity(); // Reset The Matrix
glOrtho( 0, _width , _height, 0, -1, 1 ); // Select Ortho Mode (640x480)
glMatrixMode(GL_MODELVIEW); // Select Modelview Matrix
glPushMatrix(); // Push The Matrix
glLoadIdentity(); // Reset The Matrix
}
void GLwindow::_view_perspective() // Set Up A Perspective View
{
glMatrixMode( GL_PROJECTION ); // Select Projection
glPopMatrix(); // Pop The Matrix
glMatrixMode( GL_MODELVIEW ); // Select Modelview
glPopMatrix(); // Pop The Matrix
}
| true |
d8dbd2017e7c1a42981cda1585b989b3ac568d45 | C++ | dariogarcia/tiramisu | /include/Image.hpp | UTF-8 | 1,189 | 2.640625 | 3 | [] | no_license | #ifndef IMAGE_H
#define IMAGE_H
#include <string>
#include <map>
#include "CNNScheme.hpp"
#include "CNNFeatures.hpp"
using std::string;
using std::map;
using std::pair;
class Image {
public:
inline string getImageName() const {return imageName;}
inline string getClassName() const {return className;}
inline string getPath() const {return path;}
//inline vector<vector<int> >& getRelevantFeaturesDyn() {return relevantFeatures;}
//inline const vector<vector<int> >& getRelevantFeaturesConst() const {return relevantFeatures;}
inline void setImageName(string n) {imageName=n;}
inline void setClassName(string n) {className=n;}
inline void setPath(string p) {path=p;}
void normalizeActivations(int normType);
vector< vector<pair<int,float> > > activations;
vector<double> normByLayer;
double unsquaredNorm;
//void addActivations(const string path, const string layerName);
//void exploreImage() ;
//void computeRelevantFeatures(const CNNScheme &scheme, const CNNFeatures &cnnfeatures);
private:
string imageName;
string className;
string path;
//vector<vector<int> > relevantFeatures;
}; // Image
#endif
| true |
124d30d786b6998f906b687d13555c2221439bb3 | C++ | gurum77/gengine | /gengine-0.1/Engine/GEngine/Src/GCommon/GMatrix.h | UTF-8 | 800 | 2.828125 | 3 | [] | no_license | #pragma once
/**
@brief
- 4 x 4 matrix
*/
class G_EXT_CLASS CGMatrix
{
public:
union
{
struct
{
double _11, _12, _13, _14;
double _21, _22, _23, _24;
double _31, _32, _33, _34;
double _41, _42, _43, _44;
};
double m[4][4];
};
double operator() (UINT Row, UINT Column) CONST{ return m[Row][Column]; }
double& operator() (UINT Row, UINT Column) { return m[Row][Column]; }
CGMatrix& operator= (CONST CGMatrix& M);
CGMatrix& operator*= (CONST CGMatrix& M);
CGMatrix operator* (CONST CGMatrix& M) CONST;
public:
CGMatrix(double m00, double m01, double m02, double m03,
double m10, double m11, double m12, double m13,
double m20, double m21, double m22, double m23,
double m30, double m31, double m32, double m33);
CGMatrix();
~CGMatrix();
};
| true |
3d92df5d1de6ca192a9ba6132b521f98404d1e27 | C++ | Toyohara01/ChatRoom | /ChatWindow.hpp | UTF-8 | 764 | 2.546875 | 3 | [] | no_license | #ifndef CHATWINDOW_HPP
#define CHATWINDOW_HPP
#include "Client.hpp"
#include "Message.hpp"
#include <iostream>
#include <vector>
#include <iterator>
#include <thread>
using namespace std;
const string FUNCTION = "()";
class ChatWindow
{
private:
string ip;
uint16_t port;
int sockID;
Client client;
bool continueSession;
thread readMessagesThread;
vector<thread> processMessagesThreadBuffer;
void ProcessMessage(string input);
void Connect();
void readMessageHandler();
void StringInterpreter(string input);
public:
ChatWindow(); //Empty constructor
ChatWindow(string ip, uint16_t port);
bool Login();
void Disconnect();
void Chat();
void Logout();
};
#endif //CHATWINDOW_HPP
| true |
87f5d67487bf223b24a967f477a5aed0fa4c78a4 | C++ | lukasic/ncfm | /src/NCException.h | UTF-8 | 330 | 3.046875 | 3 | [] | no_license | #pragma once
#include <string>
#include <iostream>
//! Pomocna trieda pre vynimky v grafickom rozhrani.
class NCException
{
private:
std::string msg; ///< Informacie o vynimke.
public:
/*!
* \brief Vytvori instanciu vynimky.
* \param msg informacie o vynimke.
*/
NCException(const std::string & msg): msg(msg) {}
};
| true |
2389c3f2577e93b563e1d980ef25f690198708fb | C++ | Laylatame/Data-Structures | /Tareas de programación/Tarea4/Tarea4/LinkedList.h | UTF-8 | 7,441 | 3.1875 | 3 | [] | no_license | //
// LinkedList.h
// Tarea4
//
// Created by Layla Tame on 2/8/19.
// Copyright © 2019 Layla Tame. All rights reserved.
//
#include "Node.h"
using namespace std;
#ifndef LinkedList_h
#define LinkedList_h
template <class T>
class LinkedList
{
private:
Node<T> *head;
int iSize;
void deleteHelp();
public:
LinkedList();
~LinkedList();
LinkedList(const LinkedList<T> &list); //No está
T get(int iPos);
T set(T data, int iPos); //Al reves
bool isEmpty();
int getSize();
bool change(int iPos1, int iPos2);
bool add(T data, int iPos);
void addFirst(T data);
void addLast(T data);
bool del(int iPos);
void deleteFirst();
void deleteLast();
int deleteAll();
void print();
void reverse();
bool operator==(const LinkedList<T> &list);
void operator+=(T data);
void operator+=(const LinkedList<T> &list);
void operator=(const LinkedList<T> &list);
};
template <class T>
LinkedList<T>::LinkedList()
{
head = NULL;
iSize = 0;
}
template <class T>
LinkedList<T>::~LinkedList()
{
deleteHelp();
}
template <class T>
LinkedList<T>::LinkedList(const LinkedList<T> &list)
{
iSize = list -> iSize;
Node<T> *currnt = list -> head;
for (int i = 0; i < iSize; i++)
{
currnt -> addLast(currnt -> getData());
currnt = currnt -> getNext();
}
}
template <class T>
T LinkedList<T>::get(int iPos)
{
Node<T> *currnt = head;
for(int i=0; i<iPos; i++)
{
currnt = currnt->getNext();
}
return currnt->getData();
}
template <class T>
T LinkedList<T>::set(T data, int iPos)
{
Node<T> *currnt = head;
for(int i=0; i<iPos; i++)
{
currnt = currnt->getNext();
}
T temp = currnt->getData();
currnt->setData(data);
return temp;
}
template <class T>
bool LinkedList<T>::isEmpty()
{
return (head == NULL);
}
template <class T>
int LinkedList<T>::getSize()
{
return iSize;
}
template <class T>
bool LinkedList<T>::change(int iPos1, int iPos2)
{
if (iPos1 == iPos2)
{
return true;
}
int minPos = (iPos1 < iPos2) ? iPos1 : iPos2;
int maxPos = (iPos1 > iPos2) ? iPos1 : iPos2;
Node <T> *currnt1 = head, currnt2;
for (int i = 1; i <= minPos; i++)
{
currnt1 = currnt1 -> getNext();
}
currnt2 = currnt1;
for (int i=minPos; i<=maxPos; i++)
{
currnt2 = currnt2 -> getNext();
}
T temp = currnt1 -> getData();
currnt1->setData(currnt2->getData());
currnt2->setData(temp);
return true;
}
template <class T>
bool LinkedList<T>::add(T data, int iPos)
{
if (iPos > iSize)
{
return false;
}
if (iPos == 0)
{
addFirst(data);
}
else if (iPos == iSize)
{
addLast(data);
}
else
{
Node<T> *currnt = head;
for(int i=1; i<iPos; i++)
{
currnt = currnt->getNext();
}
currnt->setNext(new Node<T>(data, currnt->getNext()));
iSize++;
}
return true;
}
template <class T>
void LinkedList<T>::addFirst(T data)
{
head = new Node<T>(data, head);
iSize++;
}
template <class T>
void LinkedList<T>::addLast(T data)
{
if (isEmpty())
{
addFirst(data);
}
else
{
Node<T> *currnt = head;
while (currnt -> getNext() != NULL)
{
currnt = currnt->getNext();
}
currnt = new Node<T>(data);
iSize++;
}
}
template <class T>
bool LinkedList<T>::del(int iPos)
{
if (iPos < iSize)
{
if (iPos == 0)
{
deleteFirst();
}
else if (iPos == iSize - 1)
{
deleteLast();
}
else
{
Node<T> *currnt = head;
for (int i=1; i<iPos; i++)
{
currnt = currnt->getNext();
}
Node<T> *temp = currnt -> getNext();
currnt->setNext(currnt->getNext()->getNext());
delete temp;
iSize--;
}
}
return true;
}
template <class T>
void LinkedList<T>::deleteFirst()
{
if (!this-> isEmpty())
{
Node<T> *currnt = head;
head = head->getNext();
delete currnt;
iSize--;
}
}
template <class T>
void LinkedList<T>::deleteLast()
{
if (iSize <= 1)
{
deleteFirst();
}
else
{
Node<T> *currnt = head;
while(currnt -> getNext() -> getNext() != NULL)
{
currnt = currnt -> getNext();
}
delete currnt ->getNext();
currnt -> setNext(NULL);
iSize--;
}
}
template <class T>
int LinkedList<T>::deleteAll()
{
deleteHelp();
int iCount = iSize;
iSize = 0;
return iCount;
}
template <class T>
void LinkedList<T>::print()
{
Node<T> *currnt = head;
while(currnt != NULL)
{
cout << currnt -> getData() << " " ;
currnt = currnt -> getNext();
}
cout << endl;
}
template <class T>
void LinkedList<T>::reverse()
{
Node<T> *currnt = nullptr;
Node<T> *next = head->getNext();
if(iSize >= 2)
{
while(next != nullptr)
{
head ->setNext(currnt);
currnt = head;
head = next;
next = head->getNext();
}
head-setNext(currnt);
delete next;
}
}
template <class T>
bool LinkedList<T>::operator==(const LinkedList<T> &list)
{
Node<T> *currnt = list -> head;
Node<T> *currnt1 = head;
if (iSize != list -> iSize)
{
return false;
}
for (int i=0; i<iSize; i++)
{
if (currnt1 -> get(i) == list -> get(i))
{
currnt1 -> getNext();
currnt = currnt -> getNext();
}
else
{
return false;
}
}
return true;
//OTRA
/*Node<T> *curr = head;
Node<T> *curr1 = LL.head;
if ( iSize != LL.iSize()) {
return false;
}
for ( int i = 0; i < iSize; i++) {
if(curr->getData() != curr1 -> getData()) {
return false;
}
curr = curr ->getNext();
curr1 = curr1 ->getNext();
}
return true;*/
}
template <class T>
void LinkedList<T>::operator+=(T data)
{
addLast(data);
}
template <class T>
void LinkedList<T>::operator+=(const LinkedList<T> &list)
{
Node<T> *currnt = list -> head;
for (int i=0; i<list -> iSize; i++)
{
addLast(currnt->getData());
currnt = currnt -> getNext();
}
//OTRO
/*
Node<T> *curr = head;
Node<T> *curr1 = LL.head;
while (curr -> getNext() != nullptr) {
curr = curr -> getNext();
curr1 = curr1 -> getNext();
}
*/
}
template <class T>
void LinkedList<T>::operator=(const LinkedList<T> &list)
{
deleteAll();
Node<T> *currnt = head;
iSize = list -> iSize;
for(int i=0; i<iSize; i++)
{
currnt -> addLast(currnt -> getData());
currnt = currnt -> getNext();
}
//OTRO
/*
deleteAll();
this -> iSize = LL.iSize();
head ) new Node<T>(LL.head --> getData(), nullptr);
Node<T> *curr1 = LL.head->getNext();
node<T> *Curr = head;
while ( curr1 != nullptr) {
curr -> setNext(new Node<T>(curr1->getData(), nullptr));
curr = curr->getNext();
curr1 = curr1->getNext();
}
*/
}
#endif /* LinkedList_h */
| true |
81d4bc12ec7fec9526425dda6203a22dfe4e5537 | C++ | gametechnology/psi-2013 | /source/Game/StationStats.h | UTF-8 | 578 | 2.671875 | 3 | [] | no_license | #ifndef STATIONSTATS
#define STATIONSTATS
#include "../../include/Engine/Component.h"
#include "Stations/Station.h"
class StationStats : public Component
{
public:
StationStats();
~StationStats();
void increaseHealth(int health);
void increasePower(int power);
void increaseShield(int shield);
void decreaseHealth(int health);
void decreasePower(int power);
void decreaseShield(int shield);
//Station information
const static int maxHealth = 100;
const static int maxPower = 100;
const static int maxShield = 100;
int health;
int power;
int shield;
};
#endif | true |
74286cadf77b1981a6f7676cf05810aa5ca01fb6 | C++ | nevergofullretard/Arduino-Learning | /sketch_buttons_dimmable_led/sketch_buttons_dimmable_led.ino | UTF-8 | 1,408 | 2.78125 | 3 | [] | no_license | int ledPin = 11;
int button1 = 9;
int button2 = 10;
int brightness = 0;
int downPin = A1;
int upPin = A0;
int downVal;
int upVal;
int delayTime = 100;
int buzzPin = 12; // buzz pin ist das Ton-Teil, wird verwendet wenn wir auf max oder min Helligkeit sind
int buzzTime = 100;
void setup() {
// put your setup code here, to run once:
pinMode(ledPin, OUTPUT);
pinMode(button1, OUTPUT);
pinMode(button2, OUTPUT);
pinMode(buzzPin, OUTPUT);
pinMode(downPin, INPUT);
pinMode(upPin, INPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(button1, HIGH);
digitalWrite(button2, HIGH);
downVal = digitalRead(downPin);
upVal = digitalRead(upPin);
Serial.println(upVal);
Serial.println(downVal);
if (upVal == 0) {
if (brightness <= 240) { // digitalWrite geht nur bis 255
brightness += 10;
} else {
digitalWrite(buzzPin, HIGH);
delay(buzzTime);
digitalWrite(buzzPin, LOW);
}
}
if (downVal == 0) {
if (brightness >= 10) {
brightness -= 10;
} else {
digitalWrite(buzzPin, HIGH);
delay(buzzTime);
digitalWrite(buzzPin, LOW);
}
}
Serial.println(brightness);
Serial.println();
analogWrite(ledPin, brightness);
delay(delayTime);
}
| true |
4bea3b34a01b2465a1bdeccc9a7eec07f26bee82 | C++ | leezhongshan/3D-Framework | /Framework/Framework/source/src/ResourceManager.cpp | UTF-8 | 2,255 | 2.53125 | 3 | [] | no_license | #include "ResourceManager.h"
#include "FBXLoader.h"
#include "BitmapFont.h"
#include <SOIL.h>
ResourceManager* ResourceManager::m_pInstance = nullptr;
void ResourceManager::Create()
{
if( m_pInstance == nullptr )
m_pInstance = new ResourceManager();
}
void ResourceManager::Destroy()
{
if( m_pInstance != nullptr )
delete m_pInstance;
}
ResourceManager* ResourceManager::Get()
{
return m_pInstance;
}
ResourceManager::ResourceManager()
{
}
ResourceManager::~ResourceManager()
{
std::map<const char*, FBXFile*>::iterator pIterFBX = m_pFBXMap.begin();
for(; pIterFBX != m_pFBXMap.end(); ++pIterFBX)
{
pIterFBX->second->unload();
}
std::map<const char*, GLuint>::iterator pIterTexture = m_pTextureMap.begin();
for(; pIterTexture != m_pTextureMap.end(); ++pIterTexture)
{
glDeleteTextures(1, &pIterTexture->second);
}
std::map<const char*, BitmapFont*>::iterator pIterFont = m_pFontMap.begin();
for(; pIterFont != m_pFontMap.end(); ++pIterFont)
{
delete pIterFont->second;
}
}
FBXFile* ResourceManager::LoadFBX(const char* a_ccFile, int a_iScale)
{
if(m_pFBXMap.find(a_ccFile) == m_pFBXMap.end())
{
FBXFile* pFBX = new FBXFile();
if (!(pFBX->load(a_ccFile, FBXFile::UNIT_SCALE(a_iScale))))
{
printf("Failed to load file: %s \n", a_ccFile);
return nullptr;
}
m_pFBXMap.insert(std::pair<const char*, FBXFile*>(a_ccFile, pFBX));
return pFBX;
}
else
{
return m_pFBXMap[a_ccFile];
}
}
GLuint ResourceManager::LoadTexture(const char* a_ccFilePath)
{
if(m_pTextureMap.find(a_ccFilePath) == m_pTextureMap.end())
{
GLuint pTexture = SOIL_load_OGL_texture(a_ccFilePath, 4, 0, SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_INVERT_Y);
m_pTextureMap.insert(std::pair<const char*, GLuint>(a_ccFilePath, pTexture));
return pTexture;
}
else
{
return m_pTextureMap[a_ccFilePath];
}
}
BitmapFont* ResourceManager::LoadFont(const char* a_ccFont)
{
if(m_pFontMap.find(a_ccFont) == m_pFontMap.end())
{
BitmapFont* pFont = new BitmapFont();
if (!(pFont->LoadFont(a_ccFont)))
{
printf("Failed to load file: %s \n", a_ccFont);
return nullptr;
}
m_pFontMap.insert(std::pair<const char*, BitmapFont*>(a_ccFont, pFont));
return pFont;
}
else
{
return m_pFontMap[a_ccFont];
}
} | true |
3f572c7b0902ecd3cab1dcea1829c50ba29d4d9c | C++ | navispeed/IFT-3100 | /src/model/model3d/Model3d.cpp | UTF-8 | 1,627 | 2.65625 | 3 | [] | no_license | #include "Model3d.h"
Model3d::Model3d(ofxAssimpModelLoader * model,ofVec3f position)
{
this->position = position;
this->model = model;
this->scale = ofVec3f(1,1,1);
this->angleX = 0;
this->angleY = 0;
this->angleZ = 0;
}
void Model3d::drawObject(map<int, ofLight*>& lights)
{
model->setPosition(position.x,position.y,position.z);
model->setScale(scale.x, scale.y, scale.z);
model->setRotation(0, angleX, 1, 0, 0);
model->setRotation(1, angleY, 0, 1, 0);
model->setRotation(2, angleZ, 0, 0, 1);
this->material.beginMaterial(lights);
model->draw(OF_MESH_FILL);
this->material.endMaterial();
}
void Model3d::rotate(float angle, ofVec3f axis)
{
if (axis.x > 0) {
adjustAngleX(angle);
}
if (axis.y > 0) {
adjustAngleY(angle);
}
if (axis.z > 0) {
adjustAngleZ(angle);
}
}
void Model3d::translate(ofVec3f translation)
{
this->position += translation;
}
void Model3d::modifyScale(ofVec3f scaleAdjust)
{
this->scale += scaleAdjust;
}
void Model3d::adjustAngleX(const float adjust)
{
adjustangle(adjust, this->angleX);
}
void Model3d::adjustAngleY(const float adjust)
{
adjustangle(adjust, this->angleY);
}
void Model3d::adjustAngleZ(const float adjust)
{
adjustangle(adjust, this->angleZ);
}
void Model3d::adjustangle(const float adjust, float & angle)
{
angle -= adjust;
if (angle > 360) {
angle -= 360;
}
if (angle < -360) {
angle+= 360;
}
}
ofImage Model3d::getTexture()
{
return texture;
}
void Model3d::setTexture(ofImage texture)
{
this->texture = texture;
}
ofNode *Model3d::getAsOfNode() {
return nullptr;
}
Material &Model3d::getMaterial() {
return this->material;
}
| true |
e5041ef2c1377114a3f897cab850201230708e19 | C++ | zhangzz2015/code | /algorithms/cpp/41_first_missing_positive/FirstMissing.cpp | UTF-8 | 448 | 2.84375 | 3 | [] | no_license | class FirstMissing {
public:
int firstMissingPositive(vector<int>& nums) {
int index = 0, size = nums.size();
while (index < size) {
long current = (long)nums[index] - 1;
if (current >= 0 && current < size && nums[i] != nums[j]) {
swap(nums[index], nums[current]);
} else {
index++;
}
}
for (index = 0; index < size; ++index) {
if (nums[index] != index + 1) {
return index + 1;
}
}
return size + 1;
}
};
| true |
b12e2b69a93f7e208a1c2ae1bf0b0ff166860c83 | C++ | GCZhang/Profugus | /packages/CudaUtils/test/tstHost_Vector.cc | UTF-8 | 4,043 | 2.59375 | 3 | [
"BSD-2-Clause"
] | permissive | //----------------------------------*-C++-*----------------------------------//
/*!
* \file CudaUtils/test/tstHost_Vector.cc
* \author Seth R Johnson
* \date Mon Aug 12 10:29:26 2013
* \brief
* \note Copyright (C) 2013 Oak Ridge National Laboratory, UT-Battelle, LLC.
*/
//---------------------------------------------------------------------------//
#include "../cuda_utils/Host_Vector.hh"
#include "gtest/utils_gtest.hh"
#include "../cuda_utils/Device_Vector.hh"
#include "../cuda_utils/Hardware.hh"
#include "utils/View_Field.hh"
#include <config.h>
#include "Polyglot_Kernel.cuh"
//---------------------------------------------------------------------------//
// Test fixture
//---------------------------------------------------------------------------//
class HostVectorTest : public ::testing::Test
{
protected:
typedef cuda::arch::Device Arch_t;
typedef cuda::Device_Vector<Arch_t,float> Device_Vector_t;
typedef std::vector<float> Vector_t;
typedef cuda::Host_Vector<float> Host_Vector_t;
typedef profugus::const_View_Field<float> const_View_Field_t;
typedef profugus::View_Field<float> View_Field_t;
protected:
void SetUp()
{
#ifdef USE_CUDA
typedef cuda::Hardware<Arch_t> Hardware_t;
// Initialize device
if (!Hardware_t::have_acquired())
{
std::cout << "Acquiring device..." << std::flush;
Hardware_t::acquire();
std::cout << "done." << std::endl;
}
INSIST(Hardware_t::have_acquired(), "Device could not be acquired.");
#endif
// Add values to the vector
for (std::size_t i = 0; i < 63; ++i)
{
original.push_back(i * i);
}
}
protected:
Vector_t original;
};
//---------------------------------------------------------------------------//
// TESTS
//---------------------------------------------------------------------------//
TEST_F(HostVectorTest, accessors)
{
Host_Vector_t hv(original.size(), 1.23f);
ASSERT_EQ(63, hv.size());
ASSERT_TRUE(!hv.empty());
EXPECT_FALSE(hv.is_mapped());
EXPECT_FALSE(hv.is_write_combined());
// Check default value and iterators
for (Host_Vector_t::const_iterator it = hv.begin(),
end_it = hv.end();
it != end_it;
++it)
{
EXPECT_FLOAT_EQ(1.23f, *it);
}
// Copy data
hv.assign(profugus::make_view(original));
// Check equivalence and bracket accessors
for (std::size_t i = 0; i < 63; ++i)
{
EXPECT_FLOAT_EQ(original[i], hv[i]);
}
}
//---------------------------------------------------------------------------//
// Mapped memory is only supported when CUDA is enabled
TEST_F(HostVectorTest, mapped_memory)
{
#ifdef USE_CUDA
// Create a "mapped memory, write-only" vector where assigning to the host
// memory will automagically be copied to the GPU
Host_Vector_t hv(original.size(), 0.f,
cuda::alloc::MAPPED_WRITE_COMBINED);
// Create blank destination vector
Device_Vector_t gpu_out(original.size());
// Copy data
hv.assign(profugus::make_view(original));
// Call kernel; the host wrapper uses the .data() accessor to extract the
// GPU pointer
polyglot_copy(hv, gpu_out);
// Copy from device vector to new vector
Vector_t result(original.size());
device_to_host(gpu_out, profugus::make_view(result));
// Check result
for (std::size_t i = 0; i < original.size(); ++i)
{
EXPECT_FLOAT_EQ(original[i], result[i]) << "Failure at index " << i;
}
#else
// No cuda, no mapped memory; INSIST should be raised
EXPECT_THROW({Host_Vector_t hv(original.size(), 0.f,
cuda::alloc::MAPPED_WRITE_COMBINED);}, profugus::assertion);
#endif
}
//---------------------------------------------------------------------------//
// end of tstHost_Vector.cc
//---------------------------------------------------------------------------//
| true |
3124c579bce773e5ba3370380725301802f6f7d3 | C++ | jatinverma12/Data_And_Algo | /findMissing.cpp | UTF-8 | 971 | 3.328125 | 3 | [] | no_license | #include<iostream>
using namespace std;
void findmissingSorted(int *arr,int size)
{ int i;
int diff=arr[0]-0;
for(i=0;i<size;i++)
{
if(arr[i]-i!=diff)
{
while(diff<arr[i]-i)
{
cout<<i+diff<<"\n";
diff++;
}
}
}
delete arr;
}
void findmissingUnsorted(int *k,int len)
{
int max=k[0],i;
for(i=1;i<len;i++)
{
if(k[i]>max)
max=k[i];
}
int *b=new int[max];
for(i=1;i<max;i++)
b[i]=0;
for(i=0;i<len;i++)
{
b[k[i]]++;
}
for(i=1;i<max;i++)
{
if(b[i]==0)
cout<<"\n"<<i;
}
delete k;
}
int isSorted(int *p,int length)
{
int i=0;
for(;i<length-1;i++)
{
if(p[i]>p[i+1])
{
return 0;
}
}
return 1;
}
int main()
{
int *a,len,i;
cout<<"Enter the size of array";
cin>>len;
a=new int[len];
cout<<"Enter elements";
for(i=0;i<len;i++)
{
cin>>a[i];
}
if(isSorted(a,len))
findmissingSorted(a,len);
else
findmissingUnsorted(a,len);
}
| true |
2978998e65edbbef45310c6d4640cd61a8b1ca8b | C++ | LunarWatcher/TermUtils | /include/termutil/ColorPrinter.hpp | UTF-8 | 4,016 | 3.21875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "TermUtils.hpp"
#include <any>
#include <codecvt>
#include <iostream>
#include <locale>
#include <sstream>
#include <stdexcept>
#include <string>
namespace termutil {
// Enable forwarding of std::endl
typedef std::basic_ostream<char, std::char_traits<char>> CoutType;
typedef CoutType& (*StandardEndLine)(CoutType&);
/**
* Enum for properly mapping the ANSI features.
*/
enum class ANSIFeature {
CLEAR = 0,
BOLD = 1,
ITALIC = 3, // According to Wikipedia, this is some times treated as inverse
UNDERLINE = 4,
BLINK = 5,
STRIKE = 9,
FOREGROUND = 38,
BACKGROUND = 48
};
class ColorPrinter {
private:
/**
* Cache for whether or not the provided output stream supports ansi.
* This variable is a reflection of TermUtils::supportsAnsi(stream),
* and is calculated in the constructor.
*
* Note that certain variable changes involving processing256 will
* still be computed in order to drop all ANSI-related input.
* In the event this variable is false, the processing256 variable
* is a sign to drop the next variable instead of using it for
* something useful.
*/
bool supportsAnsi;
/**
* Internal variable; used to tell certain operator<<
* functions that they're about to get ANSI input or ANSI-related
* input that requires special processing.
*
* If supportsAnsi = false, this doubles down as a flag to discard
* certain parts of the input.
*/
bool processing256 = false;
std::ostream& outputStream;
bool shouldReturnEarly() {
if (!supportsAnsi && processing256) {
processing256 = false;
return true;
}
return false;
}
public:
ColorPrinter(std::ostream& outputStream) : outputStream(outputStream) {
supportsAnsi = TermUtils::supportsAnsi(&outputStream);
}
ColorPrinter() : ColorPrinter(std::cout) {}
template <typename T>
friend ColorPrinter& operator<<(ColorPrinter&, T);
friend ColorPrinter& operator<<(ColorPrinter&, ANSIFeature);
friend ColorPrinter& operator<<(ColorPrinter&, const std::string&);
friend ColorPrinter& operator<<(ColorPrinter&, int);
friend ColorPrinter& operator<<(ColorPrinter&, StandardEndLine manip);
};
template <typename T>
ColorPrinter& operator<<(ColorPrinter& printer, T type) {
printer.outputStream << type;
return printer;
}
inline ColorPrinter& operator<<(ColorPrinter& printer, ANSIFeature feature) {
if (!printer.supportsAnsi) {
// While we're dropping the print itself, we can't drop this part.
// If we do, we get a number printed out, which isn't what we want
printer.processing256 = true;
// Silently drop print
return printer;
}
if (printer.processing256)
throw std::runtime_error("Cannot print a new ANSI feature while attempting to print a color");
printer.outputStream << "\033[" << int(feature);
if (feature == ANSIFeature::FOREGROUND || feature == ANSIFeature::BACKGROUND) {
printer.processing256 = true;
printer.outputStream << ";5;";
} else {
printer.outputStream << "m";
}
return printer;
}
inline ColorPrinter& operator<<(ColorPrinter& printer, const std::string& str) {
if (printer.shouldReturnEarly()) {
return printer;
}
printer.outputStream << str;
if (printer.processing256) {
printer.processing256 = false;
printer.outputStream << "m";
}
return printer;
}
inline ColorPrinter& operator<<(ColorPrinter& printer, int code) {
if (printer.shouldReturnEarly()) {
return printer;
}
printer.outputStream << code;
if (printer.processing256) {
printer.processing256 = false;
printer.outputStream << "m";
}
return printer;
}
inline ColorPrinter& operator<<(ColorPrinter& printer, StandardEndLine manip) {
manip(printer.outputStream);
return printer;
}
} // namespace termutil
| true |
3a8a0692b304d5d9363d8b36425906ab756d0514 | C++ | GreenTangoo/SIEM | /aggregator/time_class/parse_time.hpp | UTF-8 | 1,373 | 3.03125 | 3 | [] | no_license | #ifndef PARSE_TIME_HPP
#define PARSE_TIME_HPP
#include "../parser_txt/parser.hpp"
namespace data_time_space
{
enum monthType{ JANUARY_NUM = 1, FEBRUARY_NUM = 2, MARCH_NUM = 3, APRIL_NUM = 4, MAY_NUM = 5,
JUNE_NUM = 6, JULY_NUM = 7, AUGUST_NUM = 8, SEPTEMBER_NUM = 9, OCTOBER_NUM = 10,
NOVEMBER_NUM = 11, DECEMBER_NUM = 12, INCORRECT_NUM = 13};
class Time
{
private:
int year;
int month;
int day;
int absoluteOneDayTime;
private:
void transformToAbsoluteTime(std::string strTime);
public:
explicit Time(std::string strTime); // Format: year/month/day/hour:minute:second
explicit Time();
Time(const Time &other);
Time(Time &&other) = delete;
~Time();
Time& operator=(const Time &other);
bool operator==(const Time &other);
friend int compare(const Time &first, const Time &second);
void setTime(std::string strTime); // Format: year/month/day/hour:minute:second
std::string getStrTime();
int getAbsoluteTime() const;
static int getAbsoluteTime(std::string timeStr);
int getYear() const ;
int getMonth() const ;
int getDay() const ;
};
monthType getMonthType(std::string monthString);
std::string getMonthString(monthType monthTypeRepresentation);
}
#endif
| true |
435cf21e34f5d84ffa1d069665c74062406b4950 | C++ | Aksha/Technical-and-Competitive-Programming | /practice/priority_queue_ascending_descending_sort.cpp | UTF-8 | 1,352 | 3.328125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <queue>
using namespace std;
int main() {
vector<int> numbers = {1,72,20,10,0};
vector<string> words = {"hi", "how", "are", "you"};
priority_queue<int> pq;
cout << "Descending order : " << endl;
cout << "Integer: " << endl;
for(int i = 0; i < numbers.size(); i++) {
pq.push(numbers[i]);
}
for(int i = 0; i < numbers.size(); i++) {
cout << pq.top() << endl;
pq.pop();
}
cout << "String : " << endl;
priority_queue<string> pq1;
for(int i = 0; i < words.size(); i++) {
pq1.push(words[i]);
}
for(int i = 0; i < words.size(); i++) {
cout << pq1.top() << endl;
pq1.pop();
}
cout << " Ascending order : " << endl;
cout << "Integer: " << endl;
priority_queue<int,vector<int>, greater<int>> pq2;
for(int i = 0; i < numbers.size(); i++) {
pq2.push(numbers[i]);
}
for(int i = 0; i < numbers.size(); i++) {
cout << pq2.top() << endl;
pq2.pop();
}
priority_queue<string,vector<string>, greater<string>> pq3;
for(int i = 0; i < words.size(); i++) {
pq3.push(words[i]);
}
cout << "String : " << endl;
for(int i = 0; i < words.size(); i++) {
cout << pq3.top() << endl;
pq3.pop();
}
return 0;
}
| true |
c1a7e49f54010eb5a8cbe9f246f768dfc7afa563 | C++ | epitaciosilva/estudosProgramacao | /lp1/empresa_10052018/src/funcionario.cpp | UTF-8 | 1,189 | 3.1875 | 3 | [] | no_license | #include <string>
#include <iostream>
using namespace std;
#include "../include/funcionario.hpp"
Funcionario::Funcionario() { }
Funcionario::~Funcionario() { }
void Funcionario::aumentoSalario() {
this->salario *= 1/100;
}
void operator>> (istream &i, Funcionario &funcionario) {
cout << "Digite o nome do funcionario: ";
getline(i, funcionario.nome);
cout << "Digite o salario do funcionario: ";
i >> funcionario.salario;
i.ignore();
cout << "Digite a data de admissao do funcionario: ";
getline(i, funcionario.dataAdmissao);
i.ignore();
}
ostream& operator<< (ostream &o, Funcionario funcionario) {
o << "\nNome: " << funcionario.nome;
o << "\nSalario: " << funcionario.salario;
o << "\nData de Admissao: " << funcionario.dataAdmissao;
return o;
}
// void operator<< (ostream &o, vector<Funcionario> &funcionarios) {
// for(size_t i = 0; i < funcionarios.size(); i++) {
// cout << funcionarios[i];
// }
// }
string Funcionario::getNome() {
return this->nome;
}
double Funcionario::getSalario() {
return this->salario;
}
string Funcionario::getDataAdmissao() {
return this->dataAdmissao;
}
| true |
59e814ca4f397f12556a1e213a24ff7126eb329b | C++ | penguin210135/C-language | /11431.cpp | UTF-8 | 3,361 | 3.34375 | 3 | [] | no_license | #include <iostream>
#include "string.h"
using namespace std;
class Char{
friend class Str;
private:
Char(char text):next(NULL){
this->text=text;
}
~Char(){
if(next)
delete next;
}
void print(){
cout<<text;
if(next)
next->print();
}
char text;
Char *next;
};
class Str{
public:
// construct a new Str by linked list of Char
Str(char*);
// copy constructor
// have to copy all Chars of another Str
Str(const Str &);
// equality operator
bool operator==( const Str & ) const;
/** the following methods are already implemented **/
Str():head(NULL),tail(NULL){} // default constructor
~Str(){
if(head)
delete head;
}
Str& strInsert(const Str &s){
Str tmp(s);
tail->next=tmp.head;
tail=tmp.tail;
tmp.head=NULL;
return *this;
}
Str& strSwap(Str &s){
Str tmp(*this);
this->~Str();
*this=s;
s=tmp;
tmp.head=NULL;
return *this;
}
void strPrint(){
if(head)
head->print();
cout<<endl;
}
private:
Char *head;
Char *tail;
};
typedef void (*FUNC)(Str &s1,Str &s2);
const int OPnum=5;
typedef struct _OPmap{
const char *op;
FUNC fp;
}OPmap;
void func_si(Str &s1,Str &s2){
s1.strSwap(s2).strInsert(s2);
}
void func_is(Str &s1,Str &s2){
s1.strInsert(s2).strSwap(s2);
}
void func_s(Str &s1,Str &s2){
s1.strSwap(s2);
}
void func_i(Str &s1,Str &s2){
s1.strInsert(s2);
}
void func_t(Str &s1,Str &s2){
if(s1==s2){
s1.strInsert(s2);
}else{
s1.strSwap(s2);
}
}
OPmap MAP[OPnum]={{"si",func_si},{"is",func_is},{"s",func_s},{"i",func_i},{"t",func_t}};
void operate(char *op,Str &s1,Str &s2){
for(int i=0;i<OPnum;i++)
if(strcmp(MAP[i].op,op)==0){
MAP[i].fp(s1,s2);
break;
}
}
Str::Str(char *ch){
Char *tmp;
int num = strlen(ch);
head = new Char(ch[0]);
tmp = head;
for(int i=1;i<num;i++){
tmp->next = new Char(ch[i]);
tmp = tmp->next;
}
tail = tmp;
tail->next = NULL;
}
Str::Str(const Str &b){
Char *tmp = b.head,*np;
head = new Char(tmp->text);
np = head;
while(tmp->next != NULL){
np->next = new Char(tmp->next->text);
tmp = tmp->next;
np = np->next;
}
tail = tmp;
tail->next = NULL;
}
bool Str::operator==(const Str &b) const{
Char *np = head,*nq = b.head;
while(np!=NULL || nq!=NULL){
if(np==NULL && nq!=NULL) return false;
if(np!=NULL && nq==NULL) return false;
if(np->text != nq->text) return false;
np = np->next;
nq = nq->next;
}
return true;
}
int main() {
int N;
char input[100];
int index=0;
Str *s[100];
cin>>N;
for(int i=0;i<N;i++){
cin>>input;
s[index++]=new Str(input);
}
char op[3];//"si" || "is" || "s" || "i" || "t" || "e"
while(1){
cin>>op;
if(op[0]=='e')break;
int idx1,idx2;
cin>>idx1;
cin>>idx2;
operate(op,*s[idx1],*s[idx2]);
}
for(int i=0;i<N;i++){
s[i]->strPrint();
delete s[i];
}
return 0;
}
| true |
80256a2ece36eee34c49e721b52ed25816ec5ec0 | C++ | rbdannenberg/o2 | /test/longtest.cpp | UTF-8 | 5,092 | 2.6875 | 3 | [
"MIT"
] | permissive | // longtest.c -- test long messages that require allocation
//
#include <stdio.h>
#include "o2.h"
#include "assert.h"
#include "string.h"
bool got_the_message = false;
O2blob_ptr a_blob;
char a_midi_msg[4];
int arg_count = 0;
// receive arg_count floats
void service_f(O2msg_data_ptr data, const char *types,
O2arg_ptr *argv, int argc, const void *user_data)
{
o2_extract_start(data);
for (int i = 0; i < arg_count; i++) {
assert(*types == O2_FLOAT);
#ifndef NDEBUG
O2arg_ptr arg = // only needed for assert()
#endif
o2_get_next(O2_FLOAT);
assert(arg);
assert(arg->f == i + 123);
types++;
}
assert(*types == 0); // end of string, got arg_count floats
got_the_message = true;
}
// receive arg_count doubles
void service_d(O2msg_data_ptr data, const char *types,
O2arg_ptr *argv, int argc, const void *user_data)
{
o2_extract_start(data);
for (int i = 0; i < arg_count; i++) {
assert(*types == O2_DOUBLE);
#ifndef NDEBUG
O2arg_ptr arg = // only needed for assert()
#endif
o2_get_next(O2_DOUBLE);
assert(arg);
assert(arg->d == i + 1234);
types++;
}
assert(*types == 0); // end of string, got arg_count floats
got_the_message = true;
}
// receive arg_count floats, coerced to ints, with parsing
void service_fc(O2msg_data_ptr data, const char *types,
O2arg_ptr *argv, int argc, const void *user_data)
{
assert(argc == arg_count);
o2_extract_start(data);
for (int i = 0; i < arg_count; i++) {
assert(*types == 'i');
assert(argv[i]);
assert(argv[i]->i == i + 123);
types++;
}
assert(*types == 0); // end of string, got arg_count floats
got_the_message = true;
}
// receive arg_count doubles, coerced to ints, with parsing
void service_dc(O2msg_data_ptr data, const char *types,
O2arg_ptr *argv, int argc, const void *user_data)
{
assert(argc == arg_count);
o2_extract_start(data);
for (int i = 0; i < arg_count; i++) {
assert(*types == 'h');
assert(argv[i]);
#ifndef NDEBUG
int64_t actual = argv[i]->h; // only needed for assert()
#endif
assert(actual == i + 1234);
types++;
}
assert(*types == 0); // end of string, got arg_count floats
got_the_message = true;
}
void send_the_message()
{
while (!got_the_message) {
o2_poll();
}
got_the_message = false;
}
int main(int argc, const char * argv[])
{
const int N = 100;
char address[32];
char types[200];
o2_initialize("test");
o2_service_new("one");
// send from 0 to N-1 floats, without coercion
for (int i = 0; i < N; i++) {
sprintf(address, "/one/f%d", i);
for (int j = 0; j < i; j++) {
types[j] = O2_FLOAT;
}
types[i] = 0;
o2_method_new(address, types, &service_f, NULL, false, false);
o2_send_start();
for (int j = 0; j < i; j++) {
o2_add_float(j + 123.0F);
}
arg_count = i;
o2_send_finish(0, address, true);
send_the_message();
}
printf("DONE sending 0 to %d floats\n", N - 1);
// send from 0 to N-1 doubles, without coercion
for (int i = 0; i < N; i++) {
sprintf(address, "/one/d%d", i);
for (int j = 0; j < i; j++) {
types[j] = O2_DOUBLE;
}
types[i] = 0;
o2_method_new(address, types, &service_d, NULL, false, false);
o2_send_start();
for (int j = 0; j < i; j++) {
o2_add_double(j + 1234);
}
arg_count = i;
o2_send_finish(0, address, true);
send_the_message();
}
printf("DONE sending 0 to %d doubles\n", N - 1);
// send from 0 to N-1 floats, with coercion to int and parsing
for (int i = 0; i < N; i++) {
sprintf(address, "/one/fc%d", i);
for (int j = 0; j < i; j++) {
types[j] = 'i';
}
types[i] = 0;
o2_method_new(address, types, &service_fc, NULL, true, true);
o2_send_start();
for (int j = 0; j < i; j++) {
o2_add_float(j + 123.0F);
}
arg_count = i;
o2_send_finish(0, address, true);
send_the_message();
}
printf("DONE sending 0 to %d floats coerced to ints with parsing\n",
N - 1);
// send from 0 to N-1 doubles, with coercion to int64_t and parsing
for (int i = 0; i < N; i++) {
sprintf(address, "/one/dc%d", i);
for (int j = 0; j < i; j++) {
types[j] = 'h';
}
types[i] = 0;
o2_method_new(address, types, &service_dc, NULL, true, true);
o2_send_start();
for (int j = 0; j < i; j++) {
o2_add_double(j + 1234);
}
arg_count = i;
o2_send_finish(0, address, true);
send_the_message();
}
printf("DONE sending 0 to %d doubles coerced to int64_t with parsing\n",
N - 1);
printf("DONE\n");
o2_finish();
return 0;
}
| true |
c5b5aad687214a9da0d63b2380d8c7b827a99602 | C++ | misoboute/modern-cpp-challenges | /test/chapter01/primenumbers.cpp | UTF-8 | 3,200 | 3 | 3 | [
"MIT"
] | permissive | #include <gtest/gtest.h>
#include "PrimeNumbers.h"
using testing::Test;
using namespace modcppchal::math;
struct PrimeNumbersFixture : public Test
{
PrimeNumbersFixture()
{
}
~PrimeNumbersFixture()
{
}
PrimeNumbers m_Primes;
};
TEST_F(PrimeNumbersFixture, IsPrimeReturnFalseForAllNegatives)
{
EXPECT_EQ(m_Primes.IsPrime(-1), false);
EXPECT_EQ(m_Primes.IsPrime(-2), false);
EXPECT_EQ(m_Primes.IsPrime(-3), false);
EXPECT_EQ(m_Primes.IsPrime(-4), false);
EXPECT_EQ(m_Primes.IsPrime(-5), false);
EXPECT_EQ(m_Primes.IsPrime(-6), false);
EXPECT_EQ(m_Primes.IsPrime(-7), false);
EXPECT_EQ(m_Primes.IsPrime(-1000000), false);
}
TEST_F(PrimeNumbersFixture, IsPrimeReturnsFalseForZeroAndOne)
{
EXPECT_EQ(m_Primes.IsPrime(0), false);
EXPECT_EQ(m_Primes.IsPrime(1), false);
}
TEST_F(PrimeNumbersFixture, IsPrimeReturnsTrueFor2_3_5_7)
{
EXPECT_EQ(m_Primes.IsPrime(2), true);
EXPECT_EQ(m_Primes.IsPrime(3), true);
EXPECT_EQ(m_Primes.IsPrime(5), true);
EXPECT_EQ(m_Primes.IsPrime(7), true);
}
TEST_F(PrimeNumbersFixture, IsPrimeReturnsTrueForPrimeNumbers)
{
EXPECT_EQ(m_Primes.IsPrime(11), true);
EXPECT_EQ(m_Primes.IsPrime(13), true);
EXPECT_EQ(m_Primes.IsPrime(17), true);
EXPECT_EQ(m_Primes.IsPrime(19), true);
EXPECT_EQ(m_Primes.IsPrime(23), true);
EXPECT_EQ(m_Primes.IsPrime(29), true);
EXPECT_EQ(m_Primes.IsPrime(31), true);
EXPECT_EQ(m_Primes.IsPrime(37), true);
EXPECT_EQ(m_Primes.IsPrime(43), true);
EXPECT_EQ(m_Primes.IsPrime(47), true);
EXPECT_EQ(m_Primes.IsPrime(53), true);
EXPECT_EQ(m_Primes.IsPrime(61), true);
EXPECT_EQ(m_Primes.IsPrime(67), true);
EXPECT_EQ(m_Primes.IsPrime(71), true);
EXPECT_EQ(m_Primes.IsPrime(73), true);
EXPECT_EQ(m_Primes.IsPrime(79), true);
EXPECT_EQ(m_Primes.IsPrime(83), true);
EXPECT_EQ(m_Primes.IsPrime(89), true);
EXPECT_EQ(m_Primes.IsPrime(97), true);
EXPECT_EQ(m_Primes.IsPrime(10007), true);
}
TEST_F(PrimeNumbersFixture, IsPrimeReturnsFalseFor4_6_8_9)
{
EXPECT_EQ(m_Primes.IsPrime(4), false);
EXPECT_EQ(m_Primes.IsPrime(6), false);
EXPECT_EQ(m_Primes.IsPrime(8), false);
EXPECT_EQ(m_Primes.IsPrime(9), false);
}
TEST_F(PrimeNumbersFixture, IsPrimeReturnsFalseForSomeNonPrimes)
{
EXPECT_EQ(m_Primes.IsPrime(10), false);
EXPECT_EQ(m_Primes.IsPrime(12), false);
EXPECT_EQ(m_Primes.IsPrime(14), false);
EXPECT_EQ(m_Primes.IsPrime(15), false);
EXPECT_EQ(m_Primes.IsPrime(16), false);
EXPECT_EQ(m_Primes.IsPrime(20), false);
EXPECT_EQ(m_Primes.IsPrime(25), false);
EXPECT_EQ(m_Primes.IsPrime(888), false);
}
TEST_F(PrimeNumbersFixture, IndexedPrimeNumbers)
{
EXPECT_EQ(m_Primes[0], 2);
EXPECT_EQ(m_Primes[1], 3);
EXPECT_EQ(m_Primes[2], 5);
EXPECT_EQ(m_Primes[3], 7);
EXPECT_EQ(m_Primes[4], 11);
EXPECT_EQ(m_Primes[5], 13);
EXPECT_EQ(m_Primes[6], 17);
EXPECT_EQ(m_Primes[7], 19);
EXPECT_EQ(m_Primes[8], 23);
EXPECT_EQ(m_Primes[9], 29);
EXPECT_EQ(m_Primes[10], 31);
EXPECT_EQ(m_Primes[14], 47);
EXPECT_EQ(m_Primes[22], 83);
EXPECT_EQ(m_Primes[29], 113);
EXPECT_EQ(m_Primes[168], 1009);
}
| true |
9cc3360c28c70b3bde9e6c2372edb5343983b0bb | C++ | justinnqs/ITP-435-Projects | /pa7-justinnqs-master/src/Node.cpp | UTF-8 | 3,393 | 2.796875 | 3 | [] | no_license | #include "Node.h"
#include <sstream>
void NBlock::AddStatement(NStatement* statement)
{
mStatements.emplace_back(statement);
}
void NBlock::CodeGen(CodeContext& context) const
{
// TODO: Loop through statements in list and code gen them
for (NStatement* statement : mStatements)
{
statement->CodeGen(context);
}
if(mMainBlock)
{
context.mOps.emplace_back("goto,1");
context.mGoTos.insert(std::make_pair(context.mOps.size(),1));
}
if(mOptimize)
{
std::map<int,int>::iterator it1;
for(it1 = context.mGoTos.begin(); it1 != context.mGoTos.end(); ++it1)
{
std::vector<int> changeGoTos;
std::map<int,int>::iterator it2;
int end = 0;
changeGoTos.emplace_back(it1->first);
it2 = context.mGoTos.find(it1->second);
while(it2 != context.mGoTos.end())
{
changeGoTos.emplace_back(it2->first);
end = it2->second;
it2 = context.mGoTos.find(it2->second);
}
if(changeGoTos.size() > 1)
{
for(int i = 0; i < changeGoTos.size(); i++)
{
context.mOps[changeGoTos[i]-1] = "goto," + std::to_string(end);
}
}
}
}
}
NNumeric::NNumeric(std::string& value)
{
mValue = std::stoi(value);
}
NRotate::NRotate(NNumeric* dir)
: mDir(dir)
{
}
void NRotate::CodeGen(CodeContext& context) const
{
if (mDir->mValue == 0)
{
context.mOps.emplace_back("rotate,0");
}
else if (mDir->mValue == 1)
{
context.mOps.emplace_back("rotate,1");
}
}
void NForward::CodeGen(CodeContext & context) const
{
context.mOps.emplace_back("forward");
}
void NRangedAttack::CodeGen(CodeContext & context) const
{
context.mOps.emplace_back("ranged_attack");
}
void NAttack::CodeGen(CodeContext & context) const
{
context.mOps.emplace_back("attack");
}
NIfElse::NIfElse(NBoolean* boolVal, NBlock* ifBlock, NBlock* elseBlock)
: mBoolVal(boolVal), mIfBlock(ifBlock), mElseBlock(elseBlock)
{
}
void NIfElse::CodeGen(CodeContext &context) const
{
int je, go, ifLine, elseLine;
mBoolVal->CodeGen(context);
context.mOps.emplace_back("je,");
je = context.mOps.size()-1;
mElseBlock->CodeGen(context);
elseLine = context.mOps.size();
context.mOps.emplace_back("goto,");
go = context.mOps.size()-1;
mIfBlock->CodeGen(context);
ifLine = context.mOps.size();
context.mOps[je] = "je," + std::to_string(elseLine+2);
context.mOps[go] = "goto," + std::to_string(ifLine+1);
context.mGoTos.insert(std::make_pair(go+1, ifLine+1));
}
IsHuman::IsHuman(NNumeric* dir)
: mDir(dir)
{
}
void IsHuman::CodeGen(CodeContext & context) const
{
context.mOps.emplace_back("test_human," + std::to_string(mDir->mValue));
}
IsZombie::IsZombie(NNumeric* dir) : mDir(dir)
{
}
void IsZombie::CodeGen(CodeContext & context) const
{
context.mOps.emplace_back("test_zombie," + std::to_string(mDir->mValue));
}
void IsPassable::CodeGen(CodeContext & context) const
{
context.mOps.emplace_back("test_passable");
}
void IsRandom::CodeGen(CodeContext & context) const
{
context.mOps.emplace_back("test_random");
}
void IsWall::CodeGen(CodeContext & context) const
{
context.mOps.emplace_back("test_wall");
}
| true |
d366b2610f6f3231eab3cb8314ee8e66044879e1 | C++ | SeboCode/ETHZ-AlgoLab-2020 | /exercise_11/fighting_pits_of_meereen/main.cpp | UTF-8 | 4,405 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <map>
#include <cmath>
int mask24 = std::pow(2, 24) - 1;
int mask16 = std::pow(2, 16) - 1;
int mask8 = std::pow(2, 8) - 1;
struct State {
int gateDifference;
// We use 8 bits to represent a fighterType.
int lastSentFightersNorth;
int lastSentFightersSouth;
int mask;
State() {};
State(int fighterCount) :
gateDifference(0), lastSentFightersNorth(0), lastSentFightersSouth(0), mask(fighterCount == 2 ? mask16 : mask24) {}
State(State const & other) :
gateDifference(other.gateDifference),
lastSentFightersNorth(other.lastSentFightersNorth),
lastSentFightersSouth(other.lastSentFightersSouth),
mask(other.mask) {}
void sendFighter(int fighterType, bool isNorth) {
if (isNorth) {
lastSentFightersNorth = ((lastSentFightersNorth << 8) & mask) + (fighterType & mask8);
gateDifference--;
} else {
lastSentFightersSouth = ((lastSentFightersSouth << 8) & mask) + (fighterType & mask8);
gateDifference++;
}
}
int calculateExcitement(bool isNorth) const {
int fighters = lastSentFightersSouth;
if (isNorth) {
fighters = lastSentFightersNorth;
}
int firstFighter = fighters & mask8;
int secondFighter = (fighters >> 8) & mask8;
int thirdFighter = (fighters >> 16) & mask8;
int excitementFactor = (firstFighter && firstFighter != secondFighter && firstFighter != thirdFighter) + (secondFighter && secondFighter != thirdFighter) + (thirdFighter != 0);
return excitementFactor * 1000 - (1 << std::abs(gateDifference));
}
bool operator <(State const & rhs) const {
if (lastSentFightersNorth != rhs.lastSentFightersNorth) {
return lastSentFightersNorth < rhs.lastSentFightersNorth;
}
if (lastSentFightersSouth != rhs.lastSentFightersSouth) {
return lastSentFightersSouth < rhs.lastSentFightersSouth;
}
return gateDifference < rhs.gateDifference;
}
};
void storeBestExcitementScore(std::map<State, int> & next, State const & state, bool isNorth, int currentExcitement) {
int roundExcitement = state.calculateExcitement(isNorth);
if (roundExcitement < 0) {
return;
}
const auto it = next.find(state);
if (it != next.end()) {
// It can happen that we end up in the same state, as we can add a
// fighter to the south or the north. Therefore we could have one state,
// where adding the current fighter to the north gives us state S and
// another state, where adding the current fighter to the south gives
// us S as well.
it->second = std::max(it->second, roundExcitement + currentExcitement);
} else {
next.emplace_hint(it, state, roundExcitement + currentExcitement);
}
}
void testcase() {
int n; std::cin >> n;
int k; std::cin >> k; // useless
int m; std::cin >> m;
// We store the best possible excitement level for each state that we can
// be in, after each fighter that has been processed.
std::map<State, int> current;
current.insert({State(m), 0});
std::map<State, int> next;
for (int i = 0; i < n; i++) {
int fighterType; std::cin >> fighterType; fighterType++;
next.clear();
for (auto const & element : current) {
State chooseNorthState(element.first);
chooseNorthState.sendFighter(fighterType, true);
storeBestExcitementScore(next, chooseNorthState, true, element.second);
State chooseSouthState(element.first);
chooseSouthState.sendFighter(fighterType, false);
storeBestExcitementScore(next, chooseSouthState, false, element.second);
}
// With this, current once again contains all possible states with its
// maximal excitement level.
std::swap(next, current);
}
int best = 0;
for (auto const & element : current) {
best = std::max(best, element.second);
}
std::cout << best << std::endl;
}
int main() {
std::ios_base::sync_with_stdio(false);
int t; std::cin >> t;
for (int i = 0; i < t; i++) {
testcase();
}
}
| true |
0ce3bec76d4cb299c040a1784395904ab0d94fb4 | C++ | kyung01/Abyss-Mining-Corporation | /Abyss-Mining-Corporation/World.cpp | UTF-8 | 761 | 2.765625 | 3 | [] | no_license | #include "World.h"
using namespace NGame;
void World::init(int worldWidth, int worldHeight)
{
mTiles.resize(worldWidth, worldHeight);
int values = 0;
int simHeight = (int)(worldHeight / 2);
//add sims
for (int i = 0; i < worldWidth; i++) {
addSim(i, simHeight);
}
}
//event listeners
void NGame::World::onSimMovedTo(Sim &sim, int fromX, int fromY, int toX, int toY) {
if (sim.getIsMaterial()){
mTiles.out(sim, fromX, fromY);
mTiles.on(sim, toX, toY);
}
}
//member functions
void NGame::World::update(float timeElapsed)
{
}
void NGame::World::addSim(int x, int y)
{
Sim sim = Sim().setPosition(x, y);
sim.link(this);
mSims.assign(sim);
mTiles.on(sim, x, y);
}
Sim& NGame::World::getSim(int x, int y)
{
return *mTiles.getSim(x, y);
}
| true |
9988a0f227c9a19ca80350d18a111bb437820a72 | C++ | QLubov/ConfShooter | /ConfShooter/ConfigFile.cpp | UTF-8 | 686 | 2.53125 | 3 | [] | no_license | #include "ConfigFile.h"
#include "pugixml.hpp"
using namespace pugi;
ConfigFile::ConfigFile(const std::string& file)
{
xml_document doc;
doc.load_file(file.c_str());
ReadGraphics(doc);
ReadOptions(doc);
}
ConfigFile::~ConfigFile(void)
{
}
void ConfigFile::ReadGraphics(pugi::xml_document &doc)
{
xml_node graphics = doc.child("graphics");
width = graphics.child("width").text().as_int();
height = graphics.child("height").text().as_int();
mode = graphics.child("screenMode").text().as_bool();
}
void ConfigFile::ReadOptions(pugi::xml_document &doc)
{
xml_node options = doc.child("options");
level = options.child("level").text().as_string();
} | true |
9b9fe166442a04687896f4d89752459fbf92b175 | C++ | Hyperzsb/bit-cs | /2020/object-oriented-technology-and-methods/exam/topic-1/complex.h | UTF-8 | 944 | 3.171875 | 3 | [
"MIT"
] | permissive | #ifndef TOPIC_1_COMPLEX_H
#define TOPIC_1_COMPLEX_H
#include <iostream>
class Complex {
private:
/*
* 复数的实部
*/
double real;
/*
* 复数的虚部
*/
double image;
public:
/*
* 类的默认构造函数
*/
Complex();
/*
* 类的带有两个双精度浮点数的构造函数,分别定义了复数的实部和虚部
*/
Complex(double real_,double image_);
/*
* 类的拷贝构造函数
*/
Complex(const Complex &complex_);
/*
* 重载+运算符,实现两个复数对象的相加
*/
Complex &operator+(const Complex &complex_);
/*
* 重载+=运算符
*/
Complex &operator+=(const Complex &complex_);
/*
* 重载<<流输出运算符,实现复数对象的流输出
*/
friend std::ostream &operator<<(std::ostream &ostream_, const Complex &complex_);
};
#endif //TOPIC_1_COMPLEX_H
| true |
62361d49fa9e6019415aa0367b0fb5d6fd8eabc5 | C++ | TlStephen2011/myCode | /COS1512_ASS02_Q7/RepeatPrescription.h | UTF-8 | 644 | 2.78125 | 3 | [] | no_license | #ifndef REPEATPRESCRIPTION_H
#define REPEATPRESCRIPTION_H
#include <iostream>
#include "Prescription.h"
using namespace std;
class RepeatPrescription : public Prescription {
public:
// default constructor
RepeatPrescription();
// overloaded constructor
RepeatPrescription(string med, string pName, string fund, int num, double c,
int repeats, int date);
// updates prescription
void issuePrescription(int d);
// overides DisplayInfo
void DisplayInfo();
// accessors
int getRepeats();
int getDateIssued();
private:
int numberOfRepeats;
int lastDateIssued;
};
#endif // REPEATPRESCRIPTION_H | true |
cf9b7a6091fe083b766df1fda8eced609ca409d0 | C++ | fantauzzi/SFND_Lidar_Obstacle_Detection | /src/environment.cpp | UTF-8 | 10,434 | 2.75 | 3 | [] | no_license | /* \author of the original Aaron Brown*/
// Create simple 3d highway environment using PCL
// for exploring self-driving car sensors
#include "sensors/lidar.h"
#include "render/render.h"
#include "processPointClouds.h"
// using templates for processPointClouds so also include .cpp to help linker
#include "processPointClouds.cpp"
#include "processing.h"
#include <pcl/impl/point_types.hpp>
#include <memory>
#include <thread>
std::vector<Car> initHighway(bool renderScene, pcl::visualization::PCLVisualizer::Ptr &viewer) {
Car egoCar(Vect3(0, 0, 0), Vect3(4, 2, 2), Color(0, 1, 0), "egoCar");
Car car1(Vect3(15, 0, 0), Vect3(4, 2, 2), Color(0, 0, 1), "car1");
Car car2(Vect3(8, -4, 0), Vect3(4, 2, 2), Color(0, 0, 1), "car2");
Car car3(Vect3(-12, 4, 0), Vect3(4, 2, 2), Color(0, 0, 1), "car3");
std::vector<Car> cars;
cars.push_back(egoCar);
cars.push_back(car1);
cars.push_back(car2);
cars.push_back(car3);
if (renderScene) {
renderHighway(viewer);
egoCar.render(viewer);
car1.render(viewer);
car2.render(viewer);
car3.render(viewer);
}
return cars;
}
void simpleHighway(pcl::visualization::PCLVisualizer::Ptr &viewer) {
// ----------------------------------------------------
// -----Open 3D viewer and display simple highway -----
// ----------------------------------------------------
// RENDER OPTIONS
bool renderScene = false;
std::vector<Car> cars = initHighway(renderScene, viewer);
// DONE:: Create lidar sensor
auto pLidar = std::make_unique<Lidar>(cars, 0);
// DONE:: Create point processor
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud = pLidar->scan();
// renderRays(viewer, pLidar->position, cloud);
// renderPointCloud(viewer, cloud, "cloud");
ProcessPointClouds<pcl::PointXYZ> process;
std::pair<typename pcl::PointCloud<pcl::PointXYZ>::Ptr, typename pcl::PointCloud<pcl::PointXYZ>::Ptr> segmentedCloud = process.SegmentPlane(cloud, 100, .2);
// renderPointCloud(viewer, segmentedCloud.first, "Obstructions", Color(1, 0, 0));
renderPointCloud(viewer, segmentedCloud.second, "Plane", Color(0, 1, 0));
std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr> cloudClusters = process.Clustering(segmentedCloud.first,
1.0,
3,
30);
int clusterId = 0;
std::vector<Color> colors = {Color(1, 0, 0), Color(1, 1, 0), Color(0, 0, 1)};
for (pcl::PointCloud<pcl::PointXYZ>::Ptr cluster : cloudClusters) {
std::cout << "cluster size ";
process.numPoints(cluster);
renderPointCloud(viewer, cluster, "obstCloud" + std::to_string(clusterId), colors[clusterId]);
Box box = process.BoundingBox(cluster);
renderBox(viewer, box, clusterId);
++clusterId;
}
}
//setAngle: SWITCH CAMERA ANGLE {XY, TopDown, Side, FPS}
void initCamera(CameraAngle setAngle, pcl::visualization::PCLVisualizer::Ptr &viewer) {
viewer->setBackgroundColor(0, 0, 0);
// set camera position and angle
viewer->initCameraParameters();
// distance away in meters
int distance = 16;
switch (setAngle) {
case XY :
viewer->setCameraPosition(-distance, -distance, distance, 1, 1, 0);
break;
case TopDown :
viewer->setCameraPosition(0, 0, distance, 1, 0, 1);
break;
case Side :
viewer->setCameraPosition(0, -distance, 0, 0, 0, 1);
break;
case FPS :
viewer->setCameraPosition(-10, 0, 0, 0, 0, 1);
}
if (setAngle != FPS)
viewer->addCoordinateSystem(1.0);
}
class Timer {
std::chrono::time_point<std::chrono::steady_clock> startTime = std::chrono::steady_clock::now();
public:
long elapsed() const {
std::chrono::duration<double, std::milli> res = std::chrono::steady_clock::now() - startTime;
return res.count();
}
void reset() {
startTime = std::chrono::steady_clock::now();
}
long fetch_and_restart() {
auto savedStart = startTime;
reset();
std::chrono::duration<double, std::milli> res = std::chrono::steady_clock::now() - savedStart;
return res.count();
}
};
void cityBlock(pcl::visualization::PCLVisualizer::Ptr &viewer,
ProcessPointClouds<pcl::PointXYZI> processor,
const pcl::PointCloud<pcl::PointXYZI>::Ptr &inputCloud) {
// ----------------------------------------------------
// -----Open 3D viewer and display City Block -----
// ----------------------------------------------------
Timer theTimer;
// --------------------------------------------------------------------------------------------
// Filter the point cloud to remove points belonging to the car with lidar and outside the road
// --------------------------------------------------------------------------------------------
pcl::PointCloud<pcl::PointXYZI>::Ptr filteredCloud = processor.FilterCloud(inputCloud, .1, Eigen::Vector4f(-20, -6.5, -2, 1),
Eigen::Vector4f(40, 7.1, 2, 1));
std::cout << "Filtering took " << theTimer.fetch_and_restart() << " milliseconds" << std::endl;
// --------------------------------------------------------------------------------------------
// Detect the road (plane) in the point cloud
// --------------------------------------------------------------------------------------------
std::pair<typename pcl::PointCloud<pcl::PointXYZI>::Ptr, typename pcl::PointCloud<pcl::PointXYZI>::Ptr > segmentedCloud = Ransac(filteredCloud, 100, .2);
std::cout << "Segmentation took " << theTimer.fetch_and_restart() << " milliseconds" << std::endl;
// Draw the points belonging to the road, in green
renderPointCloud(viewer, segmentedCloud.second, "Plane", Color(0, 1, 0));
theTimer.fetch_and_restart();
/* Compile a vector of vectors with all the points that passed the filter and do not belong to the road
* (they are obstacles). Each point is represented with a vector with 4 coordinates XYZI. */
std::vector<std::vector<float>> points(segmentedCloud.first->size());
// typedef std::vector<pcl::PointXYZI, Eigen::aligned_allocator<pcl::PointXYZI>> PointsVector;
for (int i = 0; i < segmentedCloud.first->size(); ++i) {
auto &source_point = segmentedCloud.first->points[i];
std::vector<float> point_vec = {source_point.x, source_point.y, source_point.z, source_point.intensity};
points[i] = point_vec;
}
// Build the KD-Tree that will be used for clustering, and populate it with points from obstacles
auto *tree = new KdTree;
for (int i = 0; i < points.size(); i++)
tree->insert(points[i], i);
std::cout << "Building the KD-tree took " << theTimer.fetch_and_restart() << " milliseconds" << std::endl;
// --------------------------------------------------------------------------------------------
// Cluster points belonging to obstacles
// --------------------------------------------------------------------------------------------
std::vector<std::vector<int>> clusters_vec = euclideanCluster(points, tree, .3, 30);
std::cout << "Clustering took " << theTimer.fetch_and_restart() << " milliseconds" << std::endl;
// typedef std::vector<PointT, Eigen::aligned_allocator<PointT> > VectorType;
// Convert the output of clustering to a format suitable for graphic display with PCL
std::vector<pcl::PointCloud<pcl::PointXYZI>::Ptr> cloudClusters;
for (const auto &cluster_vec: clusters_vec) {
typename pcl::PointCloud<pcl::PointXYZI>::Ptr cloud_cluster(new pcl::PointCloud<pcl::PointXYZI>);
for (const auto &index: cluster_vec) {
pcl::PointXYZI newPoint;
newPoint.x = points[index][0];
newPoint.y = points[index][1];
newPoint.z = points[index][2];
newPoint.intensity = points[index][3];
cloud_cluster->points.emplace_back(newPoint);
}
cloud_cluster->height = 1;
cloud_cluster->width = clusters_vec.size();
cloud_cluster->is_dense = true;
cloudClusters.emplace_back(cloud_cluster);
}
std::cout << "Handling the clustering output took " << theTimer.fetch_and_restart() << " milliseconds" << std::endl;
std::cout << "Got " << cloudClusters.size() << " cluster(s)" << std::endl;
int clusterId = 0;
std::vector<Color> colors = {Color(1, 0, 0), Color(1, 1, 0), Color(0, 0, 1)};
for (const auto &cluster : cloudClusters) {
// std::cout << "cluster size ";
// processor.numPoints(cluster);
renderPointCloud(viewer, cluster, "obstCloud" + std::to_string(clusterId), colors[clusterId % colors.size()]);
Box box = processor.BoundingBox(cluster);
renderBox(viewer, box, clusterId);
++clusterId;
}
}
int main(int argc, char **argv) {
std::cout << "starting enviroment" << std::endl;
pcl::visualization::PCLVisualizer::Ptr viewer(new pcl::visualization::PCLVisualizer("3D Viewer"));
CameraAngle setAngle = XY;
initCamera(setAngle, viewer);
// simpleHighway(viewer);
ProcessPointClouds<pcl::PointXYZI> processor;
std::vector<boost::filesystem::path> stream = processor.streamPcd("../src/sensors/data/pcd/data_1");
auto streamIterator = stream.begin();
pcl::PointCloud<pcl::PointXYZI>::Ptr inputCloudI;
/*while (!viewer->wasStopped()) {
viewer->spinOnce();
}*/
while (!viewer->wasStopped()) {
Timer theTimer;
// Clear viewer
viewer->removeAllPointClouds();
viewer->removeAllShapes();
// Load pcd and run obstacle detection process
inputCloudI = processor.loadPcd((*streamIterator).string());
cityBlock(viewer, processor, inputCloudI);
streamIterator++;
if (streamIterator == stream.end())
streamIterator = stream.begin();
viewer->spinOnce();
using namespace std::chrono_literals;
// std::this_thread::sleep_for(1s);
std::cout << "FPS=" << 1000. / theTimer.elapsed() << std::endl << std::endl;
}
} | true |
fc75a6cf28692be1ff73aec2eb92ed5b2c33b04c | C++ | MahsaAbbasian/basicCplusPlus | /randomSum.cpp | UTF-8 | 1,230 | 3.75 | 4 | [] | no_license | #include<iostream>
#include<time.h>
#include<cstdlib>
using namespace std;
int main(){
int randomNumber1, randomNumber2, maxRand, sumOfRandNumbers, userInput;
cout<<"Please enter Maximum range of random numbers you wish to have"<<endl;
cin>>maxRand;
/* srand(time(null)); makes use of the computer's internal clock(since time is changing continually so seeds keep changing forever)
to control the choice of seed.
in order to simulate a random number we need two bult in c++ functions, rand() and srand().
srand() is used to provide seed for generating random numbers
rand() is used to generate next random number in sequence.
*/
srand(time(0));
randomNumber1 = (rand()%maxRand)+1;
randomNumber2 = (rand()%maxRand)+1;
sumOfRandNumbers = randomNumber1 + randomNumber2 ;
cout<<"Random number1 is equal to "<<randomNumber1<<endl;
cout<<"Random number2 is equal to "<<randomNumber2<<endl;
cout<<randomNumber1<< "+" <<randomNumber2<< "= ? " <<endl;
cout<<"Please guest a number and enter below "<<endl;
cin>>userInput;
if (userInput==sumOfRandNumbers)
{
cout<<"congradulate your answer is correct"<<endl;
}else{
cout<<"your is wrong and correct answer is = "<<sumOfRandNumbers<<endl;
}
return 0;
} | true |
36907ecf89fd85f673e361602fc13f1d9493882c | C++ | sureshmangs/Code | /competitive programming/leetcode/1408. String Matching in an Array.cpp | UTF-8 | 1,181 | 3.234375 | 3 | [
"MIT"
] | permissive | Given an array of string words. Return all strings in words which is substring of another word in any order.
String words[i] is substring of words[j], if can be obtained removing some characters to left and/or right side of words[j].
Example 1:
Input: words = ["mass","as","hero","superhero"]
Output: ["as","hero"]
Explanation: "as" is substring of "mass" and "hero" is substring of "superhero".
["hero","as"] is also a valid answer.
Example 2:
Input: words = ["leetcode","et","code"]
Output: ["et","code"]
Explanation: "et", "code" are substring of "leetcode".
Example 3:
Input: words = ["blue","green","bu"]
Output: []
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 30
words[i] contains only lowercase English letters.
It's guaranteed that words[i] will be unique.
class Solution {
public:
vector<string> stringMatching(vector<string>& words) {
int n=words.size();
vector<string> res;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(i!=j && words[j].find(words[i])!=-1){
res.push_back(words[i]); break;
}
}
}
return res;
}
};
| true |
e7bfa4d010f4dc53c862cc7c9d4deb852286a950 | C++ | SaulZhang/NJU-Summary-Vocation-Camp-OJ | /2017A.cpp | GB18030 | 2,240 | 3.1875 | 3 | [] | no_license | /*
ڸöΪ˼ٶΪαĽ
Բòαķ
*/
#include <iostream>
#include <queue>
#include <stack>
#define N 1000+5
using namespace std;
int loc;
int n,sum;
void init(){
loc = 0;
}
int A[N];
struct TreeNode{
int data;
TreeNode* lchild;
TreeNode* rchild;
}Tree[N];
TreeNode* create(){
Tree[loc].lchild=Tree[loc].rchild=NULL;
return &Tree[loc++];
}
queue<TreeNode*> Que;
stack<int> S,Stmp;
vector<int> res;
void dfs(TreeNode* T,int curSum){
S.push(T->data);
curSum+=T->data;
if(T->lchild==NULL&&T->rchild==NULL&&curSum==sum){
res.clear();
Stmp = S;
while(!Stmp.empty()){
res.push_back(Stmp.top());
Stmp.pop();
}
for(int i=res.size()-1;i>=0;i--){
cout<<res[i]<<" ";
}
cout<<endl;
}
if(T->lchild!=NULL)
dfs(T->lchild,curSum);
if(T->rchild!=NULL)
dfs(T->rchild,curSum);
curSum -= T->data;
S.pop();
}
int main()
{
while(~scanf("%d%d",&n,&sum)){
for(int i=0;i<n;i++)
cin>>A[i];
while(!Que.empty())
Que.pop();
while(!S.empty())
S.pop();
TreeNode* T = create();
T->data = A[0];
Que.push(T);
int pos=0;
while(!Que.empty()){//α
TreeNode* tmp = Que.front();
Que.pop();
if(pos<n&&A[++pos]!=-1){
TreeNode* lt = create();
lt->data = A[pos];
tmp->lchild = lt;
Que.push(lt);
}
if(pos<n&&A[++pos]!=-1){
TreeNode* rt = create();
rt->data = A[pos];
tmp->rchild = rt;
Que.push(rt);
}
}
dfs(T,0);
}
return 0;
}
/*
7 2
1 1 1 -1 -1 -1 -1
31 14
3 4 5 7 6 2 5 6 3 2 1 2 4 3 2 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
31 22
5 4 8 11 -1 13 4 7 2 -1 -1 -1 -1 5 1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
*/
| true |
35a5ea2f3cd295df7c56bda89a09910b183f0b68 | C++ | sabhya19/C-Plus-Plus | /data_structures/searchsorted_LL.cpp | UTF-8 | 1,018 | 3.75 | 4 | [
"MIT",
"CC-BY-SA-4.0"
] | permissive | #include <iostream>
using namespace std;
// searching in a sorted linked list
class node {
public:
int info;
node* link;
};
node* search(int, node*);
int main() {
int n, x, i = 1;
cin >> n;
node* start;
node* ptr;
node* temp;
start = new node;
start->info = 19;
ptr = start;
while (i < n - 1) {
temp = new node;
cin >> x;
temp->info = x;
ptr->link = temp;
ptr = temp;
i++;
// cout<<"moving to"<<i<<endl;
}
// cout<<"here1";
temp = new node;
cin >> x;
temp->info = x;
// cout<<"here2";
ptr->link = temp;
temp->link = NULL;
// searching a sorted array
int item;
cin >> item;
cout << "item found at" << search(item, start) << endl;
return 0;
}
node* search(int item, node* start) {
node* ptr;
ptr = start;
while (item <= ptr->info) {
if (item == ptr->info)
return ptr;
else
ptr = ptr->link;
}
return NULL;
}
| true |
f0bb689bbf53c22bee510bfadf44e57abb920993 | C++ | venediklee/School | /Programming Language Concepts(CENG242)/HW4/HW4-StudentPack/Tracer.h | UTF-8 | 1,007 | 3.234375 | 3 | [] | no_license | #ifndef HW4_TRACER_H
#define HW4_TRACER_H
#include "Player.h"
class Tracer : public Player {
public:
Tracer(uint id, int x, int y);
// Name : Tracer
// Priority : { UP, LEFT, DOWN, RIGHT, ATTACK }
// Armor : BRICK
// Weapon : SHOVEL
// HP : 100
// DO NOT MODIFY THE UPPER PART
// ADD OWN PUBLIC METHODS/PROPERTIES/OVERRIDES BELOW
~Tracer();
Armor getArmor() const;
Weapon getWeapon() const ;
/**
* Every player has a different priority move list.
* It's explained in the Players' header.
*
* @return The move priority list for the player.
*/
std::vector<Move> getPriorityList() const ;
/**
* Get the full name of the player.
*
* Example (Tracer with ID 92) = "Tracer92"
* Example (Tracer with ID 1) = "Tracer01"
*
* @return Full name of the player.
*/
const std::string getFullName() const;
//bool operator()(Tracer a,Tracer b);
};
#endif //HW4_TRACER_H
| true |
646b36bc9fa9b54eda7185286e1e367f7d9d56fc | C++ | amitprat/PracticeCode | /acessPrivateMembersOfClassUsingPointer.cpp | UTF-8 | 476 | 3.75 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Sol
{
int a,b;
public:
Sol(int a,int b) {
this->a = a;
this->b = b;
}
};
int main()
{
Sol obj(10,208);
void *ptr = (void *)&obj; //we can typecast anything to void pointer
cout<<*(int *)ptr<<endl; //point to first data member of class
cout<<*(int *)(ptr+4)<<endl; //increase pointer by 4 assuming int size to be 4 to point to next data member
return 0;
}
| true |
59e3321ffe776dd396b25cdca7a18b8eae81b170 | C++ | jhellerstein/arugula | /test/smoke/ints.cpp | UTF-8 | 1,486 | 2.96875 | 3 | [] | no_license | #include "../catch.hpp"
#include "lattice_core.hpp"
#include "merges/maxmin_mrg.hpp"
TEST_CASE("Binary IntMax") {
const Max m;
Lattice li(1, Max{});
Lattice ri(40, Max{});
auto expr = li + ri;
REQUIRE(expr.reveal() == 40);
}
TEST_CASE("Nary IntMax") {
Lattice li(1, Max{});
Lattice lj(40, Max{});
Lattice lk(50, Max{});
auto expr = li + lj + lk + li + lj;
REQUIRE(expr.reveal() == 50);
}
TEST_CASE("IntMax merges") {
Lattice li(1, Max{});
Lattice li3(3, Max{});
li += 2;
REQUIRE(li.reveal() == 2);
li += li3;
REQUIRE(li.reveal() == 3);
}
TEST_CASE("IntMax equality") {
Lattice l1(1,Max{});
Lattice l2(2,Max{});
Lattice l11(1,Max{});
REQUIRE(l1 == l11);
REQUIRE(!(l1 == l2));
REQUIRE(l1 != l2);
}
TEST_CASE("Binary IntMin") {
const Min m;
Lattice li(1, Min{});
Lattice lj(40, Min{});
auto expr = li + lj;
REQUIRE(expr.reveal() == 1);
}
TEST_CASE("Nary IntMin") {
Lattice li(1, Min{});
Lattice lj(40, Min{});
Lattice lk(50, Min{});
auto expr = li + lj + lk + li + lj;
REQUIRE(expr.reveal() == 1);
}
TEST_CASE("IntMin merges") {
Lattice li(1, Min{});
Lattice li3(3, Min{});
li3 += 2;
REQUIRE(li3.reveal() == 2);
li3 += li;
REQUIRE(li.reveal() == 1);
}
TEST_CASE("IntMin equality") {
Lattice l1(1,Min{});
Lattice l2(2,Min{});
Lattice l11(1,Min{});
REQUIRE(l1 == l11);
REQUIRE(!(l1 == l2));
REQUIRE(l1 != l2);
}
| true |
93d6eb0aebe59449679eda8793866210387c4642 | C++ | CauchYLIU3551/EigProblem | /c_min_trace/CG/poisson_equation/possion_equation.cpp | UTF-8 | 3,291 | 2.640625 | 3 | [
"MIT"
] | permissive | ////////////////////////////////////////////////////////////////////////////////////////////
// main1.cpp :
//
#include <iostream>
#include <fstream>
#include <AFEPack/AMGSolver.h>
#include <AFEPack/Geometry.h>
#include <AFEPack/TemplateElement.h>
#include <AFEPack/FEMSpace.h>
#include <AFEPack/Operator.h>
#include <AFEPack/Functional.h>
#include <AFEPack/EasyMesh.h>
#include <CG/CGSolver.h>
#define PI (4.0*atan(1.0))
double u(const double *);
double f(const double *);
clock_t start, end, start2, end2;
int main(int argc, char * argv[])
{
EasyMesh mesh;
mesh.readData(argv[1]);
TemplateGeometry<2> triangle_template_geometry;
triangle_template_geometry.readData("triangle.tmp_geo");
CoordTransform<2,2> triangle_coord_transform;
triangle_coord_transform.readData("triangle.crd_trs");
TemplateDOF<2> triangle_template_dof(triangle_template_geometry);
triangle_template_dof.readData("triangle.1.tmp_dof");
BasisFunctionAdmin<double,2,2> triangle_basis_function(triangle_template_dof);
triangle_basis_function.readData("triangle.1.bas_fun");
std::vector<TemplateElement<double,2,2> > template_element(1);
template_element[0].reinit(triangle_template_geometry,
triangle_template_dof,
triangle_coord_transform,
triangle_basis_function);
FEMSpace<double,2> fem_space(mesh, template_element);
int n_element = mesh.n_geometry(2);
fem_space.element().resize(n_element);
for (int i = 0;i < n_element;i ++)
fem_space.element(i).reinit(fem_space,i,0);
fem_space.buildElement();
fem_space.buildDof();
fem_space.buildDofBoundaryMark();
StiffMatrix<2,double> stiff_matrix(fem_space);
stiff_matrix.algebricAccuracy() = 4;
stiff_matrix.build();
FEMFunction<double,2> solution(fem_space), solution2(fem_space);
Vector<double> right_hand_side;
Operator::L2Discretize(&f, fem_space, right_hand_side, 4);
BoundaryFunction<double,2> boundary(BoundaryConditionInfo::DIRICHLET, 1, &u);
BoundaryConditionAdmin<double,2> boundary_admin(fem_space);
boundary_admin.add(boundary);
boundary_admin.apply(stiff_matrix, solution, right_hand_side);
boundary_admin.apply(stiff_matrix, solution2, right_hand_side);
AMGSolver solver(stiff_matrix);
start=clock();
solver.solve(solution, right_hand_side, 1.0e-08, 200);
end=clock();
CGSolver sol2(stiff_matrix);
start2=clock();
sol2.solve(solution2, right_hand_side, 1.0e-08, 200);
end2=clock();
solution.writeOpenDXData("u.dx");
double error = Functional::L2Error(solution, FunctionFunction<double>(&u), 3);
std::cerr << "\nL2 error = " << error << std::endl;
double error2 = Functional::L2Error(solution2, FunctionFunction<double>(&u), 3);
std::cerr << "\nL2 error2 from CG Solver = " << error2 << std::endl;
double endtime=(double)(end-start)/CLOCKS_PER_SEC;
double endtime2=(double)(end2-start2)/CLOCKS_PER_SEC;
std::cout<<"The computing time of AMGSolver is :::"<<1000*endtime<<" ms \n";
std::cout<<"The computing time of CGSolver is :::"<<1000*endtime2<<" ms \n";
return 0;
};
double u(const double * p)
{
return sin(PI*p[0]) * sin(2*PI*p[1]);
};
double f(const double * p)
{
return 5*PI*PI*u(p);
};
//
// end of file
////////////////////////////////////////////////////////////////////////////////////////////
| true |
7b44f733edfca3911f0008b72a4e1410c6969ebe | C++ | Davidlihuang/DataStructure | /DSAInCpp/capter1/segment1_9/include/personal.h | UTF-8 | 723 | 2.703125 | 3 | [] | no_license | #ifndef PERSONAL_H_
#define PERSONAL_H_
#include <fstream>
#include <iostream>
#include <cstring>
class Personal
{
public:
Personal();
Personal(char *, char *, char *, int, long);
//~Personal();
void writeToFile(std::fstream &) const;
void readFromFile(std::fstream &);
void readKey();
int size() const;
bool operator==(const Personal& p);
protected:
const int nameLen, cityLen;
char SSN[10], *name, *city;
int year;
long salary;
std::ostream &writeLegibly(std::ostream &);
friend std::ostream &operator<<(std::ostream &, Personal &);
std::istream &readFromConsoled(std::istream &);
friend std::istream &operator>>(std::istream &, Personal &);
};
#endif | true |
8c44f2cba14c24102bde128ba7580ec8e63ff152 | C++ | jazzpurr/popup14h | /algorithms/modular_arithmetic/handler.cpp | ISO-8859-1 | 856 | 2.6875 | 3 | [] | no_license | // Authors:
// Jesper Norberg, jenor@kth.se
// Didrik Nordstrm, didrikn@kth.se
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include "modular.h"
using namespace std;
//Source: http://en.wikipedia.org/wiki/Modular_arithmetic
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
long long a = -3;
long long b = 2;
long long m, nuoOperations;
long long x, y;
string op;
cin >> m >> nuoOperations;
while (m != 0){
for (long long i = 0; i < nuoOperations; i++){
cin >> x >> op >> y;
if (op == "+"){
printf("%d\n", add_mod(x, y, m));
}
else if (op == "-"){
printf("%d\n", sub_mod(x, y, m));
}
else if (op == "*"){
printf("%d\n", mul_mod(x, y, m));
}
else if (op == "/"){
printf("%d\n", div_mod(x, y, m));
}
else{
printf("Invalid input\n");
}
}
cin >> m >> nuoOperations;
}
return 0;
} | true |
36e14fcd305ed661159d03a13e8cf9f138d91c5a | C++ | icebear0516/cpp_study | /cpp_study/chapter3-4/code/test4_10.cpp | UTF-8 | 680 | 3.859375 | 4 | [] | no_license | /* 编写一个程序,让用户输入3次40米跑成绩,并显示次数和平均成绩
使用arry对象存储数据
version:0.1
author:李京泽 */
#include <iostream>
#include <array>
using namespace std;
int main()
{
array<float,3> time;
cout << "请输入您第一次40米成绩:";
cin >> time[0];
cin.get();
cout << "请输入您第二次40米成绩:";
cin >> time[1];
cin.get();
cout << "请输入您第三次40米成绩:";
cin >> time[2];
cin.get();
cout << "您的跑步次数为3次";
cout << "您的平均成绩为:" << (time[0] + time[1] + time[2]) / 3.0 << endl;
} | true |
e30ba31cff849f7cfa9dba5484371d5aec6a9b73 | C++ | alexanderbrannlund/ProjektRefereeGameBookQt | /RefereeGameBookDV1553/game.h | UTF-8 | 830 | 2.828125 | 3 | [] | no_license | #ifndef GAME_H
#define GAME_H
#include "referees.h"
#include <QString>
#include <QDate>
class Game
{
private:
QString homeTeam;
QString guestTeam;
QDate date;
int refID;
int penaltiesMin;
int penaltyShots;
int goals;
public:
Game(const QString& homeTeam, const QString& guestTeam, QDate date, int refID=-1, int penaltiesMin=0,int penaltyShots=0, int goals=0);
~Game();
int GetPenaltiesMin()const;
int GetPenaltyShots() const;
int GetGoals() const;
QDate GetDate();
int GetRefID()const;
void SetRefID(int refID);
void SetPenaltiesMin(int pMin);
void SetPenaltyShots(int pShots);
void SetGoals(int goals);
QString ToStringReadable(Referees* referees);
QString ToStringSaveable();
bool operator ==(const Game& other)const;
};
#endif // GAME_H
| true |
e40e3989d544afad04c1f982c821832c41fe1dd5 | C++ | Maakuz/ComponentLek | /Lite_Component_Lek/Lite_Component_Lek/CollisionBox.h | UTF-8 | 555 | 2.546875 | 3 | [] | no_license | #ifndef COLLISIONBOX_H
#define COLLISIONBOX_H
#include "Component.h"
#include "D3DHeader.h"
#include "SimpleMath.h"
#include <sstream>
class CollisionBox : public Component
{
private:
DirectX::SimpleMath::Vector3 mLength;
DirectX::SimpleMath::Vector3 mPos;
public:
CollisionBox(DirectX::SimpleMath::Vector3 pos, DirectX::SimpleMath::Vector3 length);
~CollisionBox();
bool intersects(const CollisionBox& otherBox);
void setPosition(DirectX::SimpleMath::Vector3 position);
std::string printPos() const;
std::string toString() const;
};
#endif | true |
a6a45b829248bee0b40e2f935b4ac67a99b6148d | C++ | thibalte/bitshift | /firmware/Bitshift-master/Bitshift-master.ino | UTF-8 | 938 | 2.8125 | 3 | [
"MIT"
] | permissive | //
// BITSHIFT
// Thibault Brevet, 2015
// release under the MIT license
//
// flash via Arduino IDE on ATTiny45/85 chips
//
int in = 3; // signal in
int shift = 1; // signal out
int heat = 2; // mosfet control
int heatTime = 15000; // how long we heat the panel
int wait = 5000;
int sigTime = 500; // how long we keep the OUT signal pulled high
int masterWait = 380;
void setup()
{
pinMode(in, INPUT);
pinMode(shift, OUTPUT);
pinMode(heat, OUTPUT);
}
void loop()
{
// first turn on HEAT at maximum to reach temperature for specified time
digitalWrite(heat, HIGH);
delay(heatTime);
digitalWrite(heat, LOW);
// wait some time before shifting to next board
delay(wait);
// then forward SIGNAL for specififed time
digitalWrite(shift, HIGH);
delay(sigTime);
digitalWrite(shift, LOW);
delay(100);
// do a loop because max val of delay() is 32767ms
for (int i=0; i<masterWait; i++){
delay(1000);
}
}
| true |
39478ad0652f43db64939bf9802a0390dda0d71e | C++ | YairHanimov/Searching_Algorithm_Server | /AStar.h | UTF-8 | 5,553 | 2.9375 | 3 | [] | no_license | #ifndef SEARCHING_ALGORITHM_SERVER_ASTAR_H
#define SEARCHING_ALGORITHM_SERVER_ASTAR_H
#include "Searcher.h"
#include "queue"
#include "set"
#include "PriorityQueueState.h"
#include "Cell.h"
#include "compar.h"
#include "Matrix.h"
#include "comparforset.h"
#include "compareStar.h"
using namespace std;
template<class T>
class AStar : public Searcher<T> {
public:
explicit AStar() {
}
string search(Matrix *problem) {
vector<State<T>> path;
vector<string> direct;
double minPath = -1;
double currentPathCost = 0;
priority_queue<State<T> *, vector<State<T> *>, compareStar> mypq; // a priority queue of states to be evaluated
auto initialNode = problem->getInitialState();
initialNode.setShortestPath(initialNode.getCost());
problem->givemegoalcell().setHeuristic(0);
initialNode.setHeuristic(initialNode.getObj(), problem->givemegoalcell().getObj());
mypq.push(&initialNode);
initialNode.setVisited();
set<State<T>, comparforset> closedNodesSet; // a set of states already evaluated
set<State<T>, comparforset> specialSearchSet;
specialSearchSet.insert(initialNode);
int evaluations = 0;
while (!mypq.empty()) {
evaluations++;
State<T> *currentNode = (mypq.top());
specialSearchSet.erase(mypq.top());
(mypq.pop());
closedNodesSet.insert(currentNode); // so we won't check currentNode again
if (problem->isGoalState(currentNode)) {
//build path
int mytotalcost = 0;
while (currentNode->getParent() != NULL) {
Cell *d = currentNode->getObj();
Cell *dp = currentNode->getParent()->getObj();
if (d->getCol() < dp->getCol()) {
int total = currentNode->getShortestPath();
string s = to_string(total);
direct.push_back("Left(" + s + ")");
}
if (d->getCol() > dp->getCol()) {
int total = currentNode->getShortestPath();
string s = to_string(total);
direct.push_back("Right(" + s + ")");
}
if (d->getRow() < dp->getRow()) {
int total = currentNode->getShortestPath();
string s = to_string(total);
direct.push_back("Up(" + s + ")");
}
if (d->getRow() > dp->getRow()) {
int total = currentNode->getShortestPath();
string s = to_string(total);
direct.push_back("Down(" + s + ")");
}
currentNode = currentNode->getParent();
}
string pathSolution = "";
for (int jj = direct.size(); jj > 0; jj--) {
if(jj != 1) {
pathSolution += direct[jj - 1] + ",";
}
else {
pathSolution += direct[jj - 1];
}
}
//print and return results
mytotalcost += currentNode->getCost();
cout << "AStar:" << endl;
cout << "Total evaluations:"<<endl;
cout<<evaluations << endl;
cout<<"Path:"<<endl;
cout<<pathSolution<<endl;
return pathSolution;
} else {
list<State<T> *> neighbors = problem->getAllPossibleStates(currentNode);
//go over all neighbors of current node
for (State<T> *currentNeighbor:neighbors) {
if ((closedNodesSet.find(currentNeighbor) == closedNodesSet.end()) &&
(specialSearchSet.find(currentNeighbor) == specialSearchSet.end())) {
currentNeighbor->setParent(currentNode);
currentNeighbor->setShortestPath(currentNode->getShortestPath() + currentNeighbor->getCost());
mypq.push(currentNeighbor);
specialSearchSet.insert(currentNeighbor);
} else {
if (currentNeighbor->getShortestPath() >
currentNode->getShortestPath() + currentNeighbor->getCost()) {
currentNeighbor->setShortestPath(
currentNode->getShortestPath() + currentNeighbor->getCost());
currentNeighbor->setParent(currentNode);
if (specialSearchSet.find(currentNeighbor) == specialSearchSet.end()) {
mypq.push(currentNeighbor);
specialSearchSet.insert(currentNeighbor);
}
}
}
}
}
}
};
vector<State<T>> backtrace(State<T> goal) {
vector<State<T>> path;
path.push_back(goal);
State<T> *parent = goal.getParent();
while (parent != nullptr) {
path.push_back(parent);
*parent = parent->getParent();
}
return path;
}
//clone current object
AStar<T> *clone() override {
return new AStar<T>();
}
};
#endif //SEARCHING_ALGORITHM_SERVER_ASTAR_H
| true |
9eedf3a84b0ec51f211182592c58018e95680165 | C++ | yasyamanoi/BaseCrossDx12Study | /Study003/Libs/BaseLib/Basic/BaseMathInc.h | SHIFT_JIS | 51,449 | 2.875 | 3 | [
"MIT"
] | permissive | /*!
@file BaseMathInc.h
@brief vZCN[hNX
@copyright Copyright (c) 2021 WiZ Tamura Hiroki,Yamanoi Yasushi.
*/
#pragma once
#include "stdafx.h"
#include "BaseMath.h"
namespace basecross {
namespace bsm {
//--------------------------------------------------------------------------------------
/// Flt2CC
//--------------------------------------------------------------------------------------
inline Flt2::Flt2() :
XMFLOAT2(0, 0)
{
}
inline Flt2::Flt2(const Flt2& vec) :
XMFLOAT2(vec.x, vec.y)
{
}
inline Flt2::Flt2(const Flt3& vec) :
XMFLOAT2(vec.x, vec.y)
{
}
inline Flt2::Flt2(const Flt4& vec) :
XMFLOAT2(vec.x, vec.y)
{
}
inline Flt2::Flt2(const XMFLOAT2& v) :
XMFLOAT2(v)
{
}
inline Flt2::Flt2(float _x, float _y) :
XMFLOAT2(_x, _y)
{
}
inline Flt2::Flt2(float val) :
XMFLOAT2(val, val)
{
}
inline Flt2::Flt2(const XMVECTOR& vec) :
XMFLOAT2()
{
XMVECTOR temp = vec;
XMStoreFloat2((XMFLOAT2*)this, temp);
}
inline Flt2::operator XMVECTOR() const {
XMFLOAT2 temp = *this;
XMVECTOR Vec = XMLoadFloat2(&temp);
return Vec;
}
inline Flt2& Flt2::operator =(const Flt2& other)
{
if (this != &other) {
x = other.x;
y = other.y;
}
return *this;
}
inline Flt2& Flt2::operator =(const Flt3& other)
{
x = other.x;
y = other.y;
return *this;
}
inline Flt2& Flt2::operator =(const Flt4& other)
{
x = other.x;
y = other.y;
return *this;
}
inline Flt2& Flt2::operator=(const XMFLOAT2& other) {
(XMFLOAT2)*this = other;
return *this;
}
inline Flt2& Flt2::operator=(const XMVECTOR& other) {
XMVECTOR temp = other;
XMStoreFloat2((XMFLOAT2*)this, temp);
return *this;
}
inline bool Flt2::operator==(const Flt2& other)const {
return XMVector2Equal(*this, other);
}
inline bool Flt2::operator!=(const Flt2& other)const {
return !XMVector2Equal(*this, other);
}
inline Flt2& Flt2::setAll(float val) {
x = y = val;
return *this;
}
inline Flt2& Flt2::set(float _x, float _y) {
x = _x;
y = _y;
return *this;
}
inline Flt2& Flt2::setX(float _x)
{
x = _x;
return *this;
}
inline Flt2& Flt2::setY(float _y)
{
y = _y;
return *this;
}
inline float Flt2::getX()const {
return x;
}
inline float Flt2::getY()const {
return y;
}
inline Flt2& Flt2::setElem(int idx, float value)
{
*(&x + idx) = value;
return *this;
}
inline float Flt2::getElem(int idx) const
{
return *(&x + idx);
}
inline float& Flt2::operator [](int idx)
{
return *(&x + idx);
}
inline float Flt2::operator [](int idx) const
{
return *(&x + idx);
}
inline const Flt2 Flt2::operator +(const Flt2& vec) const
{
return (Flt2)XMVectorAdd(*this, vec);
}
inline const Flt2 Flt2::operator +(float val) const
{
Flt2 temp(val, val);
return (Flt2)XMVectorAdd(*this, temp);
}
inline const Flt2 Flt2::operator -(const Flt2& vec) const
{
return (Flt2)XMVectorSubtract(*this, vec);
}
inline const Flt2 Flt2::operator -(float val) const
{
Flt2 temp(val, val);
return (Flt2)XMVectorSubtract(*this, temp);
}
inline const Flt2 Flt2::operator *(float val) const
{
Flt2 temp(val, val);
return (Flt2)XMVectorMultiply(*this, temp);
}
inline Flt2& Flt2::operator +=(const Flt2& vec)
{
*this = *this + vec;
return *this;
}
inline Flt2& Flt2::operator +=(float val)
{
*this = *this + val;
return *this;
}
inline Flt2& Flt2::operator -=(const Flt2& vec)
{
*this = *this - vec;
return *this;
}
inline Flt2& Flt2::operator -=(float val)
{
*this = *this - val;
return *this;
}
inline Flt2& Flt2::operator *=(float val)
{
*this = *this * val;
return *this;
}
inline const Flt2 Flt2::operator /(float val) const
{
Flt2 temp(XMVectorReciprocal(Flt2(val, val)));
return (Flt2)XMVectorMultiply(*this, temp);
}
inline Flt2& Flt2::operator /=(float val)
{
*this = *this / val;
return *this;
}
inline const Flt2 Flt2::operator -() const
{
Flt2 temp(-1.0f, -1.0f);
return (Flt2)XMVectorMultiply(*this, temp);
}
inline Flt2& Flt2::normalize() {
*this = (Flt2)XMVector2Normalize(*this);
return *this;
}
inline Flt2& Flt2::floor(int len) {
x = bsm::floor(x, len);
y = bsm::floor(y, len);
return *this;
}
inline Flt2& Flt2::round(int len) {
x = bsm::round(x, len);
y = bsm::round(y, len);
return *this;
}
inline Flt2& Flt2::ceil(int len) {
x = bsm::ceil(x, len);
y = bsm::ceil(y, len);
return *this;
}
inline float Flt2::dot(const Flt2& vec1)const {
return ((Flt2)XMVector2Dot(*this, vec1)).x;
}
inline float Flt2::lengthSqr()const {
return ((Flt2)XMVector2LengthSq(*this)).x;
}
inline float Flt2::length()const {
return ((Flt2)XMVector2Length(*this)).x;
}
inline bool Flt2::isNaN() const {
return XMVector2IsNaN(*this);
}
inline bool Flt2::isInfinite() const {
return XMVector2IsInfinite(*this);
}
//--------------------------------------------------------------------------------------
/// Flt3CC
//--------------------------------------------------------------------------------------
inline Flt3::Flt3() :
XMFLOAT3(0, 0, 0)
{
}
inline Flt3::Flt3(const Flt3& vec) :
XMFLOAT3(vec.x, vec.y, vec.z)
{
}
inline Flt3::Flt3(const Flt2& vec) :
XMFLOAT3(vec.x, vec.y, 0)
{
}
inline Flt3::Flt3(const Flt4& vec) :
XMFLOAT3(vec.x, vec.y, vec.z)
{
}
inline Flt3::Flt3(const XMFLOAT3& v) :
XMFLOAT3(v)
{
}
inline Flt3::Flt3(float _x, float _y, float _z):
XMFLOAT3(_x, _y, _z)
{
}
inline Flt3::Flt3(float val):
XMFLOAT3(val, val, val)
{
}
inline Flt3::Flt3(const XMVECTOR& vec) :
XMFLOAT3()
{
XMVECTOR temp = vec;
XMStoreFloat3((XMFLOAT3*)this, temp);
}
inline Flt3::operator XMVECTOR() const {
XMFLOAT3 temp = *this;
XMVECTOR Vec = XMLoadFloat3(&temp);
return Vec;
}
inline Flt3& Flt3::operator =(const Flt2& other)
{
x = other.x;
y = other.y;
z = 0;
return *this;
}
inline Flt3& Flt3::operator =(const Flt3& other)
{
if (this != &other) {
x = other.x;
y = other.y;
z = other.z;
}
return *this;
}
inline Flt3& Flt3::operator =(const Flt4& other)
{
x = other.x;
y = other.y;
z = other.z;
return *this;
}
inline Flt3& Flt3::operator=(const XMFLOAT3& other) {
(XMFLOAT3)*this = other;
return *this;
}
inline Flt3& Flt3::operator=(const XMVECTOR& other) {
XMVECTOR temp = other;
XMStoreFloat3((XMFLOAT3*)this, temp);
return *this;
}
inline bool Flt3::operator==(const Flt3& other)const {
return XMVector3Equal(*this, other);
}
inline bool Flt3::operator!=(const Flt3& other)const {
return !XMVector3Equal(*this, other);
}
inline Flt3& Flt3::setAll(float val) {
x = y = z = val;
return *this;
}
inline Flt3& Flt3::set(float _x, float _y, float _z) {
x = _x;
y = _y;
z = _z;
return *this;
}
inline Flt3& Flt3::setX(float _x)
{
x = _x;
return *this;
}
inline Flt3& Flt3::setY(float _y)
{
y = _y;
return *this;
}
inline Flt3& Flt3::setZ(float _z)
{
z = _z;
return *this;
}
inline float Flt3::getX()const {
return x;
}
inline float Flt3::getY()const {
return y;
}
inline float Flt3::getZ()const {
return z;
}
inline Flt3& Flt3::setElem(int idx, float value)
{
*(&x + idx) = value;
return *this;
}
inline float Flt3::getElem(int idx) const
{
return *(&x + idx);
}
inline float& Flt3::operator [](int idx)
{
return *(&x + idx);
}
inline float Flt3::operator [](int idx) const
{
return *(&x + idx);
}
inline const Flt3 Flt3::operator +(const Flt3& vec) const
{
return (Flt3)XMVectorAdd(*this, vec);
}
inline const Flt3 Flt3::operator +(float val) const
{
Flt3 temp(val, val, val);
return (Flt3)XMVectorAdd(*this, temp);
}
inline const Flt3 Flt3::operator -(const Flt3& vec) const
{
return (Flt3)XMVectorSubtract(*this, vec);
}
inline const Flt3 Flt3::operator -(float val) const
{
Flt3 temp(val, val, val);
return (Flt3)XMVectorSubtract(*this, temp);
}
inline const Flt3 Flt3::operator *(float val) const
{
Flt3 temp(val, val, val);
return (Flt3)XMVectorMultiply(*this, temp);
}
inline const Flt3 Flt3::operator *(const Mat3x3& mat) const {
return (Flt3)XMVector3Transform(*this, mat);
}
inline const Flt3 Flt3::operator *(const Mat4x4& mat) const {
return (Flt3)XMVector3Transform(*this, mat);
}
inline Flt3& Flt3::operator +=(const Flt3& vec)
{
*this = *this + vec;
return *this;
}
inline Flt3& Flt3::operator +=(float val)
{
*this = *this + val;
return *this;
}
inline Flt3& Flt3::operator -=(const Flt3& vec)
{
*this = *this - vec;
return *this;
}
inline Flt3& Flt3::operator -=(float val)
{
*this = *this - val;
return *this;
}
inline Flt3& Flt3::operator *=(float val)
{
*this = *this * val;
return *this;
}
inline Flt3& Flt3::operator *=(const Mat3x3& mat) {
*this = *this * mat;
return *this;
}
inline Flt3& Flt3::operator *=(const Mat4x4& mat) {
*this = *this * mat;
return *this;
}
inline const Flt3 Flt3::operator /(float val) const
{
Flt3 temp(XMVectorReciprocal(Flt3(val, val, val)));
return (Flt3)XMVectorMultiply(*this, temp);
}
inline Flt3& Flt3::operator /=(float val)
{
*this = *this / val;
return *this;
}
inline const Flt3 Flt3::operator -() const
{
Flt3 temp(-1.0f, -1.0f, -1.0f);
return (Flt3)XMVectorMultiply(*this, temp);
}
inline Flt3& Flt3::normalize() {
*this = (Flt3)XMVector3Normalize(*this);
return *this;
}
inline Flt3& Flt3::floor(int len) {
x = bsm::floor(x, len);
y = bsm::floor(y, len);
z = bsm::floor(z, len);
return *this;
}
inline Flt3& Flt3::round(int len) {
x = bsm::round(x, len);
y = bsm::round(y, len);
z = bsm::round(z, len);
return *this;
}
inline Flt3& Flt3::ceil(int len) {
x = bsm::ceil(x, len);
y = bsm::ceil(y, len);
z = bsm::ceil(z, len);
return *this;
}
inline float Flt3::dot(const Flt3& vec1)const {
return ((Flt3)XMVector3Dot(*this, vec1)).x;
}
inline Flt3& Flt3::cross(const Flt3& vec1) {
*this = (Flt3)XMVector3Cross(*this, vec1);
return *this;
}
inline float Flt3::lengthSqr()const {
return ((Flt3)XMVector3LengthSq(*this)).x;
}
inline float Flt3::length()const {
return ((Flt3)XMVector3Length(*this)).x;
}
inline Flt3& Flt3::reflect(const Flt3& normal) {
*this = (Flt3)XMVector3Reflect(*this, normal);
return *this;
}
inline Flt3& Flt3::slide(const Flt3& normal) {
//*thisƖ@璼s̒iςŋ߂j
float Len = bsm::dot(*this, normal);
//̒ɐL
Flt3 Contact = normal * Len;
//XCh݂͌̃xNgZ
*this -= Contact;
return *this;
}
inline bool Flt3::isNaN() const {
return XMVector3IsNaN(*this);
}
inline bool Flt3::isInfinite() const {
return XMVector3IsInfinite(*this);
}
//--------------------------------------------------------------------------------------
/// Flt4CC
//--------------------------------------------------------------------------------------
inline Flt4::Flt4() :
XMFLOAT4(0, 0, 0, 0)
{
}
inline Flt4::Flt4(const Flt4& vec) :
XMFLOAT4(vec.x, vec.y, vec.z, vec.w)
{
}
inline Flt4::Flt4(const Flt2& vec) :
XMFLOAT4(vec.x, vec.y, 0, 0)
{
}
inline Flt4::Flt4(const Flt3& vec) :
XMFLOAT4(vec.x, vec.y, vec.z, 0)
{
}
inline Flt4::Flt4(const Flt3& vec, float _w):
XMFLOAT4(vec.x, vec.y, vec.z, _w)
{}
inline Flt4::Flt4(const XMFLOAT4& v) :
XMFLOAT4(v)
{
}
inline Flt4::Flt4(float _x, float _y, float _z, float _w) :
XMFLOAT4(_x, _y, _z, _w)
{
}
inline Flt4::Flt4(float val) :
XMFLOAT4(val, val, val, val)
{
}
inline Flt4::Flt4(const XMVECTOR& vec) :
XMFLOAT4()
{
XMVECTOR temp = vec;
XMStoreFloat4((XMFLOAT4*)this, temp);
}
inline Flt4::operator XMVECTOR() const {
XMFLOAT4 temp = *this;
XMVECTOR Vec = XMLoadFloat4(&temp);
return Vec;
}
inline Flt4::operator Flt3() const {
return Flt3(x, y, z);
}
inline Flt4& Flt4::operator =(const Flt2& other) {
x = other.x;
y = other.y;
z = 0;
w = 0;
return *this;
}
inline Flt4& Flt4::operator =(const Flt3& other) {
x = other.x;
y = other.y;
z = other.z;
w = 0;
return *this;
}
inline Flt4& Flt4::operator =(const Flt4& other)
{
if (this != &other) {
x = other.x;
y = other.y;
z = other.z;
w = other.w;
}
return *this;
}
inline Flt4& Flt4::operator=(const XMFLOAT4& other) {
(XMFLOAT4)*this = other;
return *this;
}
inline Flt4& Flt4::operator=(const XMVECTOR& other) {
XMVECTOR temp = other;
XMStoreFloat4((XMFLOAT4*)this, temp);
return *this;
}
inline bool Flt4::operator==(const Flt4& other)const {
return XMVector4Equal(*this, other);
}
inline bool Flt4::operator!=(const Flt4& other)const {
return !XMVector4Equal(*this, other);
}
inline Flt4& Flt4::setAll(float val) {
x = y = z = w = val;
return *this;
}
inline Flt4& Flt4::set(float _x, float _y, float _z, float _w) {
x = _x;
y = _y;
z = _z;
w = _w;
return *this;
}
inline Flt4& Flt4::setX(float _x)
{
x = _x;
return *this;
}
inline Flt4& Flt4::setY(float _y)
{
y = _y;
return *this;
}
inline Flt4& Flt4::setZ(float _z)
{
z = _z;
return *this;
}
inline Flt4& Flt4::setW(float _w)
{
w = _w;
return *this;
}
inline float Flt4::getX()const {
return x;
}
inline float Flt4::getY()const {
return y;
}
inline float Flt4::getZ()const {
return z;
}
inline float Flt4::getW()const {
return w;
}
inline Flt4& Flt4::setElem(int idx, float value)
{
*(&x + idx) = value;
return *this;
}
inline float Flt4::getElem(int idx) const
{
return *(&x + idx);
}
inline float& Flt4::operator [](int idx)
{
return *(&x + idx);
}
inline float Flt4::operator [](int idx) const
{
return *(&x + idx);
}
inline const Flt4 Flt4::operator +(const Flt4& vec) const
{
return (Flt4)XMVectorAdd(*this, vec);
}
inline const Flt4 Flt4::operator +(float val) const
{
Flt4 temp(val, val, val, val);
return (Flt4)XMVectorAdd(*this, temp);
}
inline const Flt4 Flt4::operator -(const Flt4& vec) const
{
return (Flt4)XMVectorSubtract(*this, vec);
}
inline const Flt4 Flt4::operator -(float val) const
{
Flt4 temp(val, val, val, val);
return (Flt4)XMVectorSubtract(*this, temp);
}
inline const Flt4 Flt4::operator *(float val) const
{
Flt4 temp(val, val, val, val);
return (Flt4)XMVectorMultiply(*this, temp);
}
inline const Flt4 Flt4::operator *(const Mat3x3& mat) const {
return (Flt4)XMVector4Transform(*this, mat);
}
inline const Flt4 Flt4::operator *(const Mat4x4& mat) const {
return (Flt4)XMVector4Transform(*this, mat);
}
inline Flt4& Flt4::operator +=(const Flt4& vec)
{
*this = *this + vec;
return *this;
}
inline Flt4& Flt4::operator +=(float val)
{
*this = *this + val;
return *this;
}
inline Flt4& Flt4::operator -=(const Flt4& vec)
{
*this = *this - vec;
return *this;
}
inline Flt4& Flt4::operator -=(float val)
{
*this = *this - val;
return *this;
}
inline Flt4& Flt4::operator *=(float val)
{
*this = *this * val;
return *this;
}
inline Flt4& Flt4::operator *=(const Mat3x3& mat) {
*this = *this * mat;
return *this;
}
inline Flt4& Flt4::operator *=(const Mat4x4& mat) {
*this = *this * mat;
return *this;
}
inline const Flt4 Flt4::operator /(float val) const
{
Flt4 temp(XMVectorReciprocal(Flt4(val, val, val, val)));
return (Flt4)XMVectorMultiply(*this, temp);
}
inline Flt4& Flt4::operator /=(float val)
{
*this = *this / val;
return *this;
}
inline const Flt4 Flt4::operator -() const
{
Flt4 temp(-1.0f, -1.0f, -1.0f, -1.0f);
return (Flt4)XMVectorMultiply(*this, temp);
}
inline Flt4& Flt4::normalize() {
*this = (Flt4)XMVector4Normalize(*this);
return *this;
}
inline Flt4& Flt4::floor(int len) {
x = bsm::floor(x, len);
y = bsm::floor(y, len);
z = bsm::floor(z, len);
w = bsm::floor(w, len);
return *this;
}
inline Flt4& Flt4::round(int len) {
x = bsm::round(x, len);
y = bsm::round(y, len);
z = bsm::round(z, len);
w = bsm::round(w, len);
return *this;
}
inline Flt4& Flt4::ceil(int len) {
x = bsm::ceil(x, len);
y = bsm::ceil(y, len);
z = bsm::ceil(z, len);
w = bsm::ceil(w, len);
return *this;
}
inline float Flt4::dot(const Flt4& vec1)const {
return ((Flt4)XMVector4Dot(*this, vec1)).x;
}
inline float Flt4::lengthSqr()const {
return ((Flt4)XMVector4LengthSq(*this)).x;
}
inline float Flt4::length()const {
return ((Flt4)XMVector4Length(*this)).x;
}
inline bool Flt4::isNaN() const {
return XMVector4IsNaN(*this);
}
inline bool Flt4::isInfinite() const {
return XMVector4IsInfinite(*this);
}
//--------------------------------------------------------------------------------------
/// QuatCC
//--------------------------------------------------------------------------------------
inline Quat::Quat():
XMFLOAT4()
{
identity();
}
inline Quat::Quat(const Quat& quat):
XMFLOAT4(quat.x, quat.y, quat.z, quat.w)
{
}
inline Quat::Quat(const XMFLOAT4& v) :
XMFLOAT4(v)
{
}
inline Quat::Quat(float _x, float _y, float _z, float _w):
XMFLOAT4(_x, _y, _z, _w)
{
}
inline Quat::Quat(const Flt3& vec, float r):
XMFLOAT4()
{
*this = (Quat)XMQuaternionRotationAxis(vec, r);
}
inline Quat::Quat(float val):
XMFLOAT4()
{
x = val;
y = val;
z = val;
w = val;
}
inline Quat::Quat(const XMVECTOR& other) :
XMFLOAT4()
{
XMVECTOR temp = other;
XMStoreFloat4((XMFLOAT4*)this, temp);
}
inline Quat::Quat(const Mat3x3& m) {
Mat4x4 m4(m);
*this = m4.quatInMatrix();
}
inline Quat::Quat(const Mat4x4& m) {
*this = m.quatInMatrix();
}
inline Quat::operator XMVECTOR() const {
XMFLOAT4 temp = *this;
XMVECTOR Vec = XMLoadFloat4(&temp);
return Vec;
}
inline Quat& Quat::operator=(const XMFLOAT4& other) {
(XMFLOAT4)*this = other;
return *this;
}
inline Quat& Quat::operator=(const XMVECTOR& other) {
XMVECTOR temp = other;
XMStoreFloat4((XMFLOAT4*)this, temp);
return *this;
}
inline Quat& Quat::operator =(const Quat& quat)
{
if (this != &quat) {
x = quat.x;
y = quat.y;
z = quat.z;
w = quat.w;
}
return *this;
}
inline bool Quat::operator==(const Quat& other)const {
return XMQuaternionEqual(*this, other);
}
inline bool Quat::operator!=(const Quat& other)const {
return !XMQuaternionEqual(*this, other);
}
inline Quat& Quat::setXYZ(const Flt3& vec)
{
x = vec.x;
y = vec.y;
z = vec.z;
return *this;
}
inline const Flt3 Quat::getXYZ() const
{
return Flt3(x, y, z);
}
inline Quat& Quat::setX(float _x)
{
x = _x;
return *this;
}
inline Quat& Quat::setY(float _y)
{
y = _y;
return *this;
}
inline Quat& Quat::setZ(float _z)
{
z = _z;
return *this;
}
inline Quat& Quat::setW(float _w)
{
w = _w;
return *this;
}
inline float Quat::getX()const {
return x;
}
inline float Quat::getY()const {
return y;
}
inline float Quat::getZ()const {
return z;
}
inline float Quat::getW()const {
return w;
}
inline Quat& Quat::setElem(int idx, float value)
{
*(&x + idx) = value;
return *this;
}
inline float Quat::getElem(int idx) const
{
return *(&x + idx);
}
inline float& Quat::operator [](int idx)
{
return *(&x + idx);
}
inline float Quat::operator [](int idx) const
{
return *(&x + idx);
}
inline const Quat Quat::operator +(const Quat& quat) const
{
return (Quat)XMVectorAdd(*this, quat);
}
inline const Quat Quat::operator -(const Quat& quat) const
{
return (Quat)XMVectorSubtract(*this, quat);
}
inline const Quat Quat::operator *(const Quat& quat) const
{
return (Quat)XMQuaternionMultiply(*this, quat);
}
inline const Quat Quat::operator *(float val) const
{
Quat temp(val, val, val, val);
return (Quat)XMVectorMultiply(*this, temp);
}
inline Quat& Quat::operator *=(const Quat& quat) {
*this = *this * quat;
return *this;
}
inline Quat& Quat::normalize() {
*this = (Quat)XMQuaternionNormalize(*this);
return *this;
}
inline float Quat::dot(const Quat& quat)const {
return ((Quat)XMQuaternionDot(*this, quat)).x;
}
inline Quat& Quat::conj(const Quat& quat) {
*this = (Quat)XMQuaternionConjugate(quat);
return *this;
}
inline Quat& Quat::identity()
{
*this = (Quat)XMQuaternionIdentity();
return *this;
}
inline Quat& Quat::rotationX(float radians)
{
*this = (Quat)XMQuaternionRotationAxis(XMVECTOR(Flt3(1,0,0)), radians);
return *this;
}
inline Quat& Quat::rotationY(float radians)
{
*this = (Quat)XMQuaternionRotationAxis(Flt3(0, 1, 0), radians);
return *this;
}
inline Quat& Quat::rotationZ(float radians)
{
*this = (Quat)XMQuaternionRotationAxis(Flt3(0, 0, 1), radians);
return *this;
}
inline Quat& Quat::rotation(float radians, const Flt3& unitVec) {
*this = (Quat)XMQuaternionRotationAxis(unitVec, radians);
return *this;
}
inline Quat& Quat::rotation(const Flt3& unitVec, float radians) {
*this = (Quat)XMQuaternionRotationAxis(unitVec, radians);
return *this;
}
inline Quat& Quat::rotationRollPitchYawFromVector(const Flt3& rotVec) {
*this = (Quat)XMQuaternionRotationRollPitchYawFromVector(rotVec);
return *this;
}
inline const Flt3 Quat::toRotVec() const {
Quat Temp = *this;
Temp.normalize();
Mat4x4 mt(Temp);
Flt3 Rot;
if (mt._32 == 1.0f) {
Rot.x = XM_PI / 2.0f;
Rot.y = 0;
Rot.z = -atan2(mt._21, mt._11);
}
else if (mt._32 == -1.0f) {
Rot.x = -XM_PI / 2.0f;
Rot.y = 0;
Rot.z = -atan2(mt._21, mt._11);
}
else {
Rot.x = -asin(mt._32);
Rot.y = -atan2(-mt._31, mt._33);
Rot.z = atan2(mt._12, mt._11);
}
return Rot;
}
inline Quat& Quat::inverse() {
*this = (Quat)XMQuaternionInverse(*this);
return *this;
}
inline Quat& Quat::facing(const Flt3& norm) {
Flt3 DefUp(0, 1.0f, 0);
Flt3 Temp = norm;
Flt2 TempVec2(Temp.x, Temp.z);
if (bsm::length(TempVec2) < 0.1f) {
DefUp = bsm::Flt3(0, 0, 1.0f);
}
Temp.normalize();
Mat4x4 RotMatrix;
RotMatrix = XMMatrixLookAtLH(bsm::Flt3(0, 0, 0), Temp, DefUp);
RotMatrix = bsm::inverse(RotMatrix);
*this = RotMatrix.quatInMatrix();
(*this).normalize();
return *this;
}
inline Quat& Quat::facingY(const Flt3& norm) {
Flt3 Temp = norm;
Temp.normalize();
*this = XMQuaternionRotationRollPitchYaw(0, atan2(Temp.x, Temp.z), 0);
(*this).normalize();
return *this;
}
inline bool Quat::isNaN() const {
return XMQuaternionIsNaN(*this);
}
inline bool Quat::isInfinite() const {
return XMQuaternionIsInfinite(*this);
}
//--------------------------------------------------------------------------------------
/// Mat3x3CC
//--------------------------------------------------------------------------------------
inline Mat3x3::Mat3x3():
XMFLOAT3X3()
{
identity();
}
inline Mat3x3::Mat3x3(const Mat3x3& mat):
XMFLOAT3X3(mat)
{
}
inline Mat3x3::Mat3x3(float val):
XMFLOAT3X3()
{
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
m[i][j] = val;
}
}
}
inline Mat3x3::Mat3x3(const XMFLOAT3X3& other):
XMFLOAT3X3(other)
{
}
inline Mat3x3::Mat3x3(const XMMATRIX& other):
XMFLOAT3X3()
{
XMMATRIX temp = other;
XMStoreFloat3x3((XMFLOAT3X3*)this, temp);
}
inline Mat3x3::operator XMMATRIX() const {
Mat3x3 temp = *this;
XMMATRIX m = XMLoadFloat3x3(&temp);
return m;
}
inline Mat3x3& Mat3x3::operator=(const XMFLOAT3X3& other) {
(XMFLOAT3X3)*this = other;
return *this;
}
inline Mat3x3& Mat3x3::operator=(const XMMATRIX& other) {
XMMATRIX temp = other;
XMStoreFloat3x3((XMFLOAT3X3*)this, temp);
return *this;
}
inline Mat3x3& Mat3x3::operator =(const Mat3x3& mat)
{
if (this != &mat) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
m[i][j] = mat[i][j];
}
}
}
return *this;
}
inline bool Mat3x3::operator==(const Mat3x3& other)const {
for (int i = 0; i < 3; i++) {
if (!XMVector3Equal(getMajor(i), other.getMajor(i))) {
return false;
}
}
return true;
}
inline bool Mat3x3::operator!=(const Mat3x3& other)const {
for (int i = 0; i < 3; i++) {
if (!XMVector3Equal(getMajor(i), other.getMajor(i))) {
return true;
}
}
return false;
}
inline Mat3x3::Mat3x3(const Quat& unitQuat):
XMFLOAT3X3()
{
*this = (Mat3x3)XMMatrixRotationQuaternion(unitQuat);
}
inline Mat3x3::Mat3x3(const Flt3& _major0, const Flt3& _major1, const Flt3& _major2):
XMFLOAT3X3()
{
setMajor(0, _major0);
setMajor(1, _major1);
setMajor(2, _major2);
}
inline Mat3x3& Mat3x3::setMajor0(const Flt3& _major0)
{
setMajor(0, _major0);
return *this;
}
inline Mat3x3& Mat3x3::setMajor1(const Flt3& _major1)
{
setMajor(1, _major1);
return *this;
}
inline Mat3x3& Mat3x3::setMajor2(const Flt3& _major2)
{
setMajor(2, _major2);
return *this;
}
inline Mat3x3& Mat3x3::setMajor(int major, const Flt3& vec)
{
m[major][0] = vec.x;
m[major][1] = vec.y;
m[major][2] = vec.z;
return *this;
}
inline Mat3x3& Mat3x3::setMinor(int minor, const Flt3& vec)
{
setElem(0, minor, vec.getElem(0));
setElem(1, minor, vec.getElem(1));
setElem(2, minor, vec.getElem(2));
return *this;
}
inline Mat3x3& Mat3x3::setElem(int major, int minor, float val)
{
m[major][minor] = val;
return *this;
}
inline float Mat3x3::getElem(int major, int minor) const
{
return this->getMajor(major).getElem(minor);
}
inline const Flt3 Mat3x3::getMajor0() const
{
return getMajor(0);
}
inline const Flt3 Mat3x3::getMajor1() const
{
return getMajor(1);
}
inline const Flt3 Mat3x3::getMajor2() const
{
return getMajor(2);
}
inline const Flt3 Mat3x3::getMajor(int major) const
{
Flt3 temp(m[major][0], m[major][1], m[major][2]);
return temp;
}
inline const Flt3 Mat3x3::getMinor(int minor) const
{
return Flt3(m[0][minor], m[1][minor], m[2][minor]);
}
inline Flt3& Mat3x3::operator [](int major)
{
return (Flt3&)(m[major][0]);
}
inline const Flt3 Mat3x3::operator [](int major) const
{
return (Flt3&)(m[major][0]);
}
inline const Mat3x3 Mat3x3::operator +(const Mat3x3& mat) const
{
Mat3x3 temp;
for (int i = 0; i < 3; i++) {
temp[i] = getMajor(i) + mat.getMajor(i);
}
return temp;
}
inline const Mat3x3 Mat3x3::operator -(const Mat3x3& mat) const
{
Mat3x3 temp;
for (int i = 0; i < 3; i++) {
temp[i] = getMajor(i) - mat.getMajor(i);
}
return temp;
}
inline const Mat3x3 Mat3x3::operator -() const
{
Mat3x3 temp;
for (int i = 0; i < 3; i++) {
temp[i] = -getMajor(i);
}
return temp;
}
inline const Mat3x3 Mat3x3::operator *(float val) const
{
Mat3x3 temp;
for (int i = 0; i < 3; i++) {
temp[i] = getMajor(i) * val;
}
return temp;
}
inline const Flt3 Mat3x3::operator *(const Flt3& vec) const
{
return (Flt3)XMVector3Transform(vec, *this);
}
inline const Mat3x3 Mat3x3::operator *(const Mat3x3& mat) const
{
return (Mat3x3)XMMatrixMultiply(*this, mat);
}
inline Mat3x3& Mat3x3::operator +=(const Mat3x3& mat)
{
*this = *this + mat;
return *this;
}
inline Mat3x3& Mat3x3::operator -=(const Mat3x3& mat)
{
*this = *this - mat;
return *this;
}
inline Mat3x3& Mat3x3::operator *=(float val) {
*this = *this * val;
return *this;
}
inline Mat3x3& Mat3x3::operator *=(const Mat3x3& mat) {
*this = *this * mat;
return *this;
}
inline Mat3x3& Mat3x3::identity()
{
*this = (Mat3x3)XMMatrixIdentity();
return *this;
}
inline Mat3x3& Mat3x3::scale(const Flt3& scaleVec)
{
*this = (Mat3x3)XMMatrixScalingFromVector(scaleVec);
return *this;
}
inline Mat3x3& Mat3x3::rotation(const Quat& unitQuat)
{
*this = (Mat3x3)XMMatrixRotationQuaternion(unitQuat);
return *this;
}
inline Mat3x3& Mat3x3::transpose() {
*this = (Mat3x3)XMMatrixTranspose(*this);
return *this;
}
inline Mat3x3& Mat3x3::inverse() {
XMVECTOR Vec;
*this = (Mat3x3)XMMatrixInverse(&Vec, *this);
return *this;
}
inline Mat3x3& Mat3x3::crossMatrix(const Flt3& vec) {
*this = Mat3x3(
Flt3(0.0f, vec.z, -vec.y),
Flt3(-vec.z, 0.0f, vec.x),
Flt3(vec.y, -vec.x, 0.0f)
);
return *this;
}
inline Flt3 Mat3x3::rotXInMatrix()const {
Flt3 ret(_11, _12, _13);
return ret;
}
inline Flt3 Mat3x3::rotYInMatrix()const {
Flt3 ret(_21, _22, _23);
return ret;
}
inline Flt3 Mat3x3::rotZInMatrix()const {
Flt3 ret(_31, _32, _33);
return ret;
}
//--------------------------------------------------------------------------------------
/// Mat4x4CC
//--------------------------------------------------------------------------------------
inline Mat4x4::Mat4x4():
XMFLOAT4X4()
{
identity();
}
inline Mat4x4::Mat4x4(const Mat4x4& mat) :
XMFLOAT4X4(mat)
{
}
inline Mat4x4::Mat4x4(const Mat3x3& mat) :
XMFLOAT4X4()
{
identity();
this->setUpper3x3(mat);
}
inline Mat4x4::Mat4x4(const Flt3& _major0, const Flt3& _major1, const Flt3& _major2, const Flt3& _major3) :
XMFLOAT4X4()
{
identity();
setMajor(0, _major0);
setMajor(1, _major1);
setMajor(2, _major2);
setMajor(3, _major3);
}
inline Mat4x4::Mat4x4(const Flt4& _major0, const Flt4& _major1, const Flt4& _major2, const Flt4& _major3) :
XMFLOAT4X4()
{
identity();
setMajor(0, _major0);
setMajor(1, _major1);
setMajor(2, _major2);
setMajor(3, _major3);
}
inline Mat4x4::Mat4x4(const Mat3x3& tfrm, const Flt3& translateVec)
{
identity();
this->setUpper3x3(tfrm);
this->setTranslation(translateVec);
}
inline Mat4x4::Mat4x4(const Quat& unitQuat, const Flt3& translateVec)
{
identity();
this->setUpper3x3(Mat3x3(unitQuat));
this->setTranslation(translateVec);
}
inline Mat4x4::Mat4x4(float val) :
XMFLOAT4X4()
{
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
m[i][j] = val;
}
}
}
inline Mat4x4::Mat4x4(const XMFLOAT4X4& other):
XMFLOAT4X4(other)
{
}
inline Mat4x4::Mat4x4(const XMMATRIX& other) :
XMFLOAT4X4()
{
XMMATRIX temp = other;
XMStoreFloat4x4((XMFLOAT4X4*)this, temp);
}
inline Mat4x4::operator XMMATRIX() const {
Mat4x4 temp = *this;
XMMATRIX m = XMLoadFloat4x4(&temp);
return m;
}
inline Mat4x4& Mat4x4::operator=(const XMFLOAT4X4& other) {
(XMFLOAT4X4)*this = other;
return *this;
}
inline Mat4x4& Mat4x4::operator=(const XMMATRIX& other) {
XMMATRIX temp = other;
XMStoreFloat4x4((XMFLOAT4X4*)this, temp);
return *this;
}
inline bool Mat4x4::operator==(const Mat4x4& other)const {
for (int i = 0; i < 4; i++) {
if (!XMVector4Equal(getMajor(i), other.getMajor(i))) {
return false;
}
}
return true;
}
inline bool Mat4x4::operator!=(const Mat4x4& other)const {
for (int i = 0; i < 4; i++) {
if (!XMVector4Equal(getMajor(i), other.getMajor(i))) {
return true;
}
}
return false;
}
inline bool Mat4x4::equalInt(const Mat4x4& other)const {
for (int i = 0; i < 4; i++) {
if (!XMVector4EqualInt(getMajor(i), other.getMajor(i))) {
return false;
}
}
return true;
}
inline bool Mat4x4::nearEqual(const Mat4x4& other, float epsilon)const {
Flt4 temp(epsilon, epsilon, epsilon, epsilon);
for (int i = 0; i < 4; i++) {
if (!XMVector4NearEqual(getMajor(i), other.getMajor(i), temp)) {
return false;
}
}
return true;
}
inline Mat4x4::Mat4x4(const Quat& unitQuat) :
XMFLOAT4X4()
{
*this = (Mat4x4)XMMatrixRotationQuaternion(XMVECTOR(unitQuat));
}
inline Mat4x4& Mat4x4::setUpper3x3(const Mat3x3& tfrm)
{
this->operator[](0) = tfrm.getMajor0();
this->operator[](1) = tfrm.getMajor1();
this->operator[](2) = tfrm.getMajor2();
return *this;
}
inline const Mat3x3 Mat4x4::getUpper3x3() const
{
return Mat3x3(getMajor0(), getMajor1(), getMajor2());
}
inline Mat4x4& Mat4x4::setTranslation(const Flt3& translateVec)
{
this->operator[](3) = translateVec;
m[3][3] = 1.0f;
return *this;
}
inline const Flt3 Mat4x4::getTranslation() const
{
return (Flt3)getMajor3();
}
inline Mat4x4& Mat4x4::setMajor0(const Flt3& _major0)
{
setMajor(0, _major0);
m[0][3] = 0.0f;
return *this;
}
inline Mat4x4& Mat4x4::setMajor1(const Flt3& _major1)
{
setMajor(1, _major1);
m[1][3] = 0.0f;
return *this;
}
inline Mat4x4& Mat4x4::setMajor2(const Flt3& _major2)
{
setMajor(2, _major2);
m[2][3] = 0.0f;
return *this;
}
inline Mat4x4& Mat4x4::setMajor3(const Flt3& _major3)
{
setMajor(3, _major3);
m[3][3] = 1.0f;
return *this;
}
inline Mat4x4& Mat4x4::setMajor0(const Flt4& _major0)
{
setMajor(0, _major0);
return *this;
}
inline Mat4x4& Mat4x4::setMajor1(const Flt4& _major1)
{
setMajor(1, _major1);
return *this;
}
inline Mat4x4& Mat4x4::setMajor2(const Flt4& _major2)
{
setMajor(2, _major2);
return *this;
}
inline Mat4x4& Mat4x4::setMajor3(const Flt4& _major3)
{
setMajor(3, _major3);
return *this;
}
inline Mat4x4& Mat4x4::setMajor(int major, const Flt3& vec)
{
m[major][0] = vec.x;
m[major][1] = vec.y;
m[major][2] = vec.z;
return *this;
}
inline Mat4x4& Mat4x4::setMajor(int major, const Flt4& vec)
{
m[major][0] = vec.x;
m[major][1] = vec.y;
m[major][2] = vec.z;
m[major][3] = vec.w;
m[3][3] = 1.0f;
return *this;
}
inline Mat4x4& Mat4x4::setMinor(int minor, const Flt3& vec)
{
setElem(0, minor, vec.getElem(0));
setElem(1, minor, vec.getElem(1));
setElem(2, minor, vec.getElem(2));
return *this;
}
inline Mat4x4& Mat4x4::setMinor(int minor, const Flt4& vec)
{
setElem(0, minor, vec.getElem(0));
setElem(1, minor, vec.getElem(1));
setElem(2, minor, vec.getElem(2));
setElem(3, minor, vec.getElem(3));
m[3][3] = 1.0f;
return *this;
}
inline Mat4x4& Mat4x4::setElem(int major, int minor, float val)
{
m[major][minor] = val;
return *this;
}
inline float Mat4x4::getElem(int major, int minor) const
{
return this->getMajor(major).getElem(minor);
}
inline const Flt4 Mat4x4::getMajor0() const
{
return getMajor(0);
}
inline const Flt4 Mat4x4::getMajor1() const
{
return getMajor(1);
}
inline const Flt4 Mat4x4::getMajor2() const
{
return getMajor(2);
}
inline const Flt4 Mat4x4::getMajor3() const
{
return getMajor(3);
}
inline const Flt4 Mat4x4::getMajor(int major) const
{
Flt4 temp(m[major][0], m[major][1], m[major][2], m[major][3]);
return temp;
}
inline const Flt4 Mat4x4::getMinor(int minor) const
{
return Flt4(m[0][minor], m[1][minor], m[2][minor], m[3][minor]);
}
inline Flt4& Mat4x4::operator [](int major)
{
return (Flt4&)(m[major][0]);
}
inline const Flt4 Mat4x4::operator [](int major) const
{
return (Flt4&)(m[major][0]);
}
inline Mat4x4& Mat4x4::operator =(const Mat4x4& mat)
{
if (this != &mat) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
m[i][j] = mat[i][j];
}
}
}
return *this;
}
inline const Mat4x4 Mat4x4::operator +(const Mat4x4& mat) const
{
Mat4x4 temp;
for (int i = 0; i < 4; i++) {
temp[i] = getMajor(i) + mat.getMajor(i);
}
temp[3][3] = 1.0f;
return temp;
}
inline const Mat4x4 Mat4x4::operator -(const Mat4x4& mat) const
{
Mat4x4 temp;
for (int i = 0; i < 4; i++) {
temp[i] = getMajor(i) - mat.getMajor(i);
}
temp[3][3] = 1.0f;
return temp;
}
inline const Mat4x4 Mat4x4::operator -() const
{
Mat4x4 temp;
for (int i = 0; i < 4; i++) {
temp[i] = -getMajor(i);
}
temp[3][3] = 1.0f;
return temp;
}
inline const Mat4x4 Mat4x4::operator *(float val) const
{
Mat4x4 temp;
for (int i = 0; i < 4; i++) {
temp[i] = getMajor(i) * val;
}
temp[3][3] = 1.0f;
return temp;
}
inline const Flt3 Mat4x4::operator *(const Flt3& vec) const
{
return (Flt3)XMVector3Transform(vec, *this);
}
inline const Flt4 Mat4x4::operator *(const Flt4& vec) const
{
return (Flt4)XMVector4Transform(vec, *this);
}
inline const Mat4x4 Mat4x4::operator *(const Mat4x4& mat) const
{
return (Mat4x4)XMMatrixMultiply(*this, mat);
}
inline const Mat4x4 Mat4x4::operator *(const Mat3x3& mat) const
{
return (Mat4x4)XMMatrixMultiply(*this, mat);
}
inline Mat4x4& Mat4x4::operator +=(const Mat4x4& mat)
{
*this = *this + mat;
return *this;
}
inline Mat4x4& Mat4x4::operator -=(const Mat4x4& mat)
{
*this = *this - mat;
return *this;
}
inline Mat4x4& Mat4x4::operator *=(float val) {
*this = *this * val;
return *this;
}
inline Mat4x4& Mat4x4::operator *=(const Mat4x4& tfrm)
{
*this = *this * tfrm;
return *this;
}
inline Mat4x4& Mat4x4::operator *=(const Mat3x3& tfrm)
{
*this = *this * tfrm;
return *this;
}
inline void Mat4x4::decompose(Flt3& rScaling, Quat& rQt, Flt3& rTranslation)const {
XMVECTOR Scale;
XMVECTOR Qt;
XMVECTOR Translation;
if (XMMatrixDecompose(&Scale, &Qt, &Translation, *this)) {
rScaling = Scale;
rQt = Qt;
rTranslation = Translation;
}
else {
//XP[O}CiX̏ꍇ̏
auto XLen = length(Flt3(_11, _12, _13));
auto YLen = length(Flt3(_21, _22, _23));
auto ZLen = length(Flt3(_31, _32, _33));
//XP[O0̗vf
if (XLen == 0.0f) {
XLen = 0.0001f;
}
if (YLen == 0.0f) {
YLen = 0.0001f;
}
if (ZLen == 0.0f) {
ZLen = 0.0001f;
}
rScaling = Flt3(XLen, YLen, ZLen);
rTranslation = Flt3(_41, _42, _43);
Flt3 vX = Flt3(_11, _12, _13) / XLen;
Flt3 vY = Flt3(_21, _22, _23) / XLen;
Flt3 vZ = Flt3(_31, _32, _33) / XLen;
Mat4x4 retM;
retM.identity();
retM._11 = vX.x;
retM._12 = vX.y;
retM._13 = vX.z;
retM._21 = vY.x;
retM._22 = vY.y;
retM._23 = vY.z;
retM._31 = vZ.x;
retM._32 = vZ.y;
retM._33 = vZ.z;
rQt = (Quat)XMQuaternionRotationMatrix(retM);
}
}
inline Flt3 Mat4x4::scaleInMatrix()const {
Flt3 scale, pos;
Quat qt;
decompose(scale, qt, pos);
return scale;
}
inline Quat Mat4x4::quatInMatrix()const {
Flt3 scale, pos;
Quat qt;
decompose(scale, qt, pos);
return qt;
}
inline Flt3 Mat4x4::transInMatrix()const {
Flt3 pos;
pos.x = _41;
pos.y = _42;
pos.z = _43;
return pos;
}
inline Mat4x4& Mat4x4::identity()
{
*this = (Mat4x4)XMMatrixIdentity();
return *this;
}
inline Mat4x4& Mat4x4::scaleIdentity() {
Flt3 Scale, Translation;
Quat Qt;
decompose(Scale, Qt, Translation);
Scale = Flt3(1.0f, 1.0f, 1.0f);
return affineTransformation(Scale, Flt3(0.0f,0.0f,0.0f), Qt, Translation);
}
inline Mat4x4& Mat4x4::scale(const Flt3& scaleVec)
{
*this = (Mat4x4)XMMatrixScalingFromVector(scaleVec);
return *this;
}
inline Mat4x4& Mat4x4::rotation(const Quat& unitQuat)
{
*this = (Mat4x4)XMMatrixRotationQuaternion(unitQuat);
return *this;
}
inline Mat4x4& Mat4x4::translation(const Flt3& transVec) {
*this = (Mat4x4)XMMatrixTranslationFromVector(transVec);
return *this;
}
inline Mat4x4& Mat4x4::transpose() {
*this = (Mat4x4)XMMatrixTranspose(*this);
return *this;
}
inline Mat4x4& Mat4x4::inverse() {
XMVECTOR Vec;
*this = (Mat4x4)XMMatrixInverse(&Vec, *this);
return *this;
}
inline Mat4x4& Mat4x4::affineTransformation2D(
const Flt2& scaleVec,
const Flt2& rotOrigin,
const float& rotation,
const Flt2& transVec) {
*this = (Mat4x4)XMMatrixAffineTransformation2D(scaleVec, rotOrigin,
rotation, transVec);
return *this;
}
inline Mat4x4& Mat4x4::affineTransformation(
const Flt3& scaleVec,
const Flt3& rotOrigin,
const Quat& unitQuat,
const Flt3& transVec) {
*this = (Mat4x4)XMMatrixAffineTransformation(scaleVec, rotOrigin,
unitQuat, transVec);
return *this;
}
inline Mat4x4& Mat4x4::affineTransformation(
const Flt3& scaleVec,
const Flt3& rotOrigin,
const Flt3& rotVec,
const Flt3& transVec) {
Quat Qt = (Quat)XMQuaternionRotationRollPitchYawFromVector(rotVec);
Qt.normalize();
return affineTransformation(scaleVec, rotOrigin, Qt, transVec);
}
inline Mat4x4& Mat4x4::lookatLH(
const Flt3& eye,
const Flt3& at,
const Flt3& up) {
*this = (Mat4x4)XMMatrixLookAtLH(eye, at,up);
return *this;
}
inline Mat4x4& Mat4x4::lookatRH(
const Flt3& eye,
const Flt3& at,
const Flt3& up) {
*this = (Mat4x4)XMMatrixLookAtRH(eye, at, up);
return *this;
}
inline Mat4x4& Mat4x4::perspectiveFovLH(
float fovY,
float aspectRatio,
float nearPlane,
float farPlane) {
*this = XMMatrixPerspectiveFovLH(fovY, aspectRatio, nearPlane, farPlane);
return *this;
}
inline Mat4x4& Mat4x4::perspectiveFovRH(
float fovY,
float aspectRatio,
float nearPlane,
float farPlane) {
*this = XMMatrixPerspectiveFovRH(fovY, aspectRatio, nearPlane, farPlane);
return *this;
}
inline Mat4x4& Mat4x4::orthographicLH(
float width,
float height,
float n,
float f) {
*this = (Mat4x4)XMMatrixOrthographicLH(width, height, n, f);
return *this;
}
inline Mat4x4& Mat4x4::strTransformation(
const Flt3& scaleVec,
const Flt3& transVec,
const Quat& unitQuat
) {
Mat4x4 Scale = (Mat4x4)XMMatrixScalingFromVector(scaleVec);
Mat4x4 Trans = (Mat4x4)XMMatrixTranslationFromVector(transVec);
Mat4x4 Qt = (Mat4x4)XMMatrixRotationQuaternion(unitQuat);
*this = Scale * Trans * Qt;
return *this;
}
inline Flt3 Mat4x4::rotXInMatrix()const {
Flt3 ret(_11, _12, _13);
Flt3 Scale = scaleInMatrix();
ret.x /= Scale.x;
ret.y /= Scale.x;
ret.z /= Scale.x;
return ret;
}
inline Flt3 Mat4x4::rotYInMatrix()const {
Flt3 ret(_21, _22, _23);
Flt3 Scale = scaleInMatrix();
ret.x /= Scale.y;
ret.y /= Scale.y;
ret.z /= Scale.y;
return ret;
}
inline Flt3 Mat4x4::rotZInMatrix()const {
Flt3 ret(_31, _32, _33);
Flt3 Scale = scaleInMatrix();
ret.x /= Scale.z;
ret.y /= Scale.z;
ret.z /= Scale.z;
return ret;
}
//--------------------------------------------------------------------------------------
/// [eBeBQfloat
//--------------------------------------------------------------------------------------
inline float floor(float f, int len) {
double ret;
ret = (double)f * pow(10.0, len);
ret = (double)(int)(ret);
return (float)(ret * pow(10.0, -len));
}
inline float round(float f, int len) {
double ret;
ret = (double)f * pow(10.0, len);
ret = (double)(int)(ret + 0.5);
return (float)(ret * pow(10.0, -len));
}
inline float ceil(float f, int len) {
double ret;
ret = (double)f * pow(10.0, len);
ret = (double)(int)(ret + 0.9);
return (float)(ret * pow(10.0, -len));
}
//--------------------------------------------------------------------------------------
/// [eBeBQFlt2
//--------------------------------------------------------------------------------------
inline const Flt2 operator *(float val, const Flt2& vec)
{
Flt2 temp( val, val);
return (Flt2)XMVectorMultiply(vec, temp);
}
inline const Flt2 operator /(float val, const Flt2& vec)
{
Flt2 temp(XMVectorReciprocal(Flt2(val, val)));
return (Flt2)XMVectorMultiply(vec, temp);
}
inline const Flt2 mulPerElem(const Flt2& vec0, const Flt2& vec1)
{
return (Flt2)XMVectorMultiply(vec0, vec1);
}
inline const Flt2 divPerElem(const Flt2& vec0, const Flt2& vec1)
{
Flt2 temp(XMVectorReciprocal(vec1));
return (Flt2)XMVectorMultiply(vec0, temp);
}
inline const Flt2 absPerElem(const Flt2& vec)
{
return (Flt2)XMVectorAbs(vec);
}
inline const Flt2 maxPerElem(const Flt2& vec0, const Flt2& vec1)
{
return (Flt2)XMVectorMax(vec0, vec1);
}
inline const Flt2 minPerElem(const Flt2& vec0, const Flt2& vec1)
{
return (Flt2)XMVectorMin(vec0, vec1);
}
inline float dot(const Flt2& vec0, const Flt2& vec1)
{
return ((Flt2)XMVector2Dot(vec0, vec1)).x;
}
inline float lengthSqr(const Flt2& vec)
{
return ((Flt2)XMVector2LengthSq(vec)).x;
}
inline float length(const Flt2& vec)
{
return ((Flt2)XMVector2Length(vec)).x;
}
inline const Flt2 normalize(const Flt2& vec)
{
return (Flt2)XMVector2Normalize(vec);
}
//--------------------------------------------------------------------------------------
/// [eBeBQFlt3
//--------------------------------------------------------------------------------------
inline const Flt3 operator *(float val, const Flt3& vec)
{
Flt3 temp(val, val, val);
return (Flt3)XMVectorMultiply(vec, temp);
}
inline const Flt3 operator /(float val, const Flt3& vec)
{
Flt3 temp(XMVectorReciprocal(Flt3(val,val,val)));
return (Flt3)XMVectorMultiply(vec, temp);
}
inline const Flt3 mulPerElem(const Flt3& vec0, const Flt3& vec1)
{
return (Flt3)XMVectorMultiply(vec0, vec1);
}
inline const Flt3 divPerElem(const Flt3& vec0, const Flt3& vec1)
{
Flt3 temp(XMVectorReciprocal(vec1));
return (Flt3)XMVectorMultiply(vec0, temp);
}
inline const Flt3 absPerElem(const Flt3& vec)
{
return (Flt3)XMVectorAbs(vec);
}
inline const Flt3 maxPerElem(const Flt3& vec0, const Flt3& vec1)
{
return (Flt3)XMVectorMax(vec0, vec1);
}
inline const Flt3 minPerElem(const Flt3& vec0, const Flt3& vec1)
{
return (Flt3)XMVectorMin(vec0, vec1);
}
inline float dot(const Flt3& vec0, const Flt3& vec1)
{
return ((Flt3)XMVector3Dot(vec0, vec1)).x;
}
inline float lengthSqr(const Flt3& vec)
{
return ((Flt3)XMVector3LengthSq(vec)).x;
}
inline float length(const Flt3& vec)
{
return ((Flt3)XMVector3Length(vec)).x;
}
inline const Flt3 normalize(const Flt3& vec)
{
return (Flt3)XMVector3Normalize(vec);
}
inline const Flt3 cross(const Flt3& vec0, const Flt3& vec1)
{
return (Flt3)XMVector3Cross(vec0, vec1);
}
inline const Flt3 reflect(const Flt3& vec, const Flt3& normal)
{
return (Flt3)XMVector3Reflect(vec, normal);
}
inline const Flt3 slide(const Flt3& vec, const Flt3& normal)
{
//vecƖ@璼s̒iςŋ߂j
float Len = bsm::dot(vec, normal);
//̒ɐL
Flt3 Contact = normal * Len;
//XCh݂͌̃xNgZ
return (vec - Contact);
}
inline float maxElem(const Flt3& vec)
{
float result;
result = (vec.x > vec.y) ? vec.x : vec.y;
result = (vec.z > result) ? vec.z : result;
return result;
}
inline float minElem(const Flt3& vec)
{
float result;
result = (vec.x < vec.y) ? vec.x : vec.y;
result = (vec.z < result) ? vec.z : result;
return result;
}
inline float angleBetweenNormals(const Flt3& norm11, const Flt3& norm2) {
return ((Flt3)XMVector3AngleBetweenNormals(norm11, norm2)).x;
}
//--------------------------------------------------------------------------------------
/// [eBeBQFlt4
//--------------------------------------------------------------------------------------
inline const Flt4 operator *(float val, const Flt4& vec)
{
Flt4 temp(val, val, val, val);
return (Flt4)XMVectorMultiply(vec, temp);
}
inline const Flt4 operator /(float val, const Flt4& vec)
{
Flt4 temp(XMVectorReciprocal(Flt4(val, val, val, val)));
return (Flt4)XMVectorMultiply(vec, temp);
}
inline const Flt4 mulPerElem(const Flt4& vec0, const Flt4& vec1)
{
return (Flt4)XMVectorMultiply(vec0, vec1);
}
inline const Flt4 divPerElem(const Flt4& vec0, const Flt4& vec1)
{
Flt4 temp(XMVectorReciprocal(vec1));
return (Flt4)XMVectorMultiply(vec0, temp);
}
inline const Flt4 absPerElem(const Flt4& vec)
{
return (Flt4)XMVectorAbs(vec);
}
inline const Flt4 maxPerElem(const Flt4& vec0, const Flt4& vec1)
{
return (Flt4)XMVectorMax(vec0, vec1);
}
inline const Flt4 minPerElem(const Flt4& vec0, const Flt4& vec1)
{
return (Flt4)XMVectorMin(vec0, vec1);
}
inline float dot(const Flt4& vec0, const Flt4& vec1)
{
return ((Flt4)XMVector4Dot(vec0, vec1)).x;
}
inline float lengthSqr(const Flt4& vec)
{
return ((Flt4)XMVector4LengthSq(vec)).x;
}
inline float length(const Flt4& vec)
{
return ((Flt4)XMVector4Length(vec)).x;
}
inline const Flt4 normalize(const Flt4& vec)
{
return (Flt4)XMVector4Normalize(vec);
}
//--------------------------------------------------------------------------------------
/// [eBeBQQuat֘A
//--------------------------------------------------------------------------------------
inline const Quat normalize(const Quat& quat)
{
return (Quat)XMQuaternionNormalize(quat);
}
inline const Flt3 rotate(const Quat& quat, const Flt3& vec)
{
return (Flt3)XMVector3Rotate(vec, quat);
}
inline const Quat rotation(const Flt3& unitVec0, const Flt3& unitVec1)
{
float cosHalfAngleX2, recipCosHalfAngleX2;
cosHalfAngleX2 = sqrtf((2.0f * (1.0f + dot(unitVec0, unitVec1))));
recipCosHalfAngleX2 = (1.0f / cosHalfAngleX2);
return Quat((cross(unitVec0, unitVec1) * recipCosHalfAngleX2), (cosHalfAngleX2 * 0.5f));
}
inline const Quat conj(const Quat& quat) {
return (Quat)XMQuaternionConjugate(quat);
}
inline const Quat inverse(const Quat& quat) {
return (Quat)XMQuaternionInverse(quat);
}
inline float dot(const Quat& quat0, const Quat& quat1) {
return ((Quat)XMQuaternionDot(quat0, quat1)).x;
}
inline const Quat facing(const Flt3& norm) {
Quat ret;
ret.facing(norm);
return ret;
}
inline const Quat facingY(const Flt3& norm) {
Quat ret;
ret.facingY(norm);
return ret;
}
//--------------------------------------------------------------------------------------
/// [eBeBQMat3x3֘A
//--------------------------------------------------------------------------------------
inline const Mat3x3 absPerElem(const Mat3x3& mat)
{
return Mat3x3(
absPerElem(mat.getMajor0()),
absPerElem(mat.getMajor1()),
absPerElem(mat.getMajor2())
);
}
inline const Mat3x3 operator *(float val, const Mat3x3& mat)
{
return mat * val;
}
inline const Mat3x3 transpose(const Mat3x3& mat)
{
return (Mat3x3)XMMatrixTranspose(mat);
}
inline const Mat3x3 inverse(const Mat3x3& mat)
{
XMVECTOR Vec;
return (Mat3x3)XMMatrixInverse(&Vec, mat);
}
inline const Mat3x3 crossMatrix(const Flt3& vec)
{
return Mat3x3(
Flt3(0.0f, vec.z, -vec.y),
Flt3(-vec.z, 0.0f, vec.x),
Flt3(vec.y, -vec.x, 0.0f)
);
}
//--------------------------------------------------------------------------------------
/// [eBeBQMat4x4֘A
//--------------------------------------------------------------------------------------
inline const Mat4x4 absPerElem(const Mat4x4& mat)
{
return Mat4x4(
absPerElem(mat.getMajor0()),
absPerElem(mat.getMajor1()),
absPerElem(mat.getMajor2()),
absPerElem(mat.getMajor3())
);
}
inline const Mat4x4 operator *(float val, const Mat4x4& mat)
{
return mat * val;
}
inline const Mat4x4 transpose(const Mat4x4& mat)
{
return (Mat4x4)XMMatrixTranspose(mat);
}
inline const Mat4x4 inverse(const Mat4x4& mat)
{
XMVECTOR Vec;
return (Mat4x4)XMMatrixInverse(&Vec, mat);
}
inline const Mat4x4 orthoInverse(const bsm::Mat4x4& tfrm)
{
Flt3 inv0, inv1, inv2;
inv0 = Flt3(tfrm.getMajor0().x, tfrm.getMajor1().x, tfrm.getMajor2().x);
inv1 = Flt3(tfrm.getMajor0().y, tfrm.getMajor1().y, tfrm.getMajor2().y);
inv2 = Flt3(tfrm.getMajor0().z, tfrm.getMajor1().z, tfrm.getMajor2().z);
return Mat4x4(
inv0,
inv1,
inv2,
Flt3((-((inv0 * tfrm.getMajor3().x) + ((inv1 * tfrm.getMajor3().y) + (inv2 * tfrm.getMajor3().z)))))
);
}
using Vec2 = Flt2;
using Vec3 = Flt3;
using Vec4 = Flt4;
using Pt2 = Flt2;
using Pt3 = Flt3;
using Col4 = Flt4;
using Plane4 = Flt4;
}
// end bsm
}
//end basecross
| true |
e9246604e2d878d3f589ffa8699392cc39ea1d8b | C++ | SergeiShvakel/TestSynchConnect | /main.cpp | UTF-8 | 1,210 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <boost/thread.hpp>
#include <boost/asio.hpp>
#include "ServerAsynch/ServerAsynch.h"
#include "ClientRequest/ClientRequest.h"
#include "ThreadPoolManager/threadmanager.h"
int main(int argc, char* argv[])
{
std::cout << "Start programm...\r\n";
std::cout << "Hardware max thread count to run: " << boost::thread::hardware_concurrency() << std::endl;
std::cout << "To ShutdownServer press 'Q' and 'Enter'" << std::endl;
ThreadManager threadManager(5);
ServerAsynch serverEcho(&threadManager);
// luanch server thread
std::thread thread_server (std::bind(ServerAsynch::start, &serverEcho));
// luanch client's threads
std::vector<std::thread*> threads;
for (int i = 0; i < 10; i++)
{
std::thread *client_thr = new std::thread(std::bind(send_request, i+1));
threads.push_back(client_thr);
}
std::for_each (threads.begin(), threads.end(), [](std::thread* t){
t->join();
});
char q = 0;
std::cin >> q;
if (q == 'q' || q == 'Q')
{
serverEcho.shutdown();
}
thread_server.join();
std::cout << "Press any key and Return for Exit...";
std::cin >> q;
std::for_each (threads.begin(), threads.end(), [](std::thread* t){
delete t;
});
return 0;
} | true |
547487b30661966431edf602c284ee07d24fca8a | C++ | MarkMansell/DirectX_Shaders | /Main.cpp | UTF-8 | 1,894 | 2.5625 | 3 | [] | no_license | #include "Application.h"
__int64 frameTimeOld = 0;
__int64 CounterStart = 0;
double countsPerSecond = 0.0;
double frameTime;
int frameCount = 0;
int fps = 0;
double GetFrameTime()
{
LARGE_INTEGER currentTime;
__int64 tickCount;
QueryPerformanceCounter(¤tTime);
tickCount = currentTime.QuadPart - frameTimeOld;
frameTimeOld = currentTime.QuadPart;
if (tickCount < 0.0f)
tickCount = 0.0f;
return float(tickCount) / countsPerSecond;
}
double GetTime()
{
LARGE_INTEGER currentTime;
QueryPerformanceCounter(¤tTime);
return double(currentTime.QuadPart - CounterStart) / countsPerSecond;
}
void StartTimer()
{
LARGE_INTEGER frequencyCount;
QueryPerformanceFrequency(&frequencyCount);
countsPerSecond = double(frequencyCount.QuadPart);
QueryPerformanceCounter(&frequencyCount);
CounterStart = frequencyCount.QuadPart;
}
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
Application * theApp = new Application();
if (FAILED(theApp->Initialise(hInstance, nCmdShow)))
{
return -1;
}
// Main message loop
MSG msg = {0};
while (WM_QUIT != msg.message)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
bool handled = false;
if (msg.message >= WM_KEYFIRST && msg.message <= WM_KEYLAST)
{
handled = theApp->HandleKeyboard(msg);
}
else if (WM_QUIT == msg.message)
break;
if (!handled)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
else
{
frameCount++;
if (GetTime() > 1.0f)
{
fps = frameCount;
frameCount = 0;
StartTimer();
}
frameTime = GetFrameTime();
theApp->Update(frameTime);
theApp->Draw();
}
}
delete theApp;
theApp = nullptr;
return (int) msg.wParam;
} | true |
03e4d81ceb5f2860161bfc6946afbba64420b87f | C++ | deanlee-practice/toheaven-2 | /교육/C++ Basic/Day_05/employeeSystem.cpp | UHC | 2,386 | 4.09375 | 4 | [] | no_license | /*
A ȸ α
: Employee
: Permanent ~ ̸, (⺻)
: Sales - ̸, (⺻ + Ǹż * ʽ)
ӽ : Temporary - ̸, (ñ*ٹð)
*/
#include<iostream>
#include<string>
using namespace std;
class Employee { // ֻ Ŭ
string name;
public:
Employee(string name):name(name){}
int getPay() { // ڽ 带 ƾѴ Ļ ڽ 尡 /
return 0;
}
void show() {
cout << "̸ :" << name << endl;
}
};
/*
Ŭ ̸: Permanent
Ŭ : Entity Ŭ
*/
class Permanent :public Employee {
//string name;
int salary;
public:
Permanent(string name, int pay)
:Employee(name), salary(pay){}
int getPay() {
return salary;
}
void show() {
Employee::show;
cout << " : " << getPay() << endl;
}
};
class Sales {
string name;
int salary;
int salesResult; // ǸŽ
int bonus; //
};
class Temporary {
string name;
int times; //ٹð
int pay; //ð
};
/*
Ŭ ̸ : EmployeeManager
Ŭ : Handler Ŭ
*/
class EmployeeManager {
// ü 迭
Employee* empList[100];
int empNum;
public:
EmployeeManager():empNum(0){}
// ϴ
void addEmployee(Employee* p) {
empList[empNum++] = p;
}
// ϴ
void showTotalSalary() {
int total = 0;
for (int i = 0; i < empNum; i++)
total += empList[i]->getPay(); // θ ƾ 带
cout << " : " << total << endl;
}
// ϴ
void showAllEmployee() {
for (int i = 0; i < empNum; i++)
empList[i]->show();
}
};
int main() {
EmployeeManager manager;
//
manager.addEmployee(new Permanent("aaa", 1000));
manager.addEmployee(new Permanent("bbb", 1500));
manager.addEmployee(new Permanent("ccc", 2000));
//
manager.showTotalSalary();
//
manager.showAllEmployee();
} | true |
facc81013dc6a4b423693cf4cd8b47c1cbea2c8f | C++ | WmdLogan/Free_Practice | /Sort/insertion_sort.cpp | UTF-8 | 506 | 3.25 | 3 | [] | no_license | //
// Created by logan on 2020/3/22.
//
#include "insertion_sort.h"
#include <iostream>
using namespace std;
void insertion_sort(int a[], int n){
int i, key;
for (i = 1; i < n; i++) {
int j = i - 1;
key = a[i];
while (a[j] > key && j >= 0) {
a[j+1] = a[j];
j--;
}
a[j+1] = key;
}
}
int main(){
int a[] = {4, 12, 2, 6, 123, 56};
insertion_sort(a, 6);
for (int i = 0; i < 6; i++) {
cout << a[i] << endl;
}
} | true |