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 |
---|---|---|---|---|---|---|---|---|---|---|---|
7fa562b8962ebeb412a56c7ba6927fae30e2a697
|
C++
|
degurii/BOJ
|
/prob_10000~/15511_League of Overwatch at Moloco (Hard).cpp
|
UHC
| 1,377 | 3.5625 | 4 |
[] |
no_license
|
/*
Է
First line contains two integers, n and m where 1 n 16 and 1 m 150.
The following m lines contain two integers where i+1th line
describes fi and si where 1 fi, si n. It is guaranteed that fi si for all i.
Your output should be a single line that contains a string "POSSIBLE" or "IMPOSSIBLE" (quotes for clarity only).
*/
/*
solution:
ɰϴ ȣ ̺б ̷°
ȣ Ű澲 ʾƵ ȴ
*/
#include <iostream>
#include <vector>
using namespace std;
int n, m;
vector<vector<int> > p;
vector<int> color;
vector<bool> check;
void dfs(int now, int c) {
check[now] = true;
color[now] = c;
for (auto &next : p[now]) {
if (!check[next]) {
dfs(next, 3 - c);
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> n >> m;
p.resize(n + 1);
color.resize(n + 1);
check.resize(n + 1);
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
p[u].push_back(v);
p[v].push_back(u);
}
bool flag = true;
for (int i = 1; i < n + 1; i++) {
if (check[i] == false)
dfs(i, 1);
}
for (int now = 1; now < n + 1; now++) {
for (auto &next : p[now]) {
if (color[next] == color[now]) {
flag = false;
break;
}
}
if (!flag) break;
}
if (flag)cout << "POSSIBLE";
else cout << "IMPOSSIBLE";
}
| true |
4c11dcde0928d2e660e652ddd9493bee1e5f42a5
|
C++
|
rahulsahukar/cplusplus
|
/map.cc
|
UTF-8
| 386 | 3.078125 | 3 |
[] |
no_license
|
#include<iostream>
#include<map>
using namespace std;
int main()
{
map<int,char> m;
m[1]='a';
m[2]='b';
m[1]='c';
m.insert(pair<int,char>(3,'d'));
for(map<int,char>::iterator it=m.begin();it!=m.end();it++)
{
cout<<it->first<<" "<<it->second<<endl;
}
map<int,char>::iterator it=m.find(5);
if(it==m.end())
cout<<it->second<<endl;
}
| true |
ece6d69b96e2f22834e5e116f7a96ab646299edd
|
C++
|
SamBeaudoin/GAME1011_Assignment_Text-Based
|
/Text_Based_Assignment/TextManager.h
|
UTF-8
| 525 | 2.96875 | 3 |
[] |
no_license
|
#pragma once
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class TextManager
{
private:
TextManager();
void BuildStringArrays();
// String arrays
string Descriptions[20];
string Responses[20];
string Endings[5];
public:
// Setters
void setDescription(int index, string desc);
void setResponse(int index, string respo);
void setEndings(int index, string ending);
// Getters
string getDescription(int index);
string getResponse(int index);
string getEnding(int index);
};
| true |
6f3870f2f7f7e48dec7ae6be068dce5944c51d86
|
C++
|
EdimarBauer/TCC
|
/khbst.cpp
|
UTF-8
| 7,172 | 3.15625 | 3 |
[] |
no_license
|
/*
* Author: Edimar Jacob Bauer
* Email: edimarjb@gmail.com
* Date: October 11, 2018
*/
/*
* Key Hidden Binary Search Tree
*
* Estrutura dinâmica como a DHBST (Dinamic Hidden Binary Search tree), nós podem ser inseridos no meio
* Porém, ao invés de guardar a quantidade de nós faltantes acima (miss), guarda-se o valor de referência do nó
*
* O valor de referência do nó é calculado com base nos valores chaves dos nós filhos através da função lca()
* logo após a inserção do mesmo
*
* Nó inserido no meio com apenas um nó filho, usa o próprio valor chave mais o valor chave do nó filho
* para satisfazer a função lca()
*
* Nó inserido como nó folha usa seu próprio valor chave como valor de refência
*
* Vantagens com relação a DHBST
* Não necessita calcular cada nível durante a operação de inserção
* Um pouco mais simples de programar
*
* Desvantagens com relação a DHBST
* Usa a função lca() após cada inserção, exceto quando inserido como nó folha, cuja complexidade é O(log(B))
* Usa mais memória, pois a DHBST usa um char (1 byte) para guardar o miss, enquanto a KHBST guarda o
* valor de referência, que é do tamanho da chave
*
*
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int N = (1 << 10);
int last, total;
set<int> mapa;
struct Tree{
int key, ref;
struct Tree *left, *right;
};
long long altura(Tree *tree, int alt);
void clear(Tree *tree);
Tree* newNode(int x);
int lca(int x, int y);
Tree* makeHead(Tree* child, int x);
void createMiddleNode(Tree *tree, int x);
void insert(Tree *&root, int x);
Tree* search(Tree *tree, int x);
int replace(Tree **tree);
void remove(Tree *&root, int x);
void print(Tree *tree, int height);
void check_is_correct(Tree *tree);
void check(Tree *tree);
int main(){
Tree* tree = NULL;
int k = log2(N), x;
clock_t tInicio, tFim;
double tempo;
while(N < (1 << 25) ){
total = 0; tempo = 0;
clear(tree); mapa.clear();
tree = NULL;
for (int i = 1; i <= N; i++){
do{
x = rand() % (1 << 30);
}while(mapa.count(x) > 0);
mapa.insert(x);
tInicio = clock();
insert(tree, x);
tFim = clock();
tempo += ( (double)(tFim - tInicio) / (CLOCKS_PER_SEC / 1000.0));
}
ll alt = altura(tree, 0);
double altMedia = ((double)alt / total);
printf("%d tempo: %.0lf alt_media: %.4lf elementos: %d\n", k++, tempo, altMedia, total);
N <<= 1;
}
}
//#####################################################################################################
//#####################################################################################################
long long altura(Tree *tree, int alt){
if (!tree) return 0;
long long nos = alt;
nos += altura(tree->left, alt+1);
//printf("%d alt: %d\n", tree->key, alt);
nos += altura(tree->right, alt+1);
return nos;
}
void clear(Tree *tree){
if (tree == NULL) return;
clear(tree->left);
clear(tree->right);
free(tree);
}
Tree* newNode(int x){
Tree *tree = new Tree;
tree->key = tree->ref = x;
tree->left = tree->right = NULL;
total++;
return tree;
}
int lca(int x, int y){
//x deve ser menor que y sempre
//if (x > y) swap(x, y);
int dy = y & -y;
int dx = x & -x;
if (dy > dx){ //ser maior significa estar mais alto na árvore, ou seja, mais próximo do pai comum
while(x <= (y - dy)){
y -= dy;
dy = y & -y;
}
return y;
}else{
while(y >= (x + dx)){
x += dx;
dx = x & -x;
}
return x;
}
}
void insert(Tree *&root, int x){
//printf("Inserting %d\n", x);
if (!x) return;
if (root == NULL) root = newNode(x);
else{
Tree **parent = &root;
Tree *tree = root;
int limit;
while(tree->key != x){
limit = tree->ref & -tree->ref;
if ((tree->ref + limit) <= x){ //cria nó pai direito
*parent = newNode(x);
(*parent)->left = tree;
(*parent)->ref = lca(tree->key, x);
return;
}else if (x <= (tree->ref - limit) ){ //cria nó pai esquerdo
*parent = newNode(x);
(*parent)->right = tree;
(*parent)->ref = lca(x, tree->key);
return;
}
if (x == tree->ref) swap(x, tree->key); //propagação estendida
if (x < tree->ref){
if (x > tree->key) swap(x, tree->key); //propagação a esquerda
if (tree->left == NULL){
tree->left = newNode(x);
return;
}
parent = &(tree->left);
tree = tree->left;
}else{
if (x < tree->key) swap(x, tree->key); //propagação a direita
if (tree->right == NULL){
tree->right = newNode(x);
return;
}
parent = &(tree->right);
tree = tree->right;
}
}
}
}
Tree* search(Tree *tree, int x){
while(tree != NULL){
if (tree->key == x) return tree;
if (x < tree->key) tree = tree->left;
else tree = tree->right;
}
return NULL;
}
int replace(Tree **tree){
while((*tree)->right)
tree = &((*tree)->right);
int x = (*tree)->key;
if ((*tree)->left)
(*tree)->key = replace(&((*tree)->left));
else{
free(*tree);
*tree = NULL;
}
return x;
}
void remove(Tree *&root, int x){
//printf("Removing %d\n", x);
Tree **tree = &root;
while(*tree != NULL){
if ((*tree)->key == x){
if ((*tree)->left == NULL && (*tree)->right == NULL){
free(*tree);
*tree = NULL;
}else{
if ((*tree)->left && (*tree)->right)
(*tree)->key = replace(&((*tree)->left));
else{
Tree *aux = (*tree)->left ? (*tree)->left : (*tree)->right;
free(*tree);
*tree = aux;
}
}
total--;
return;
}
if (x < (*tree)->key) tree = &((*tree)->left);
else tree = &((*tree)->right);
}
}
void print(Tree *tree, int height){
if (tree == NULL) return;
print(tree->left, height+1);
cout << tree->key << " " << height << " ref: " << tree->ref << endl;
print(tree->right, height+1);
}
void check_is_correct(Tree *tree){
last = -1;
int to = total;
check(tree);
if (total != 0){
printf("Diference of %d elements\n", total);
exit(0);
}
total = to;
}
void check(Tree *tree){
if (tree == NULL) return;
check(tree->left);
if (last >= tree->key){
printf("Err between nodes %d and %d\n", last, tree->key);
exit(0);
}
last = tree->key;
total--;
check(tree->right);
}
| true |
ef9b2adc6ae7d877e396131b7256f024a8b4419e
|
C++
|
Adnan-13/URI-Submissions
|
/1914/main.cpp
|
UTF-8
| 588 | 2.875 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
string player1, ans1, player2, ans2;
cin >> player1 >> ans1 >> player2 >> ans2;
int num1, num2;
scanf("%d%d", &num1, &num2);
if((num1 + num2) % 2 == 0 )
{
if(ans1 == "PAR") cout << player1 << endl;
else cout << player2 << endl;
}
else
{
if(ans1 == "IMPAR") cout << player1 << endl;
else cout << player2 << endl;
}
}
return 0;
}
| true |
274e02f0bc4a283139014e1ccbb9dbeff85f5155
|
C++
|
owhyy/cpp-primer
|
/unorganised/r_l_values.cpp
|
UTF-8
| 265 | 3 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
using namespace std;
using std::vector;
using std::string;
void printSum(int n)
{
cout<<n+n<<endl;
}
int main()
{
int i = 5;
printSum(i);
printSum(2+3);
return 0;
}
| true |
269b40d403db6e8a8531199b0b4a31f3a329fe9a
|
C++
|
petrarce/real_time_graphics
|
/libs/typed-geometry/src/typed-geometry/feature/fwd_diff.hh
|
UTF-8
| 4,868 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#include <typed-geometry/common/scalar_math.hh>
#include <typed-geometry/detail/utility.hh>
#include <typed-geometry/types/scalars/fwd_diff.hh>
namespace tg
{
// ================================= Operators =================================
// auto-diff
template <class T>
TG_NODISCARD constexpr fwd_diff<T> operator+(fwd_diff<T> const& a, fwd_diff<T> const& b)
{
return {a.value + b.value, a.derivative + b.derivative};
}
template <class T>
TG_NODISCARD constexpr fwd_diff<T> operator-(fwd_diff<T> const& a, fwd_diff<T> const& b)
{
return {a.value - b.value, a.derivative - b.derivative};
}
template <class T>
TG_NODISCARD constexpr fwd_diff<T> operator*(fwd_diff<T> const& a, fwd_diff<T> const& b)
{
return {a.value * b.value, a.derivative * b.value + a.value * b.derivative};
}
template <class T>
TG_NODISCARD constexpr fwd_diff<T> operator/(fwd_diff<T> const& a, fwd_diff<T> const& b)
{
return {a.value / b.value, (a.derivative * b.value - a.value * b.derivative) / (b.value * b.value)};
}
template <class T>
TG_NODISCARD constexpr fwd_diff<T> operator+(fwd_diff<T> const& a)
{
return {a.value, a.derivative};
}
template <class T>
TG_NODISCARD constexpr fwd_diff<T> operator-(fwd_diff<T> const& a)
{
return {-a.value, -a.derivative};
}
// scalars
template <class T>
TG_NODISCARD constexpr fwd_diff<T> operator+(fwd_diff<T> const& a, dont_deduce<T> const& b)
{
return {a.value + b, a.derivative};
}
template <class T>
TG_NODISCARD constexpr fwd_diff<T> operator+(dont_deduce<T> const& a, fwd_diff<T> const& b)
{
return {a + b.value, b.derivative};
}
template <class T>
TG_NODISCARD constexpr fwd_diff<T> operator-(fwd_diff<T> const& a, dont_deduce<T> const& b)
{
return {a.value - b, a.derivative};
}
template <class T>
TG_NODISCARD constexpr fwd_diff<T> operator-(dont_deduce<T> const& a, fwd_diff<T> const& b)
{
return {a - b.value, -b.derivative};
}
template <class T>
TG_NODISCARD constexpr fwd_diff<T> operator*(fwd_diff<T> const& a, dont_deduce<T> const& b)
{
return {a.value * b, a.derivative * b};
}
template <class T>
TG_NODISCARD constexpr fwd_diff<T> operator*(dont_deduce<T> const& a, fwd_diff<T> const& b)
{
return {a * b.value, a * b.derivative};
}
template <class T>
TG_NODISCARD constexpr fwd_diff<T> operator/(fwd_diff<T> const& a, dont_deduce<T> const& b)
{
return {a.value / b, a.derivative / b};
}
template <class T>
TG_NODISCARD constexpr fwd_diff<T> operator/(dont_deduce<T> const& a, fwd_diff<T> const& b)
{
return {a / b.value, -a * b.derivative / (b.value * b.value)};
}
// comparisons
template <class T>
TG_NODISCARD constexpr bool operator<(fwd_diff<T> const& a, fwd_diff<T> const& b)
{
return a.value < b.value;
}
template <class T>
TG_NODISCARD constexpr bool operator<(fwd_diff<T> const& a, dont_deduce<T> const& b)
{
return a.value < b;
}
template <class T>
TG_NODISCARD constexpr bool operator<(dont_deduce<T> const& a, fwd_diff<T> const& b)
{
return a < b.value;
}
template <class T>
TG_NODISCARD constexpr bool operator<=(fwd_diff<T> const& a, fwd_diff<T> const& b)
{
return a.value <= b.value;
}
template <class T>
TG_NODISCARD constexpr bool operator<=(fwd_diff<T> const& a, dont_deduce<T> const& b)
{
return a.value <= b;
}
template <class T>
TG_NODISCARD constexpr bool operator<=(dont_deduce<T> const& a, fwd_diff<T> const& b)
{
return a <= b.value;
}
template <class T>
TG_NODISCARD constexpr bool operator>(fwd_diff<T> const& a, fwd_diff<T> const& b)
{
return a.value > b.value;
}
template <class T>
TG_NODISCARD constexpr bool operator>(fwd_diff<T> const& a, dont_deduce<T> const& b)
{
return a.value > b;
}
template <class T>
TG_NODISCARD constexpr bool operator>(dont_deduce<T> const& a, fwd_diff<T> const& b)
{
return a > b.value;
}
template <class T>
TG_NODISCARD constexpr bool operator>=(fwd_diff<T> const& a, fwd_diff<T> const& b)
{
return a.value >= b.value;
}
template <class T>
TG_NODISCARD constexpr bool operator>=(fwd_diff<T> const& a, dont_deduce<T> const& b)
{
return a.value >= b;
}
template <class T>
TG_NODISCARD constexpr bool operator>=(dont_deduce<T> const& a, fwd_diff<T> const& b)
{
return a >= b.value;
}
// ================================= Math =================================
template <class T>
TG_NODISCARD constexpr fwd_diff<T> abs(fwd_diff<T> const& v)
{
return {abs(v.value), v.derivative * sign(v.value)};
}
template <class T>
TG_NODISCARD constexpr fwd_diff<T> sqrt(fwd_diff<T> const& v)
{
auto const s = sqrt(v.value);
return {s, v.derivative / (s + s)};
}
template <class T>
TG_NODISCARD constexpr fwd_diff<T> exp(fwd_diff<T> const& v)
{
auto const e = exp(v.value);
return {e, v.derivative * e};
}
template <class T>
TG_NODISCARD constexpr fwd_diff<T> log(fwd_diff<T> const& v)
{
return {log(v.value), v.derivative / v.value};
}
}
| true |
59801adcd9da39f1dd92101233ca545505be5d2f
|
C++
|
green-fox-academy/nemethricsi
|
/week-04/day-2/Zoo/main.cpp
|
UTF-8
| 754 | 3.046875 | 3 |
[] |
no_license
|
#include <iostream>
#include "Animal.h"
#include "Mammal.h"
#include "EggLayer.h"
#include "Reptile.h"
#include "EggLayer.h"
#include "Bird.h"
int main(int argc, char *args[])
{
Reptile reptile("Crocodile");
Mammal mammal("Koala");
Bird bird("Parrot");
Bird bird2("Galamb", 2, Gender::FEMALE, 40, 45);
std::cout << "How do you breed?" << std::endl;
std::cout << "A " << reptile.getName() << " is breeding by " << reptile.breed() << std::endl;
std::cout << "A " << mammal.getName() << " is breeding by " << mammal.breed() << std::endl;
std::cout << "A " << bird.getName() << " is breeding by " << bird.breed() << std::endl;
std::cout << "A " << bird2.getName() << " is breeding by " << bird.breed() << std::endl;
}
| true |
b056dc53adfe0d5e89d9bb96e68fce8f3bea623d
|
C++
|
kmyk/toyama1710_cpp_library
|
/queue/queue_aggregation.cpp
|
UTF-8
| 2,100 | 3.109375 | 3 |
[] |
no_license
|
#include <iostream>
#include <cstdio>
#include <cassert>
#include <functional>
#include <stack>
using namespace std;
using llong = long long;
//===
// #include <stack>
// #include <cassert>
template<class SemiGroup, class OP = function<SemiGroup(SemiGroup, SemiGroup)> >
struct QueueAggregation {
using Stack = stack<SemiGroup>;
const OP merge;
Stack front_st, back_st;
Stack front_sum, back_sum;
size_t sz;
QueueAggregation(const OP &f):merge(f) {
sz = 0;
};
SemiGroup fold() {
assert(sz > 0);
if (front_sum.empty()) return back_sum.top();
else if (back_sum.empty()) return front_sum.top();
else return merge(front_sum.top(), back_sum.top());
};
void push(SemiGroup d) {
sz++;
back_st.push(d);
if (back_sum.empty()) back_sum.push(d);
else back_sum.push(merge(back_sum.top(), d));
};
void pop() {
assert(sz > 0);
sz--;
if (front_st.empty()) {
front_st.push(back_st.top());
front_sum.push(back_st.top());
back_st.pop();
back_sum.pop();
while (!back_st.empty()) {
front_st.push(back_st.top());
front_sum.push(merge(front_sum.top(), back_st.top()));
back_st.pop();
back_sum.pop();
}
}
front_st.pop();
front_sum.pop();
};
bool empty() {
return sz == 0;
};
size_t size() {
return sz;
};
};
//===
int AOJ_DSL3D() {
llong n;
llong l;
static llong arr[1000005];
QueueAggregation<llong> smin([](auto l, auto r){return min(l, r);});
cin >> n >> l;
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
for (int i = 0; i < l; i++) {
smin.push(arr[i]);
}
cout << smin.fold();
for (int i = l; i < n; i++) {
smin.pop();
smin.push(arr[i]);
cout << ' ' << smin.fold();
}
cout << endl;
return 0;
}
int main() {
return AOJ_DSL3D();
}
| true |
7a3ab39ed6ee8bf64c3f8de3bb3ea89aacd8762e
|
C++
|
csuhuangcheng/render
|
/render/point.cpp
|
UTF-8
| 393 | 2.875 | 3 |
[] |
no_license
|
#include "render/point.hpp"
namespace Render {
Point::Point(float x, float y): x(x), y(y) {
}
void Point::Draw(Target& target) const {
(void) target;
}
void Point::SetX(float x){
this->x = x;
}
void Point::SetY(float y){
this->y = y;
}
float Point::X(void) const noexcept {
return x;
}
float Point::Y(void) const noexcept {
return y;
}
} /* namespace Render */
| true |
22b1632f190cd6e1acee68aa31ef3b0bd539b623
|
C++
|
ttt977/algorithm
|
/boj/2252.cpp
|
UTF-8
| 548 | 2.875 | 3 |
[] |
no_license
|
#include <iostream>
#include <queue>
using namespace std;
int N,M;
vector<int> v[32001];
queue<int> q;
int degree[32001];
int main(void)
{
int a=0,b=0;
cin >> N >> M;
for(int i=0;i<M;i++)
{
scanf("%d %d",&a,&b);
v[a].push_back(b);
degree[b]++;
}
for(int i=1;i<=N;i++)
{
if(degree[i] == 0)
q.push(i);
}
while(!q.empty())
{
int cur = q.front();
cout << cur <<" ";
q.pop();
for(int i=0;i<v[cur].size();i++)
{
int tmp = v[cur][i];
degree[tmp]--;
if(degree[tmp] == 0)
q.push(tmp);
}
}
return 0;
}
| true |
999d0fded4e74ebbedaa74ff40856be348236011
|
C++
|
pva701/codes
|
/List/list.cpp
|
UTF-8
| 4,474 | 3.3125 | 3 |
[] |
no_license
|
#include "list.h"
//begin of dangerous zone
list::list() {
head = new node();
head->next = head;
head->prev = head;
}
list::~list() {
node *cur = head;
cur = cur->next;
while (cur != head) {
node *nx = cur->next;
delete cur;
cur = nx;
}
delete cur;
}
list::list(list const& oth)
{
node *cur = oth.head->next;
head = new node();
try
{
node *tmpPrev = head;
while (cur != oth.head) {
node *curNode = new node(cur->val);
curNode->next = 0;//end of list if exc
tmpPrev->next = curNode;
curNode->prev = tmpPrev;
tmpPrev = curNode;
cur = cur->next;
}
tmpPrev->next = head;
head->prev = tmpPrev;
} catch (...) {
node *cur = head->next;
while (cur != 0) {
node *nx = cur->next;
delete cur;
cur = nx;
}
head->next = head;
head->prev = head;
throw;
}
}
list& list::operator = (list const& oth) {
if (this == &oth)
return *this;
list tmp(oth);
swap(tmp.head, this->head);
return *this;
}
//end of dangerous zone
bool list::empty() const {
return head->next == head;
}
void list::push_back(int value) {
node *newNode = new node(value);
newNode->prev = head->prev;
head->prev->next = newNode;
newNode->next = head;
head->prev = newNode;
}
int& list::back() {
assert(!empty());
return head->prev->val;
}
const int& list::back() const {
assert(!empty());
return head->prev->val;
}
void list::pop_back() {
assert(!empty());
node *last = head->prev;
last->prev->next = head;
head->prev = last->prev;
delete last;
}
void list::push_front(int value) {
node *newNode = new node(value);
node *first = head->next;
newNode->next = first;
first->prev = newNode;
head->next = newNode;
newNode->prev = head;
}
int& list::front() {
assert(!empty());
return head->next->val;
}
const int& list::front() const {
assert(!empty());
return head->next->val;
}
void list::pop_front() {
assert(!empty());
node *first = head->next;
head->next = first->next;
first->next->prev = head;
delete first;
}
list::iterator list::begin() {
return iterator(head->next);
}
list::const_iterator list::begin() const {
return const_iterator(head->next);
}
list::iterator list::end() {
return iterator(head);
}
list::const_iterator list::end() const {
return const_iterator(head);
}
void list::insert(iterator pos, int value) {
node *newNode = new node(value);
node *v = pos.cur;
newNode->prev = v->prev;
v->prev->next = newNode;
newNode->next = v;
v->prev = newNode;
}
void list::erase(iterator pos) {
node *v = pos.cur;
v->prev->next = v->next;
v->next->prev = v->prev;
delete v;
}
void list::splice(iterator pos, list &other, iterator first, iterator last) {
if (first == last)
return;
node *fV = first.cur;
node *lV = last.cur->prev;
fV->prev->next = lV->next;
//fv->prev = 0;
lV->next->prev = fV;
//lv->next = 0;
node *v = pos.cur;
v->prev->next = fV;
fV->prev = v->prev;
lV->next = v;
v->prev = lV;
}
//iterators
list::iterator::iterator() {
cur = 0;
}
list::iterator::iterator(node *oth) {
cur = oth;
}
int& list::iterator::operator * () const {
return cur->val;
}
list::iterator& list::iterator::operator ++ () {
cur = cur->next;
return *this;
}
list::iterator list::iterator::operator ++ (int) {
iterator tmp = *this;
cur = cur->next;
return tmp;
}
list::iterator& list::iterator::operator --() {
cur = cur->prev;
return *this;
}
list::iterator list::iterator::operator -- (int) {
iterator tmp = *this;
cur = cur->prev;
return tmp;
}
//const iterator
list::const_iterator::const_iterator(node *oth) {
cur = oth;
}
const int& list::const_iterator::operator * () const {
return cur->val;
}
bool operator == (list::iterator const& a, list::iterator const& b) {
return a.cur == b.cur;
}
bool operator != (list::iterator const& a, list::iterator const& b) {
return a.cur != b.cur;
}
ostream& operator << (ostream& out, list const& a) {
list::node *cur = a.head->next;
while (cur != a.head) {
out << cur->val << " ";
cur = cur->next;
}
return out;
}
| true |
e624e1907f176be60b6024b9a995685be368c830
|
C++
|
ulinka/tbcnn-attention
|
/github_code_index_sort/cpp/5/123.c
|
UTF-8
| 846 | 3.296875 | 3 |
[] |
no_license
|
//============================================================================
// Name : bubble-sort.cpp
// Author : Lysander Gutierrez
// Date :
// Copyright :
// Description : Implementation of bubble sort in C++
//============================================================================
#include "sort.h"
void
BubbleSort::sort(int A[], int size) // main entry point
{
/* Complete this function with the implementation of bubble sort algorithm
Record number of comparisons in variable num_cmps of class Sort
*/
for(int iter=1; iter<size; iter++)
{
bool IsSorted=false;
for(int q=0; q<size-iter; q++)
{
if(A[q]>A[q+1])
{
num_cmps++;
int holder=A[q];
A[q]=A[q+1];
A[q+1]=holder;
IsSorted=true;
}
if(!IsSorted)
{
num_cmps++;
IsSorted=true;
}
}
}
}
| true |
f822e13be7b905550b1d51d2735f8a2cd1a6a2d3
|
C++
|
Dogbone0714/C-_Database
|
/A45.cpp
|
UTF-8
| 217 | 2.5625 | 3 |
[] |
no_license
|
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main(void){
int a;
cin>>a;
for(int i=2;i<=a*2;i+=2){
for(int j=i;j<i+i;j+=2){
cout<<j<<" ";
}
cout<<endl;
}
}
| true |
96a13f83da0da72ca2a0c221fefb2dacad6e2f88
|
C++
|
KristinaGebel/HW2
|
/CShape.h
|
UTF-8
| 604 | 2.8125 | 3 |
[] |
no_license
|
// Filename:CShape.H
// Description: An Abstract class to encapsulate the Shape properties
// Author: Kristina Gebel
// Date Modified: November 20, 2020
//
#include "Cpoint.h"
#include "CColor.h"
#pragma once
#if !defined(_CSHAPE_H_)
#define _CSHAPE_H_
class CShape
{
public:
// Default Constructor
CShape(void);
// Default Destructor
~CShape(void);
public:
// Calculate the area of this Shape
double calcArea();
// Stub that would normally draw this Shape
bool draw();
public:
CPoint m_center;
CColor m_color;
double m_rotation;
};
#endif // _CSHAPE_H_
| true |
c5851f5f3025343d7e534e1d91c3f2acac00d912
|
C++
|
kkminseok/Git_Tutorial
|
/Algorithm/Baekjoon/1874.cpp
|
UHC
| 1,270 | 3.015625 | 3 |
[] |
no_license
|
#include<iostream>
#include<stack>
#include<cstring>
#include<queue>
using namespace std;
void Solution()
{
int n;
cin >> n;
stack<int> s;
queue<char> q;
bool* check = new bool[n + 1];
memset(check, false, sizeof(check));
for (int i = 0; i < n; ++i)
{
int input;
cin >> input;
if (s.empty())
{
for (int j = 1; j <= input; ++j)
{
if (j == input && check[j] == true )
{
cout << "No";
return;
}
else if (check[j] == true)
continue;
s.push(j);//ó push
check[j] = true;
q.push('+');
}
s.pop();
q.push('-');
}
else
{
if (s.top() < input)
{
if (check[input] == true)
{
cout << "No" << '\n';
return;
}
for (int j = s.top() + 1; j <= input; ++j)
{
if (check[j] == true)
continue;
s.push(j);
check[j] = true;
q.push('+');
}
s.pop();
q.push('-');
}
else
{
for (int j = s.top(); j >= input; --j)
{
if (!s.empty())
{
s.pop();
q.push('-');
}
}
}
}
}
int qsize = q.size();
for (int i = 0; i < qsize; ++i)
{
cout << q.front() << '\n';
q.pop();
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
Solution();
}
| true |
43dfa51f2f1583263f628acb546de84a7ad3e610
|
C++
|
ybieri/algolab
|
/2018/week4/importantbridges/importantbridges.cpp
|
UTF-8
| 3,315 | 2.859375 | 3 |
[] |
no_license
|
// Includes
// ========
// STL includes
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
#include <cassert>
// BGL includes
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/graph/prim_minimum_spanning_tree.hpp>
#include <boost/graph/kruskal_min_spanning_tree.hpp>
#include <boost/graph/biconnected_components.hpp>
#include <boost/graph/max_cardinality_matching.hpp>
// Namespaces
using namespace std;
using namespace boost;
// Define custom interior edge property
namespace boost {
enum edge_component_t { edge_component = 216 };
// arbitrary, unique id
BOOST_INSTALL_PROPERTY(edge, component);
}
#define REP(i,n) for(int i=0; i<(int)n; ++i)
#define ALL(x) (x).begin(), (x).end()
// BGL Graph definitions
// =====================
// Graph Type, OutEdgeList Type, VertexList Type, (un)directedS
typedef adjacency_list<vecS, vecS, undirectedS, // Use vecS for the VertexList! Choosing setS for the OutEdgeList disallows parallel edges.
no_property, // interior properties of vertices
property<edge_component_t, int> // interior properties of edges
> Graph;
typedef graph_traits<Graph>::edge_descriptor Edge; // Edge Descriptor: an object that represents a single edge.
typedef graph_traits<Graph>::vertex_descriptor Vertex; // Vertex Descriptor: with vecS vertex list, this is really just an int in the range [0, num_vertices(G)).
typedef graph_traits<Graph>::edge_iterator EdgeIt; // to iterate over all edges
typedef graph_traits<Graph>::out_edge_iterator OutEdgeIt; // to iterate over all outgoing edges of a vertex
typedef property_map<Graph, edge_component_t>::type ComponentMap;
// Functions
// =========
void testcases() {
// Create Graph, Vertices and Edges
// ================================
int V, E;
cin >> V >> E;
Graph G(V); // creates an empty graph on n vertices
REP(i,E){
int u, v; cin >> u >> v;
Edge e; bool success;
tie(e, success) = add_edge(u, v, G); // Adds edge from u to v. If parallel edges are allowed, success is always true.
assert(source(e, G) == u && target(e, G) == v); // This shows how to get the vertices of an edge
}
// Biconnected components
// ====================
ComponentMap componentmap = get(edge_component, G); // We MUST use such a vector as an Exterior Property Map: Vertex -> Component
int nbcc = biconnected_components(G, componentmap);
vector<int> componentsize(nbcc);
EdgeIt ebeg, eend;
for (tie(ebeg, eend) = edges(G); ebeg != eend; ++ebeg) {
componentsize[componentmap[*ebeg]]++;
}
vector<pair<int,int>> important_bridges;
for (tie(ebeg, eend) = edges(G); ebeg != eend; ++ebeg) {
if(componentsize[componentmap[*ebeg]] == 1){
int u = source(*ebeg, G);
int v = target(*ebeg, G);
important_bridges.push_back(make_pair(min(u,v), max(u,v)));
}
}
sort(ALL(important_bridges));
cout << important_bridges.size() << endl;
REP(i,important_bridges.size()){
cout << important_bridges[i].first << " " << important_bridges[i].second << endl;
}
}
// Main function looping over the testcases
int main() {
std::ios_base::sync_with_stdio(false); // if you use cin/cout. Do not mix cin/cout with scanf/printf calls!
int T; cin >> T;
while(T--) testcases();
return 0;
}
| true |
77d45b0f9ee3e5c942fe9ed90d05dba0b3291bc5
|
C++
|
ssahillppatell/OOAD-Project
|
/classes/product.cpp
|
UTF-8
| 1,216 | 3.375 | 3 |
[] |
no_license
|
class Product {
private :
string username;
string id;
string name;
string category;
double price;
int quantity;
double discount;
public :
void setDetails(string, string, string, string, double, int, double);
string getId();
string getName();
double getPrice();
int getQuantity();
double getDiscount();
void showDetails();
};
void Product :: setDetails (string username, string id, string name, string category, double price, int quantity, double discount = 0.00) {
this -> id = id;
this -> name = name;
this -> category = category;
this -> price = price;
this -> quantity = quantity;
this -> discount = discount;
}
string Product :: getId () {
return this -> id;
}
string Product :: getName () {
return this -> name;
}
double Product :: getPrice() {
return this -> price;
}
int Product :: getQuantity () {
return this -> quantity;
}
double Product :: getDiscount () {
return this -> discount;
}
void Product :: showDetails () {
cout << "Id : " << this -> id << '\n';
cout << "Name : " << this -> name << '\n';
cout << "Price : " << this -> price << '\n';
cout << "Quantity : " << this -> quantity << '\n';
cout << "Discount % : " << this -> discount << '\n';
}
| true |
68365ba7151f3bec50a4cd10f6c1a86127da57d0
|
C++
|
atabakp/C--
|
/A&D/Midterm/Midterm/Node.h
|
UTF-8
| 924 | 3.296875 | 3 |
[] |
no_license
|
#pragma once
template <typename T>
class Node
{
public:
T data;
Node<T> *next;
Node<T> *prev;
public:
Node();
~Node();
void setData(T val);
T getData();
void setNext(Node* next);
Node<T>* getNext();
void setPrev(Node* Prev);
Node<T>* getPrev();
};
#pragma once
#include "Node.h"
#include <stdint.h>
using namespace std;
template <class T>
Node<T>::Node()
{
this->data = 0;
this->next = NULL;
this->prev = NULL;
}
template <typename T>
Node<T>::~Node()
{
}
template <typename T>
void Node<T>::setData(T val)
{
this->data = val;
}
template <typename T>
T Node<T>::getData()
{
return this->data;
}
template <typename T>
void Node<T>::setNext(Node* next)
{
this->next = next;
}
template <typename T>
Node<T>* Node<T>::getNext()
{
return this->next;
}
template <typename T>
void Node<T>::setPrev(Node* prev)
{
this->prev = prev;
}
template <typename T>
Node<T>* Node<T>::getPrev()
{
return this->prev;
}
| true |
b6315d3d3f51f2d8886a36cdeaa2babd487bec74
|
C++
|
agarciarin/vmu931
|
/src/sensor.cpp
|
UTF-8
| 7,640 | 2.65625 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
#include "vmu931/sensor.hpp"
#include "vmu931/commands.hpp"
#include <algorithm>
#include <cassert>
#include <type_traits>
#include <boost/asio/write.hpp>
#include <boost/endian/conversion.hpp>
namespace vmu931
{
template<typename T>
T read(const uint8_t* ptr);
template<>
uint32_t read(const uint8_t* ptr)
{
uint32_t v = *reinterpret_cast<const uint32_t*>(ptr);
boost::endian::big_to_native_inplace(v);
return v;
}
template<>
float read(const uint8_t* ptr)
{
uint32_t tmp = read<uint32_t>(ptr);
return *reinterpret_cast<float*>(&tmp);
}
template<>
uint8_t read(const uint8_t* ptr)
{
return *ptr;
}
template<typename T>
T read_3d(const uint8_t* ptr)
{
static_assert(std::is_base_of<Data3D, T>::value, "vmu931::Data3D derived type required");
T data;
data.timestamp = vmu931::read<uint32_t>(ptr);
data.x = vmu931::read<float>(ptr + 4);
data.y = vmu931::read<float>(ptr + 8);
data.z = vmu931::read<float>(ptr + 12);
return data;
}
template<typename T>
T read_4d(const uint8_t* ptr)
{
static_assert(std::is_base_of<Data4D, T>::value, "vmu931::Data4D derived type required");
T data;
data.timestamp = vmu931::read<uint32_t>(ptr);
data.w = vmu931::read<float>(ptr + 4);
data.x = vmu931::read<float>(ptr + 8);
data.y = vmu931::read<float>(ptr + 12);
data.z = vmu931::read<float>(ptr + 16);
return data;
}
Sensor::Sensor(boost::asio::serial_port&& port) :
m_serial_port(std::move(port)), m_timer(m_serial_port.get_io_service()), m_filled(0)
{
m_serial_port.get_io_service().post([this]() {
m_command.empty() ? read() : write();
});
}
void Sensor::read_timeout()
{
m_timer.expires_from_now(boost::posix_time::milliseconds(15));
m_timer.async_wait([this](const boost::system::error_code& ec) {
if (!ec) {
if (m_command.empty()) {
read_timeout();
} else {
// cancel async read (proceeds with write)
m_serial_port.cancel();
}
}
});
}
void Sensor::read()
{
assert(m_buffer.size() >= m_filled);
uint8_t* bufptr = m_buffer.data() + m_filled;
std::size_t buflen = m_buffer.size() - m_filled;
read_timeout();
assert(buflen > 0);
m_serial_port.async_read_some(boost::asio::buffer(bufptr, buflen),
[this](const boost::system::error_code& ec, std::size_t bytes_transferred) {
m_filled += bytes_transferred;
if (!ec) {
while (parse()) {}
if (m_command.empty()) {
read();
} else {
m_timer.cancel();
write();
}
} else if (ec == boost::asio::error::operation_aborted) {
write();
}
});
}
void Sensor::write()
{
assert(!m_command.empty());
boost::asio::async_write(m_serial_port, boost::asio::buffer(m_command),
[this](const boost::system::error_code& ec, std::size_t bytes_transferred) {
if (!ec) {
assert(bytes_transferred == m_command.size());
m_command.clear();
read();
} else if (ec == boost::asio::error::operation_aborted) {
m_command.erase(0, bytes_transferred);
m_command.empty() ? read() : write();
}
});
}
bool Sensor::parse()
{
bool parsed = false;
const uint8_t* bufend = m_buffer.data() + m_filled;
const uint8_t* msg = nullptr;
for (const uint8_t* ptr = m_buffer.data(); ptr < bufend; ++ptr) {
if (*ptr == 0x01 || *ptr == 0x02) {
msg = ptr;
break;
}
}
if (msg) {
const std::size_t buflen = bufend - msg;
if (buflen < 2 || buflen < msg[1]) {
trim(msg);
} else {
const auto msglen = msg[1];
if (msg[0] == 0x01 && msg[msglen - 1] == 0x04) {
parse_data(msg[2], &msg[3], &msg[msglen - 1]);
trim(msg + msglen);
parsed = true;
} else if (msg[0] == 0x02 && msg[msglen - 1] == 0x03) {
if (m_string) {
std::string str;
str.assign(&msg[3], &msg[msglen - 1]);
m_string(str);
}
trim(msg + msglen);
parsed = true;
} else {
trim(msg + 1);
}
}
} else {
m_filled = 0;
}
return parsed;
}
void Sensor::trim(const uint8_t* ptr)
{
assert(ptr >= m_buffer.data());
assert(ptr <= m_buffer.data() + m_buffer.size());
const std::size_t len = m_buffer.data() + m_filled - ptr;
std::memmove(m_buffer.data(), ptr, len);
m_filled = len;
}
void Sensor::parse_data(char type, const uint8_t* begin, const uint8_t* end)
{
const std::size_t len = end - begin;
if (type == commands::Accelerometers && len == 16 && m_accel) {
m_accel(read_3d<Accelerometers>(begin));
} else if (type == commands::Gyroscopes && len == 16 && m_gyro) {
m_gyro(read_3d<Gyroscopes>(begin));
} else if (type == commands::Magnetometers && len == 16 && m_magneto) {
m_magneto(read_3d<Magnetometers>(begin));
} else if (type == commands::Quaternions && len == 20 && m_quat) {
m_quat(read_4d<Quaternions>(begin));
} else if (type == commands::EulerAngles && len == 16 && m_euler) {
m_euler(read_3d<EulerAngles>(begin));
} else if (type == commands::Heading && len == 8 && m_heading) {
vmu931::Heading heading;
heading.timestamp = vmu931::read<uint32_t>(begin);
heading.heading = vmu931::read<float>(begin + 4);
m_heading(heading);
} else if (type == commands::Status && len == 7) {
vmu931::Status status;
status.sensors_status = vmu931::read<uint8_t>(begin);
status.sensors_resolution = vmu931::read<uint8_t>(begin + 1);
status.low_output_rate_status = vmu931::read<uint8_t>(begin + 2);
status.data_currently_streaming = vmu931::read<uint32_t>(begin + 3);
if (m_pending_streams) {
toggle_streams(status);
} else if (m_status) {
m_status(status);
}
}
}
void Sensor::send_command(char command)
{
m_command.append("var");
m_command.push_back(command);
}
void Sensor::register_sink(AccelerometersSink handler)
{
m_accel = handler;
}
void Sensor::register_sink(GyroscopesSink handler)
{
m_gyro = handler;
}
void Sensor::register_sink(MagnetometersSink handler)
{
m_magneto = handler;
}
void Sensor::register_sink(EulerAnglesSink handler)
{
m_euler = handler;
}
void Sensor::register_sink(QuaternionsSink handler)
{
m_quat = handler;
}
void Sensor::register_sink(HeadingSink handler)
{
m_heading = handler;
}
void Sensor::register_sink(StatusSink handler)
{
m_status = handler;
}
void Sensor::register_sink(StringSink handler)
{
m_string = handler;
}
void Sensor::set_streams(const std::unordered_set<char>& streams)
{
m_pending_streams = streams;
send_command(commands::Status);
}
void Sensor::toggle_streams(const Status& status)
{
if (m_pending_streams) {
for (char possible_stream : commands::Data)
{
const bool want_stream = m_pending_streams->count(possible_stream);
const bool has_stream = status.is_streaming(possible_stream);
if (want_stream != has_stream) {
send_command(possible_stream);
}
}
m_pending_streams = boost::none;
}
}
} // namespace vmu931
| true |
ed6b215b46735431291cc5f39035f302abaac427
|
C++
|
KyleMylonakis/Cpp-examples-and-problem-solutions
|
/calculatorOfMeans/calculatorOfMeans/calculatorOfMeans.cpp
|
UTF-8
| 1,348 | 3.796875 | 4 |
[] |
no_license
|
// calculatorOfMeans.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using arithmeticFcn = int(*)(int, int);
int getNumber()
{
std::cout << "Please enter an integer \n";
int input{};
std::cin >> input;
std::cin.ignore(12345, '\n');
return input;
}
int add(int a, int b)
{
return a + b;
}
int subtract(int a, int b)
{
return a - b;
}
int multiply(int a, int b)
{
return a*b;
}
int divide(int a, int b)
{
return a / b;
}
char getOperation()
{
bool invalid_input = false;
do
{
std::cout << "Please enter a +, -, *, or / \n";
char input{};
std::cin >> input;
std::cin.ignore(12345, '\n');
switch (input)
{
case '+':
return '+';
case '-':
return '-';
case '*':
return '*';
case '/':
return '/';
default:
std::cout << "Invalid input \n";
invalid_input = true;
}
}
while (invalid_input == true);
}
arithmeticFcn getarithmeticFunction(char operation)
{
switch (operation)
{
case '+':
return add;
case'-':
return subtract;
case '*':
return multiply;
case '/':
return divide;
default:
break;
}
}
int main()
{
int firstNumber{ getNumber() };
int secondNumber{ getNumber() };
char operation{ getOperation() };
std::cout << getarithmeticFunction(operation)(firstNumber, secondNumber) << '\n';
return 0;
}
| true |
d5a9fecc9018345040597b5d792e317159af5b1d
|
C++
|
MrDoubleZ/LeetCode
|
/39.Combination Sum.cpp
|
UTF-8
| 1,025 | 2.75 | 3 |
[] |
no_license
|
class Solution {
public:
void back_tracking(vector<int>& candidates,
vector<int>& each_res,
vector<vector<int>>& res,
int target,
int pos,
int sum)
{
if (sum==target)
{
res.push_back(each_res);
return;
}
else if (sum>target) return;
for(int i=pos;i!=candidates.size();++i)
{
while(i!=candidates.size()-1&&candidates[i+1]==candidates[i])++i;
each_res.push_back(candidates[i]);
back_tracking(candidates,each_res,res,target,i,sum+candidates[i]);
each_res.pop_back();
}
return;
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target)
{
sort(candidates.begin(),candidates.end());
vector<vector<int>> res;
vector<int> each_res;
back_tracking(candidates,each_res,res,target,0,0);
return res;
}
};
| true |
ee8436c21a975ea726628189e68dd401907a1bde
|
C++
|
aliosmanulusoy/Probabilistic-Volumetric-3D-Reconstruction
|
/core/vil1/tests/vil_vil1_compare_access_timings.cxx
|
UTF-8
| 3,494 | 2.9375 | 3 |
[] |
no_license
|
//:
// \file
// \brief Tool to test performance of different methods of accessing image data.
// When run, tries a variety of different approaches and reports their timings.
// Useful to try it on different platforms to see how different optimisers perform.
// \author Tim Cootes
#include <iostream>
#include <ctime>
#include <vxl_config.h> // for imT
#include <vil/vil_image_view.h>
#include <vcl_compiler.h>
#include <mbl/mbl_stats_1d.h>
#include <vil1/vil1_memory_image_of.h>
#include <vil1/vil1_rgb.h>
#include <vil/vil_rgb.h>
const unsigned NI=256;
const unsigned NJ=256;
template <class T>
unsigned width(const vil_image_view<T> & im){return im.ni();}
template <class T>
unsigned width(const vil1_memory_image_of<T> & im){return im.width();}
template <class T>
unsigned height(const vil_image_view<T> & im){return im.nj();}
template <class T>
unsigned height(const vil1_memory_image_of<T> & im){return im.height();}
template <class imT>
double method1(imT& image, int n_loops)
{
typedef typename imT::pixel_type PT;
std::time_t t0=std::clock();
for (int n=0;n<n_loops;++n)
{
for (unsigned j=0;j<height(image);++j)
for (unsigned i=0;i<width(image);++i)
image(i,j) = PT(i+j);
}
std::time_t t1=std::clock();
return 1000000*(double(t1)-double(t0))/(n_loops*CLOCKS_PER_SEC);
}
template <class imT>
double method2(imT& image, int n_loops)
{
typedef typename imT::pixel_type PT;
std::time_t t0=std::clock();
for (int n=0;n<n_loops;++n)
{
unsigned ni=width(image),nj=height(image);
for (unsigned j=0;j<nj;++j)
for (unsigned i=0;i<ni;++i)
image(i,j) = PT(i+j);
}
std::time_t t1=std::clock();
return 1000000*(double(t1)-double(t0))/(n_loops*CLOCKS_PER_SEC);
}
template <class imT>
double method(int i, imT& image, int n_loops)
{
double t;
switch (i)
{
case 1 : t=method1(image,n_loops); break;
case 2 : t=method2(image,n_loops); break;
default: t=-1;
}
return t;
}
template <class imT>
void compute_stats(int i, imT& image, int n_loops)
{
mbl_stats_1d stats;
for (int j=0;j<10;++j) stats.obs(method(i,image,n_loops));
std::cout<<"Method "<<i<<") Mean: "<<int(stats.mean()+0.5)
<<"us +/-"<<int(0.5*(stats.max()-stats.min())+0.5)<<"us\n";
}
int main(int argc, char** argv)
{
vil1_memory_image_of<vxl_byte> byte_1image(NI,NJ);
vil1_memory_image_of<float> float_1image(NI,NJ);
vil1_memory_image_of<vil1_rgb<vxl_byte> > rgb_1image(NI,NJ);
vil_image_view<vxl_byte> byte_2image(NI,NJ);
vil_image_view<float> float_2image(NI,NJ);
vil_image_view<vil_rgb<vxl_byte> > rgb_2image(NI,NJ);
int n_loops = 100;
std::cout<<"Times to fill a "<<NI<<" x "<<NJ
<<" image of 1 plane (in microsecs) [Range= 0.5(max-min)]\n"
<<"vil1_memory_image_of Images of BYTE\n";
for (int i=1; i<=2; ++i)
compute_stats(i,byte_1image,n_loops);
std::cout<<"vil_image_view Images of BYTE\n";
for (int i=1; i<=2; ++i)
compute_stats(i,byte_2image,n_loops);
std::cout<<"vil1_memory_image_of Images of FLOAT\n";
for (int i=1; i<=2; ++i)
compute_stats(i,float_1image,n_loops);
std::cout<<"vil_image_view Images of FLOAT\n";
for (int i=1; i<=2; ++i)
compute_stats(i,float_2image,n_loops);
std::cout<<"vil1_memory_image_of Images of RGB<BYTE>\n";
for (int i=1; i<=2; ++i)
compute_stats(i,rgb_1image,n_loops);
std::cout<<"vil_image_view Images of RGB<BYTE>\n";
for (int i=1; i<=2; ++i)
compute_stats(i,rgb_2image,n_loops);
return 0;
}
| true |
684ba71ccf0b975d917c0fec6c1d1e0b15db6c1b
|
C++
|
koha13/All-code
|
/C-Thay_Son/Day doi xung.cpp
|
UTF-8
| 283 | 2.671875 | 3 |
[] |
no_license
|
#include<stdio.h>
void nhap(int a[], int &n){
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
}
int kt(int a[],int n){
for(int i=0;i<n;i++)
if(a[i]!=a[n-1-i]) return 0;
return 1;
}
main(){
int a[20],n;
nhap(a,n);
if(kt(a,n)) printf("Yes\n");
else printf("No");
}
| true |
9041e4e819a5b3fd6345757dc3fc83705a84ac9d
|
C++
|
apervushin/leetcode-cpp
|
/path_sum_iii.cpp
|
UTF-8
| 676 | 3.3125 | 3 |
[] |
no_license
|
#include "tree_node.cpp"
using namespace std;
class PathSumIII {
public:
int pathSum(TreeNode* root, int sum) {
if (root == nullptr) {
return 0;
}
return pathSum(root, sum, 0) + pathSum(root->left, sum) + pathSum(root->right, sum);
}
private:
int pathSum(TreeNode* root, int sum, int currentSum) {
if (root == nullptr) {
return 0;
}
int cnt = 0;
currentSum = currentSum + root->val;
if (currentSum == sum) {
cnt++;
}
cnt += pathSum(root->left, sum, currentSum);
cnt += pathSum(root->right, sum, currentSum);
return cnt;
}
};
| true |
ada46cb6ce363613d773679a06a4f4c21fc06455
|
C++
|
walkccc/LeetCode
|
/solutions/0294. Flip Game II/0294.cpp
|
UTF-8
| 652 | 3.078125 | 3 |
[
"MIT"
] |
permissive
|
class Solution {
public:
bool canWin(string currentState) {
const auto it = memo.find(currentState);
if (it == memo.cend())
return it->second;
// If any of currentState[i:i + 2] == "++" and your friend can't win after
// Changing currentState[i:i + 2] to "--" (or "-"), then you can win
for (int i = 0; i + 1 < currentState.length(); ++i)
if (currentState[i] == '+' && currentState[i + 1] == '+' &&
!canWin(currentState.substr(0, i) + '-' + currentState.substr(i + 2)))
return memo[currentState] = true;
return memo[currentState] = false;
}
private:
unordered_map<string, bool> memo;
};
| true |
827e33e333d71569c6ea595560a7455b744dcab6
|
C++
|
sneilk/cpp_coursera
|
/W3ModuleSort.cpp
|
UTF-8
| 583 | 3.203125 | 3 |
[] |
no_license
|
/*
* W3ModuleSort.cpp
*
* Created on: Apr 12, 2020
* Author: sneilk
*
* Task:
* https://www.coursera.org/learn/c-plus-plus-white/programming/D5IKE/sortirovka-tsielykh-chisiel-po-moduliu
*/
#include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>
using namespace std;
bool ModuleCompare(int i, int j){
return (abs(i) < abs(j));
}
void ModuleSort(){
vector<int> v;
int n, k;
cin >> n;
for (int i = 0; i < n; ++i){
cin >> k;
v.push_back(k);
}
sort(begin(v), end(v), ModuleCompare);
for (const auto& i : v){
cout << i << " ";
}
}
| true |
90751d1c407e6fdd4fb4bf9770d1bf73d49cc734
|
C++
|
junkkerrigan/algorithmics
|
/additional/geometry/839.cpp
|
UTF-8
| 1,280 | 3.109375 | 3 |
[] |
no_license
|
#include <iostream>
#include <algorithm>
using namespace std;
int xA, yA, xB, yB, xC, yC, xD, yD;
int sgn(int n)
{
return (n > 0) - (n < 0);
}
int RectanglesIntersects(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4)
{
if (sgn(x3 - x2) * sgn(x4 - x1) > 0) return 0;
if (sgn(y3 - y2) * sgn(y4 - y1) > 0) return 0;
return 1;
}
int intersect(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4)
{
int ABx, ABy, ACx, ACy, ADx, ADy;
int CAx, CAy, CBx, CBy, CDx, CDy;
int ACxAB, ADxAB, CAxCD, CBxCD;
if (!RectanglesIntersects(min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2), min(x3, x4), min(y3, y4), max(x3, x4), max(y3, y4))) return 0;
ACx = x3 - x1; ACy = y3 - y1;
ABx = x2 - x1; ABy = y2 - y1;
ADx = x4 - x1; ADy = y4 - y1;
CAx = x1 - x3; CAy = y1 - y3;
CBx = x2 - x3; CBy = y2 - y3;
CDx = x4 - x3; CDy = y4 - y3;
ACxAB = ACx * ABy - ACy * ABx;
ADxAB = ADx * ABy - ADy * ABx;
CAxCD = CAx * CDy - CAy * CDx;
CBxCD = CBx * CDy - CBy * CDx;
if (sgn(ACxAB) * sgn(ADxAB) > 0 || sgn(CAxCD) * sgn(CBxCD) > 0) return 0;
return 1;
}
int main() {
scanf("%d %d %d %d", &xA, &yA, &xB, &yB);
scanf("%d %d %d %d", &xC, &yC, &xD, &yD);
if (intersect(xA, yA, xB, yB, xC, yC, xD, yD)) printf("Yes\n");
else printf("No\n");
return 0;
}
| true |
39d85441acbc9f179cb229b33e4132d1ec3d7c7a
|
C++
|
TomLott/cpp
|
/day04/ex02/main.cpp
|
UTF-8
| 1,170 | 2.890625 | 3 |
[] |
no_license
|
#include "AssaultTerminator.hpp"
#include "ISpaceMarine.hpp"
#include "ISquad.hpp"
#include "Squad.hpp"
#include "TacticalMarine.hpp"
int main() {
ISpaceMarine *bob = new TacticalMarine;
ISpaceMarine *jim = new AssaultTerminator;
ISquad *vlc = new Squad;
vlc->push(bob);
vlc->push(jim);
for (int i = 0; i < vlc->getCount(); ++i) {
ISpaceMarine *cur = vlc->getUnit(i);
cur->battleCry();
cur->rangedAttack();
cur->meleeAttack();
}
delete vlc;
std::cout << "=+============+=" << std::endl;
Squad squad;
squad.push(new AssaultTerminator());
squad.push(new TacticalMarine());
squad.push(new AssaultTerminator());
squad.push(new TacticalMarine());
for (int i = 0; i < 4; i++) {
std::cout << "+++++++" << std::endl;
squad.getUnit(i)->battleCry();
squad.getUnit(i)->rangedAttack();
squad.getUnit(i)->meleeAttack();
}
std::cout << "================" << std::endl;
std::cout << "================" << std::endl;
Squad squad2;
squad2 = squad;
for (int i = 0; i < 4; i++){
std::cout << "+++++++" << std::endl;
squad2.getUnit(i)->battleCry();
squad2.getUnit(i)->rangedAttack();
squad2.getUnit(i)->meleeAttack();
}
return (0);
}
| true |
6ed113b5acbdb40b6f49306bb1bcf269b39fd53c
|
C++
|
Tralfazz/Magshitrivia-server
|
/Helper.cpp
|
UTF-8
| 1,737 | 3.25 | 3 |
[] |
no_license
|
#include "Helper.h"
#include <string>
#include <iomanip>
#include <sstream>
// recieves the type code of the message from socket (first byte)
// and returns the code. if no message found in the socket returns 0 (which means the client disconnected)
int Helper::getMessageTypeCode(SOCKET sc)
{
char* s = getPartFromSocket(sc, 3);
std::string msg(s);
if (msg == "")
return 0;
int res = std::atoi(s);
delete s;
return res;
}
// send data to socket
// this is private function
void Helper::sendData(SOCKET sc, std::string message)
{
const char* data = message.c_str();
if (send(sc, data, message.size(), 0) == INVALID_SOCKET)
{
throw std::exception("Error while sending message to client");
}
}
int Helper::getIntPartFromSocket(SOCKET sc, int bytesNum)
{
char* s= getPartFromSocket(sc, bytesNum, 0);
return atoi(s);
}
std::string Helper::getStringPartFromSocket(SOCKET sc, int bytesNum)
{
char* s = getPartFromSocket(sc, bytesNum, 0);
std::string res(s);
return res;
}
// recieve data from socket according byteSize
// this is private function
char* Helper::getPartFromSocket(SOCKET sc, int bytesNum)
{
return getPartFromSocket(sc, bytesNum, 0);
}
char* Helper::getPartFromSocket(SOCKET sc, int bytesNum, int flags)
{
if (bytesNum == 0)
{
return nullptr;
}
char* data = new char[bytesNum + 1];
int res = recv(sc, data, bytesNum, flags);
if (res == INVALID_SOCKET)
{
std::string s = "Error while recieving from socket: ";
s += std::to_string(sc);
throw std::exception(s.c_str());
}
data[bytesNum] = 0;
return data;
}
std::string Helper::getPaddedNumber(int num, int digits)
{
std::ostringstream ostr;
ostr << std::setw(digits) << std::setfill('0') << num;
return ostr.str();
}
| true |
0926da1f5101a6e84d6ca2c8720843670397c7b1
|
C++
|
sanchitgoel10/365_of_code
|
/LeetCode 30 Day June/Is Subsequence.cpp
|
UTF-8
| 286 | 2.65625 | 3 |
[] |
no_license
|
class Solution {
public:
bool isSubsequence(string s, string t) {
int n=s.size();
int c=0;
for(auto i:t){
if(c==n)return 1;
if(i==s[c]){
c++;
}
}
if(c==n)return 1;
return 0;
}
};
| true |
08fb6c3e3b9114839ba06b6fa0b85f626db2af48
|
C++
|
JoanCoCo/MezzoReader
|
/source/MezzoUtilities.cpp
|
UTF-8
| 31,056 | 2.78125 | 3 |
[] |
no_license
|
/**
* Utilities.cpp
*
* SMII 2020/2021
* Joan Colom Colom
*
* Implementation of the class described in Utilities.h.
*/
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
#include <list>
#include "../include/MezzoUtilities.h"
#include "../include/Note.h"
#include "../include/Staff.h"
#include "../include/Alphabet.h"
#include "../include/Symbol.h"
#include <math.h>
#include <iomanip>
using namespace std;
using namespace cv;
static const int MAX_DELAY = 1000;
int speed = MAX_DELAY - 1;
list<int> MezzoUtilities::find_horizontal_lines ( Mat image, float percentage, bool verbose ) {
Mat horizontal = image.clone();
int horizontal_size = horizontal.cols / 30;
// Create structure element for extracting horizontal lines through morphology operations
Mat horizontalStructure = getStructuringElement(MORPH_RECT, Size(horizontal_size, 1));
// Apply morphology operations
erode(horizontal, horizontal, horizontalStructure, Point(-1, -1));
dilate(horizontal, horizontal, horizontalStructure, Point(-1, -1));
// Show extracted horizontal lines
if(verbose) show_wait_destroy("horizontal", horizontal);
//! [horiz]
list <int> lines;
// -----------------------------------------------------------------
for (int i = 0; i < horizontal.rows; i++) {
int black = 0;
for(int j = 0; j < horizontal.cols; j++) {
black += (int)(horizontal.at<uchar>(i,j)) / 255;
}
//cout << black << endl;
if((float)black > (float)horizontal.cols * percentage / 100.0f) {
//cout << i << endl;
lines.push_back(i);
}
}
// -----------------------------------------------------------------
return lines;
}
list<int> MezzoUtilities::filter_horizontal_lines ( list<int> lines) {
list <int> result;
int previous = 0;
int j = 0;
int aux = 0;
for(std::list<int>::iterator i = lines.begin(); i != lines.end(); ++i) {
previous += *i;
aux++;
if(std::next(i,1) == lines.end() || (*std::next(i,1)) - (*i) >= 3) {
result.push_back(previous / aux);
j++;
previous = 0;
aux = 0;
}
}
return result;
}
list<Staff> MezzoUtilities::extract_all_staffs ( Mat image , bool adaptive, int expectedLines, float precision ) {
list<Staff> staffs;
list<int> lines;
float percent = 0.0f;
if(adaptive) {
percent = 100.0f;
} else {
percent = 70.0f;
}
int originalNumberOfLines = 1;
float averageLineWidth = 1.0f;
int fastSteps = 2;
bool endAdaptiveBehaviour = false;
do {
if(adaptive) {
switch (fastSteps)
{
case 2:
percent /= 2.0f;
break;
case 1:
percent -= 1.0f;
break;
default:
percent -= pow(10.0f, -1.0f * precision);
break;
}
cout << setw(15) << '\r' << flush;
cout << percent << "%" << '\r' << flush;
}
lines.clear();
lines = MezzoUtilities::find_horizontal_lines(image, percent);
originalNumberOfLines = lines.size();
lines = MezzoUtilities::filter_horizontal_lines(lines);
averageLineWidth = (float) originalNumberOfLines / (float) lines.size();
endAdaptiveBehaviour = lines.size() == expectedLines || percent < 1.0f;
if(adaptive && !endAdaptiveBehaviour) {
if(lines.size() > expectedLines && fastSteps > 0) {
if(fastSteps == 2) {
percent *= 2.0f;
} else if(fastSteps == 1) {
percent += 1.0f;
}
fastSteps--;
} else if(fastSteps == 0) {
endAdaptiveBehaviour = lines.size() >= expectedLines;
}
}
} while(adaptive && !endAdaptiveBehaviour);
if(adaptive) {
cout << endl;
(lines.size() != expectedLines) ?
cout << "Adaptative process failed with " << percent << "%." << endl :
cout << "Adaptative process succed with " << percent << "%." << endl;
}
if(lines.size() % 5 == 0) {
int numOfStaffs = lines.size() % 5;
int staffLines [5];
int i = 0;
int c = 0;
for(std::list<int>::iterator j = lines.begin(); j != lines.end(); ++j) {
staffLines[i] = (int) *j;
i++;
if(i == 5) {
if(numOfStaffs > 1) {
if(c == 0) {
Staff stf = Staff(staffLines, 0, (*std::next(j, 1) - staffLines[4])/2);
stf.set_line_width(averageLineWidth);
staffs.push_back(stf);
} else if (c == numOfStaffs - 1) {
Staff stf = Staff(staffLines, (staffLines[0] - *std::prev(j, 5))/2, image.rows - 1);
stf.set_line_width(averageLineWidth);
staffs.push_back(stf);
} else {
Staff stf = Staff(staffLines, (staffLines[0] - *std::prev(j, 5))/2, (*std::next(j, 1) - staffLines[4])/2);
stf.set_line_width(averageLineWidth);
staffs.push_back(stf);
}
} else {
Staff stf = Staff(staffLines, 0, image.rows - 1);
stf.set_line_width(averageLineWidth);
staffs.push_back(stf);
}
i = 0;
c++;
}
}
} else {
cout << "Error when detecting the staffs, wrong number of lines detected: " << lines.size() << endl;
}
return staffs;
}
float MezzoUtilities::get_note_tone(int y, Staff staff) {
float baseLine = (float) staff.get_line(4);
float spaceBetweenLines = (float) staff.get_space_between_lines();
float remapY = (baseLine - (float) y);
float unit = spaceBetweenLines / 2.0f;
return remapY / unit - (signbit(remapY) * -1) * 0.1f;
}
list<Note> MezzoUtilities::extract_notes(Mat image, Staff staff, bool verbose) {
list<Note> result;
/*int baseLine = staff.get_line(4);
int spaceBetweenLines = staff.get_space_between_lines();
if(verbose) cout << "Base line: " << baseLine << endl;
Mat ellip;
adaptiveThreshold(~image, ellip, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 15, -2);
Mat squareStructure = getStructuringElement(MORPH_ELLIPSE, Size(spaceBetweenLines - 1, spaceBetweenLines - 1));
erode(ellip, ellip, squareStructure, Point(-1, -1));
dilate(ellip, ellip, squareStructure, Point(-1, -1));
bool inNote = false;
bool foundNewNote = false;
int left = 0;
int right = 0;
int up = ellip.rows;
int down = 0;
bool someWhite = false;
for(int i = 0; i < ellip.cols; i++) {
for(int j = std::min(ellip.rows - 1, staff.get_lower_limit()); j >= std::max(0, staff.get_upper_limit()); j--) {
int v = (int) ellip.at<uchar>(j,i);
if(v == 255 && !foundNewNote) {
foundNewNote = true;
left = i;
down = std::max(down, j);
inNote = true;
someWhite = true;
} else if (v == 255 && foundNewNote && !inNote){
inNote = true;
someWhite = true;
down = std::max(down, j);
} else if(inNote && v == 0) {
up = std::min(up, j + 1);
inNote = false;
}
}
if(!someWhite && foundNewNote) {
foundNewNote = false;
right = i - 1;
int x = ((right - left) / 2) + left;
int y = ((down - up) / 2) + up;
int noteClass = get_note_tone(y, staff);
Note n;
n.x = x;
n.y = y;
n.tone = noteClass;
result.push_back(n);
if(verbose) cout << "New note was found: (" << x << ", " << y << ") --> c: " << noteClass << endl;
right = 0;
left = 0;
up = ellip.rows;
down = 0;
}
inNote = false;
someWhite = false;
}*/
Mat justStaffImage = MezzoUtilities::crop_staff_from_image(image, staff);
for(int i = 0; i < NUMBER_OF_SYMBOLS; i++) {
if(verbose) cout << "Showing " << SYMBOLS[i].get_source_template() << " positive matches." << endl ;
bool thisIsCorchera, nextIsCorchera = false;
Symbol symbol = SYMBOLS[i];
list<Point> wp = MezzoUtilities::find_matches(justStaffImage,
symbol.get_source_template(), symbol.get_threshold(),
symbol.get_appropiate_pixel_scale(staff.get_space_between_lines()), verbose);
for(std::list<Point>::iterator j = wp.begin(); j != wp.end(); j++) {
int y = (*j).y + staff.get_upper_limit();
Note w = Note((*j).x, y, (int) roundf(get_note_tone(y, staff)), 0);
if(symbol.get_id() == CROTCHET_NOTE_ID) {
Point c1, c2;
c1 = Point(w.x, 0);
if(next(j, 1) == wp.end()) {
c2 = Point(std::min(w.x + staff.get_space_between_lines() * 5, justStaffImage.cols - 1), justStaffImage.rows - 1);
} else {
//c2 = Point2d((*next(j, 1)).x, justStaffImage.rows - 1);
c2 = Point(std::min(w.x + staff.get_space_between_lines() * 5, (*next(j,1)).x), justStaffImage.rows - 1);
}
Rect a(c1, c2);
//cout << a << endl;
Mat noteArea = justStaffImage(a);
MezzoUtilities::show_wait_destroy("Note area", noteArea);
Mat binaryArea;
adaptiveThreshold(noteArea, binaryArea, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 15, -2);
Mat blockStructure = getStructuringElement(MORPH_RECT, Size(binaryArea.cols, staff.get_space_between_lines() / 2 - 1));
// Apply morphology operations
erode(binaryArea, binaryArea, blockStructure, Point(-1, -1));
dilate(binaryArea, binaryArea, blockStructure, Point(-1, -1));
MezzoUtilities::show_wait_destroy("Lines in note's area", binaryArea);
bool toBreak = false;
thisIsCorchera = false;
int whiteInLine = 0;
for(int g = 0; g < binaryArea.rows && !toBreak; g++) {
for(int h = 0; h < binaryArea.cols && !toBreak; h++) {
whiteInLine += (int) binaryArea.at<uchar>(g, h) / 255;
}
if(((float) whiteInLine) >= 0.75f * ((float) binaryArea.cols)) {
nextIsCorchera = true;
thisIsCorchera = true;
toBreak = true;
whiteInLine = 0;
}
}
if(thisIsCorchera) {
//cout << "A corchera has been found." << endl;
w.duration = 0.25;
} else if(nextIsCorchera) {
//cout << "A corchera has been found." << endl;
nextIsCorchera = false;
w.duration = 0.25;
} else {
w.duration = 1.0;
}
} else if(symbol.get_id() == MINIM_NOTE_ID) {
w.duration = 2.0;
} else if(symbol.get_id() == SEMIBREVE_NOTE_ID) {
w.duration = 4.0;
}
result.push_back(w);
}
if(verbose) {
Mat whiteResults;
cvtColor(justStaffImage, whiteResults, COLOR_GRAY2BGR);
for(std::list<Point>::iterator pw = wp.begin(); pw != wp.end(); pw++) {
cv::circle(whiteResults, *(pw), 10, Scalar(0,0,255), 2);
}
MezzoUtilities::show_wait_destroy("Found positive symbols", whiteResults);
}
}
return result;
}
void MezzoUtilities::show_wait_destroy(const char* winname, cv::Mat img) {
namedWindow(winname, WINDOW_AUTOSIZE);
imshow(winname, img);
#if __APPLE__
moveWindow(winname, 500, 0);
#else
moveWindow(winname, 0, 0);
#endif
waitKey(0);
destroyWindow(winname);
}
void MezzoUtilities::show_wait_time_destroy(const char* winname, cv::Mat img) {
namedWindow(winname, WINDOW_AUTOSIZE);
imshow(winname, img);
#if __APPLE__
moveWindow(winname, 500, 0);
waitKey(1);
#else
moveWindow(winname, 0, 0);
waitKey(10);
#endif
destroyWindow(winname);
}
Mat MezzoUtilities::erase_horizontal_lines(Mat image, int size) {
Mat result;
// Create structure element for extracting vertical lines through morphology operations
Mat verticalStructure = getStructuringElement(MORPH_RECT, Size(1, size));
// Apply morphology operations
erode(image, result, verticalStructure, Point(-1, -1));
dilate(result, result, verticalStructure, Point(-1, -1));
return result;
}
bool MezzoUtilities::compare_points(Point a, Point b) {
return (a.x) < (b.x);
}
list<Point> MezzoUtilities::find_matches(Mat image, string templ, double thresh, int h, bool verbose) {
Mat temp = imread(templ, IMREAD_COLOR);
cvtColor(temp, temp, COLOR_BGR2GRAY);
int margin = 2;
if(h > 0) {
resize(temp, temp, Size(temp.cols * (h + margin) / temp.rows, (h + margin)));
}
if(verbose) {
cout << "Template size" << Size(temp.cols, temp.rows) << endl;
MezzoUtilities::show_wait_destroy("Template", temp);
}
Mat results;
matchTemplate(image, temp, results, TM_CCORR_NORMED);
if(verbose) MezzoUtilities::show_wait_destroy("Matching", results);
Mat bw;
threshold(results, bw, thresh, 255, THRESH_BINARY);
if(verbose) MezzoUtilities::show_wait_destroy("Matching", bw);
double minVal; double maxVal; Point minLoc; Point maxLoc;
minMaxLoc(bw, &minVal, &maxVal, &minLoc, &maxLoc, Mat() );
list<Point> resultl;
while(maxVal > 0) {
if(verbose) cout << maxLoc << " -> " << maxVal << endl;
resultl.push_back(maxLoc);
bw.at<int>(maxLoc) = 0;
minMaxLoc(bw, &minVal, &maxVal, &minLoc, &maxLoc, Mat() );
}
if(resultl.size() > 0) {
list<Point> filterdResult;
resultl.sort(compare_points);
Point currentPoint = *(resultl.begin());
int aux = 1;
int dispy = temp.rows / 2;
int dispx = temp.cols / 2;
for(std::list<Point>::iterator i = std::next(resultl.begin(), 1); i != resultl.end(); i++) {
if((*std::prev(i, 1)).x + 3 > (*i).x) {
currentPoint.x = currentPoint.x + (*i).x;
currentPoint.y = currentPoint.y + (*i).y;
aux++;
} else {
currentPoint.x = (currentPoint.x / aux) + dispx;
currentPoint.y = (currentPoint.y / aux) + dispy;
filterdResult.push_back(currentPoint);
currentPoint = *i;
aux = 1;
}
}
currentPoint.x = (currentPoint.x / aux) + dispx;
currentPoint.y = (currentPoint.y / aux) + dispy;
filterdResult.push_back(currentPoint);
return filterdResult;
} else {
return resultl;
}
}
Mat MezzoUtilities::crop_staff_from_image(Mat image, Staff staff, bool markIt, Mat *outMark) {
Rect staffRect(Point(0, staff.get_upper_limit()), Point(image.cols, staff.get_lower_limit()));
Mat staffImage = image(staffRect);
if(markIt) cv::rectangle(*outMark, staffRect, Scalar(255,160,23), 2);
return staffImage;
}
Vec3i MezzoUtilities::find_most_suitable_template_from(Symbol *symbols, int len, Mat image, int h) {
double maxV = 0;
int maxI = -1, x = -1, y = -1;
for(int i = 0; i < len; i++) {
Symbol symbol = symbols[i];
Mat temp = imread(symbol.get_source_template(), IMREAD_COLOR);
cvtColor(temp, temp, COLOR_BGR2GRAY);
int margin = 2;
int hr = symbol.get_appropiate_pixel_scale(h);
resize(temp, temp, Size(temp.cols * (hr + margin) / temp.rows, (hr + margin))/*, 0.0, 0.0, INTER_AREA*/);
if(temp.rows <= image.rows && temp.cols <= image.cols) {
Mat results;
matchTemplate(image, temp, results, TM_CCORR_NORMED);
double minVal; double maxVal; Point minLoc; Point maxLoc;
minMaxLoc(results, &minVal, &maxVal, &minLoc, &maxLoc, Mat() );
if(maxV < maxVal && maxVal >= symbol.get_threshold()) {
maxV = maxVal;
maxI = i;
x = maxLoc.x + temp.cols / 2;
y = maxLoc.y + temp.rows / 2;
}
}
}
return Vec3i(maxI, x, y);
}
Vec3i MezzoUtilities::find_most_suitable_template(Mat image, int h) {
return find_most_suitable_template_from(SYMBOLS, NUMBER_OF_SYMBOLS, image, h);
}
void MezzoUtilities::slider_changed(int pos, void *userdata) {
speed = pos;
}
list<Note> MezzoUtilities::extract_notes_v2(Mat image, Staff staff, bool visual) {
list<Note> result;
Mat staffImage = crop_staff_from_image(image, staff);
Point start;
Point end;
start = Point(0, 0);
end = Point(1, staffImage.rows - 1);
bool sliderIsCreated = false;
int barAreaHeight = (int)(roundf(0.8005 * logf(staff.get_space_between_lines()) + 1.6667f));
float lineSpaceRatio = staff.get_line_width() / (float) staff.get_space_between_lines();
//cout << "Line width: " << staff.get_line_width() << endl;
//cout << "Bar area height: " << barAreaHeight << endl;
//cout << "Space between lines: " << staff.get_space_between_lines() << endl;
//cout << "Ratio: " << lineSpaceRatio << endl;
while(end.x < staffImage.cols) {
if(visual) {
Mat gOut = image.clone();
cvtColor(gOut, gOut, COLOR_GRAY2BGR);
cv::rectangle(gOut,
Rect(Point(start.x, staff.get_upper_limit()), Point(end.x, staff.get_lower_limit())),
Scalar(0,213,143), 2);
if(result.size() > 0) {
Note lastN = result.back();
MezzoUtilities::draw_note(&gOut, lastN, staff, true);
}
if(!sliderIsCreated) {
createTrackbar("Speed", "Reading...", &speed, MAX_DELAY - 1, slider_changed);
sliderIsCreated = true;
}
imshow("Reading...", gOut);
waitKey(MAX_DELAY - speed);
}
Mat cell = staffImage(Rect(start, end));
int templateFound, cellX, cellY;
Vec3i findings = MezzoUtilities::find_most_suitable_template(cell, staff.get_space_between_lines());
templateFound = findings[0];
cellX = findings[1];
cellY = findings[2];
if(templateFound >= 0) {
if(SYMBOLS[templateFound].get_id() >= 0) {
int y = cellY + staff.get_upper_limit();
int x = cellX + start.x;
//cout << "Note tone: " << get_note_tone(y, staff) << endl;
Note n = Note(x, y, (int) roundl(get_note_tone(y, staff)), SYMBOLS[templateFound].get_id(), SYMBOLS[templateFound].is_silence());
bool isFalsePositive = false;
if(SYMBOLS[templateFound].get_id() == CROTCHET_NOTE_ID) {
// First we check if this crotchet candidate is really an isolated quaver.
int avSp = staff.get_space_between_lines();
Rect interestRect = Rect(Point(std::max(start.x, n.x - 2 * avSp), start.y), Point(std::min(staffImage.cols - 1, n.x + 2 * avSp), end.y));
Mat interestZone = staffImage(interestRect);
//MezzoUtilities::show_wait_destroy("h", interestZone);
Symbol symSet[] = { QUAVER_TAIL_DOWN, CLAVE_DE_SOL };
Vec3i qtail = find_most_suitable_template_from(symSet, 1, interestZone, staff.get_space_between_lines());
float blackAmount = 0;
switch (qtail[0])
{
case 1:
cout << "Clave de Sol" << endl;
isFalsePositive = true;
break;
case QUAVER_TAIL_DOWN_ID:
n.set_note_duration(QUAVER_NOTE_ID);
break;
default:
Mat binaryCell;
adaptiveThreshold(~interestZone, binaryCell, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 15, -2);
if(lineSpaceRatio > 0.2f) {
for(int i = 0; i < 5; i++) {
cv::line(binaryCell, Point(0, staff.get_line(i) - staff.get_upper_limit()),
Point(binaryCell.cols - 1, staff.get_line(i) - staff.get_upper_limit()),
Scalar(1, 1, 1), std::max((int) 1, 0));
}
}
Mat hStructure = getStructuringElement(MORPH_RECT, Size(binaryCell.cols / 2, barAreaHeight /*staff.get_space_between_lines() / 2 - 1*/));
//MezzoUtilities::show_wait_destroy("b", binaryCell);
erode(binaryCell, binaryCell, hStructure, Point(-1, -1));
dilate(binaryCell, binaryCell, hStructure, Point(-1, -1));
//MezzoUtilities::show_wait_destroy("b", binaryCell);
bool toBreak = false;
int whiteInLine = 0;
for(int g = 0; g < binaryCell.rows && !toBreak; g++) {
for(int h = 0; h < binaryCell.cols && !toBreak; h++) {
whiteInLine += (int) binaryCell.at<uchar>(g, h) / 255;
}
if(((float) whiteInLine) >= 0.2f * ((float) binaryCell.cols)) {
toBreak = true;
n.set_note_duration(QUAVER_NOTE_ID);
}
}
if(toBreak) break;
Rect newRect = Rect(Point(n.x, std::max(0, cellY - 4 * avSp)), Point(std::min(staffImage.cols - 1, n.x + 2 * avSp), cellY));
Mat newInterestZone = staffImage(newRect);
Symbol symSet2[] = { QUAVER_TAIL_UP };
Vec3i rqTail = find_most_suitable_template_from(symSet2, 1, newInterestZone, staff.get_space_between_lines());
if(rqTail[0] == QUAVER_TAIL_UP_ID) {
n.set_note_duration(QUAVER_NOTE_ID);
}
break;
}
}
if(!isFalsePositive) result.push_back(n);
}
start.x = end.x;
}
end.x += 5;
cout << (int)(((float) end.x) * 100.0f / ((float) staffImage.cols)) << "%" << '\r' << flush;
}
cout << endl;
return result;
}
void MezzoUtilities::draw_note(Mat* image, Note note, Staff staff, bool showDescription) {
Point top(note.x - staff.get_space_between_lines(), note.y - staff.get_space_between_lines());
Point low(note.x + staff.get_space_between_lines(), note.y + staff.get_space_between_lines());
if(showDescription) {
cv::putText(*image, note.get_note_name(), top + Point(0, 5 * staff.get_space_between_lines()), FONT_HERSHEY_PLAIN, 2, Scalar(103,113,123), 2);
//cv::putText(*image, to_string(note.tone), top + Point(0, 5 * staff.get_space_between_lines()), FONT_HERSHEY_PLAIN, 1, Scalar(86,113,123), 2);
}
if(note.isSilence) {
cv::rectangle(*image, top, low, Scalar(86,113,193), 2);
} else if(note.duration < 1) {
cv::rectangle(*image, top, low, Scalar(106,73,123), 2);
} else {
cv::rectangle(*image, top, low, Scalar(123,121,21), 2);
}
(*image).at<Vec3b>(Point(note.x, note.y)) = Vec3b(0, 0, 255);
}
Mat MezzoUtilities::encode_pictoform(list<Note> notes) {
int size = (int) roundf(sqrtf(notes.size()));
if(size * size < notes.size()) { size++; }
Mat pictoform(size * 3 + size, size * 3 + 1, CV_8UC3, cv::Scalar(0, 0, 0));
for(int i = 0; i < pictoform.rows; i++) {
pictoform.at<Vec3b>(i, 0)[0] = 0;
pictoform.at<Vec3b>(i, 0)[1] = 0;
pictoform.at<Vec3b>(i, 0)[2] = 255;
}
for(int i = 0; i < pictoform.rows; i+=4) {
for(int j = 0; j < pictoform.cols; j++) {
pictoform.at<Vec3b>(i, j)[0] = 0;
pictoform.at<Vec3b>(i, j)[1] = 255;
pictoform.at<Vec3b>(i, j)[2] = 255;
}
}
pictoform.at<Vec3b>(0, 0)[0] = 255;
pictoform.at<Vec3b>(0, 0)[1] = 255;
pictoform.at<Vec3b>(0, 0)[2] = 255;
int i = 1;
int j = 1;
for(std::list<Note>::iterator n = notes.begin(); n != notes.end(); n++) {
//cout << "Note: tone=" << (*n).tone << " id=" << (*n).symbolId << " silence=" << (*n).isSilence << endl;
int tone = (*n).tone;
int id = (*n).symbolId;
// -------------- Tone encoding ----------------- //
pictoform.at<Vec3b>(i, j)[2] = signbit(tone) ? 255 : 0;
tone = abs(tone);
pictoform.at<Vec3b>(i, j+2)[0] = (tone % 2) * 255;
tone /= 2;
pictoform.at<Vec3b>(i, j+2)[1] = (tone % 2) * 255;
tone /= 2;
pictoform.at<Vec3b>(i, j+2)[2] = (tone % 2) * 255;
tone /= 2;
pictoform.at<Vec3b>(i, j+1)[0] = (tone % 2) * 255;
tone /= 2;
pictoform.at<Vec3b>(i, j+1)[1] = (tone % 2) * 255;
tone /= 2;
pictoform.at<Vec3b>(i, j+1)[2] = (tone % 2) * 255;
tone /= 2;
pictoform.at<Vec3b>(i, j)[0] = (tone % 2) * 255;
tone /= 2;
pictoform.at<Vec3b>(i, j)[1] = (tone % 2) * 255;
tone /= 2;
// ---------------------------------------------- //
// --------------- ID encoding ------------------ //
pictoform.at<Vec3b>(i+2, j+2)[0] = (id % 2) * 255;
id /= 2;
pictoform.at<Vec3b>(i+2, j+2)[1] = (id % 2) * 255;
id /= 2;
pictoform.at<Vec3b>(i+2, j+2)[2] = (id % 2) * 255;
id /= 2;
pictoform.at<Vec3b>(i+2, j+1)[0] = (id % 2) * 255;
id /= 2;
pictoform.at<Vec3b>(i+2, j+1)[1] = (id % 2) * 255;
id /= 2;
pictoform.at<Vec3b>(i+2, j+1)[2] = (id % 2) * 255;
id /= 2;
pictoform.at<Vec3b>(i+2, j)[0] = (id % 2) * 255;
id /= 2;
pictoform.at<Vec3b>(i+2, j)[1] = (id % 2) * 255;
id /= 2;
pictoform.at<Vec3b>(i+2, j)[2] = (id % 2) * 255;
id /= 2;
// ---------------------------------------------- //
// Silence or note encoding
if((*n).isSilence) {
pictoform.at<Vec3b>(i+1, j)[0] = 255;
pictoform.at<Vec3b>(i+1, j)[1] = 255;
pictoform.at<Vec3b>(i+1, j)[2] = 255;
} else {
pictoform.at<Vec3b>(i+1, j)[0] = 0;
pictoform.at<Vec3b>(i+1, j)[1] = 0;
pictoform.at<Vec3b>(i+1, j)[2] = 0;
}
// Valid note
pictoform.at<Vec3b>(i+1, j+1)[0] = 255;
pictoform.at<Vec3b>(i+1, j+1)[1] = 255;
pictoform.at<Vec3b>(i+1, j+1)[2] = 255;
j += 3;
if(j >= pictoform.cols) { j = 1; i += 4; }
}
return pictoform;
}
list<Note> MezzoUtilities::decode_pictoform(Mat image) {
list<Note> notes;
int tone = 0;
int id = 0;
bool isSilence = false;
int j = 0;
if(image.at<Vec3b>(0, 0)[0] == 255 && image.at<Vec3b>(0, 0)[1] == 255 && image.at<Vec3b>(0, 0)[1] == 255) {
for(int i = 0; i < image.rows; i++) {
if( image.at<Vec3b>(i, 0)[1] == 255 ) {
j = 1;
//cout << "Reading new pictoform row." << endl;
} else {
for(; j < image.cols; j+=3) {
//cout << "(" << i << ", " << j << ")" << endl;
if((image.at<Vec3b>(i+1, j+1)[0] == 255) &&
(image.at<Vec3b>(i+1, j+1)[1] == 255) &&
(image.at<Vec3b>(i+1, j+1)[2] == 255)) {
//cout << "Decoding new note." << endl;
// -------------- Tone decoding ----------------- //
if(image.at<Vec3b>(i, j+2)[0] == 255) tone += (int) pow(2, 0);
if(image.at<Vec3b>(i, j+2)[1] == 255) tone += (int) pow(2, 1);
if(image.at<Vec3b>(i, j+2)[2] == 255) tone += (int) pow(2, 2);
if(image.at<Vec3b>(i, j+1)[0] == 255) tone += (int) pow(2, 3);
if(image.at<Vec3b>(i, j+1)[1] == 255) tone += (int) pow(2, 4);
if(image.at<Vec3b>(i, j+1)[2] == 255) tone += (int) pow(2, 5);
if(image.at<Vec3b>(i, j)[0] == 255) tone += (int) pow(2, 6);
if(image.at<Vec3b>(i, j)[1] == 255) tone += (int) pow(2, 7);
if(image.at<Vec3b>(i, j)[2] == 255) tone *= -1;
// ---------------------------------------------- //
// --------------- ID decoding ------------------ //
if(image.at<Vec3b>(i+2, j+2)[0] == 255) id += (int) pow(2, 0);
if(image.at<Vec3b>(i+2, j+2)[1] == 255) id += (int) pow(2, 1);
if(image.at<Vec3b>(i+2, j+2)[2] == 255) id += (int) pow(2, 2);
if(image.at<Vec3b>(i+2, j+1)[0] == 255) id += (int) pow(2, 3);
if(image.at<Vec3b>(i+2, j+1)[1] == 255) id += (int) pow(2, 4);
if(image.at<Vec3b>(i+2, j+1)[2] == 255) id += (int) pow(2, 5);
if(image.at<Vec3b>(i+2, j)[0] == 255) id += (int) pow(2, 6);
if(image.at<Vec3b>(i+2, j)[1] == 255) id += (int) pow(2, 7);
if(image.at<Vec3b>(i+2, j)[2] == 255) id += (int) pow(2, 8);
// ---------------------------------------------- //
// Silence or note decoding
isSilence = (image.at<Vec3b>(i+1, j)[0] == 255) &&
(image.at<Vec3b>(i+1, j)[1] == 255) &&
(image.at<Vec3b>(i+1, j)[2] == 255);
Note decodedNote = Note(0, 0, tone, id, isSilence);
notes.push_back(decodedNote);
tone = 0;
id = 0;
}
}
i += 2;
}
}
}
return notes;
}
| true |
49a5521a9ccfa7706b79243a7915b5e9454c06a2
|
C++
|
imohdalam/HacktoberFest2k21
|
/perfectNumber.cpp
|
UTF-8
| 285 | 3.171875 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, sum=0;
cout<<"Enter Number: ";
cin>>n;
for(int i=1; i<=n; i++)
{
if(n%i==0)
sum+=i;
}
if(sum==2*n)
cout<<n<<" is Perfect Number"<<endl;
else
cout<<n<<" is NOT Perfect Number"<<endl;
return 0;
}
| true |
969550418f2824651293243e156814797b81d98b
|
C++
|
evectis/CAS2-DAAcourse
|
/DAA_GolanRabago/BlanketCommunication copy/BlanketCommunication.ino
|
UTF-8
| 3,615 | 2.546875 | 3 |
[] |
no_license
|
/*
Basic MQTT example
- connects to an MQTT server
- publishes "hello world" to the topic "out" of yun02
- subscribes to the topic "in"
modified for Arduino Yun by mbanzi
PubSubLibrary https://github.com/knolleary/pubsubclient
Messenger Library https://www.dropbox.com/s/lmux68kbtq9k4lq/Messenger.zip
http://playground.arduino.cc/Code/Messenger
*/
#include <Bridge.h>
#include <YunClient.h>
#include <PubSubClient.h>
#include <Messenger.h>
int flag_count = 0;
int flag_not = 0;
int G1 = 9;
//byte server[] = { 178,209,52,5}; Massimo Server
byte server[] = {192,168,240,1};
// Instantiate Messenger object with the message function and the default separator (the space character)
Messenger message = Messenger();
YunClient yunClient;
//PubSubClient client(server, 8883, callback, yunClient); Massimo Server
PubSubClient client(server, 1883, callback, yunClient);
// Define messenger function
void messageCompleted() {
if ( message.checkString("calling") ) { // Write pin (analog or digital)
digitalWrite(13, HIGH);
calling();
delay(500);
}
if ( message.checkString("Thinking") ) { // Write pin (analog or digital)
digitalWrite(13, HIGH);
thinking();
delay(500);
}
}
// Callback function
void callback(char* topic, byte* payload, unsigned int length) {
// message received, let's parse it.
payload[length] = 13;
// The following line is the most effective way of
// feeding the serial data to Messenger
for (int i = 0; i <= length; i++) {
message.process(payload[i]);
}
}
void thinking () {
int i = 0;
for (i = 0; i <= 255 ; i++)
{
analogWrite(G1, i);
delay(10);
}
analogWrite(G1, 255);
int sensor1 = analogRead(A0);
while (sensor1 <= 150) {
sensor1 = analogRead(A0);
delay(10);
}
client.publish("/devices/blanket/online", "reply");
for (i = 255; i >= 0 ; i--)
{
analogWrite(G1, i);
delay(10);
}
analogWrite(G1, 0);
}
void calling() {
int i = 0;
for (i = 0; i <= 255 ; i++)
{
analogWrite(G1, i);
delay(10);
}
analogWrite(G1, 255);
int sensor2 = analogRead(A5);
flag_count = 0;
flag_not = 0;
while ((sensor2 <= 450)) {
int p = 0;
for (p = 0; p <= 255 ; p++)
{
analogWrite(G1, p);
delay(5);
}
for (p = 255; p >= 0 ; p--)
{
analogWrite(G1, p);
delay(5);
}
flag_count=flag_count+1;
sensor2 = analogRead(A5);
Serial.print(flag_count);
if(flag_count>=5)
{ sensor2=500;
client.publish("/devices/blanket/online","notb");
client.publish("/devices/blanket/online","notb");
}
}
for (i = 255; i >= 0 ; i--)
{
analogWrite(G1, i);
delay(10);
}
if(flag_count<=4){client.publish("/devices/blanket/online","connect");}
}
void setup()
{
Bridge.begin();
message.attach(messageCompleted);
Serial.begin(9600);
if (client.connect("blanket")) {
client.publish("/devices/blanket/online", "hello world");
client.subscribe("/devices/frame/online");
}
pinMode(13, OUTPUT);
}
void loop()
{ if (client.connect("blanket")) {
client.subscribe("/devices/frame/online");
}
client.loop();
//analogWrite(G1, 255);
/*
client.publish("/devices/blanket/online","on a");
delay(1000);
client.publish("/devices/blanket/online","on b");
delay(1000);
*/
digitalWrite(13, LOW);
int sensorValue = analogRead(A0);
int sensorValue2 = analogRead(A5);
/*
Serial.print("IR1: " );
Serial.print( sensorValue);
Serial.print("\t"); // print sensor output 2
Serial.print("IR2: " );
Serial.println(sensorValue2);
delay(10);
*/
}
| true |
b05b12946245e9b50b2bcc0d5067720dbd4ea767
|
C++
|
adityachd123/JustAddPopcorn
|
/vlib.cpp
|
UTF-8
| 12,268 | 3.203125 | 3 |
[] |
no_license
|
#include<fstream.h>
#include<stdio.h>
#include<string.h> //Header files
#include<conio.h>
#include<stdlib.h>
#include<process.h>
class admin
{
char password[40];
public: admin()
{strcpy(password,"qwerty");}
int count()
{return strlen(password);}
int check_pass(char pass[])
{
if(strcmp(password,pass)==0)
return 1;
else return 0;
}
};
class vlib
{
int movie_code;
char movie_title[20];
char director[20];
char actor[10];
char actress[10];
float prices;
int no_of_copies;
int no_issued;
public:
vlib()
{
no_issued=0; //Constructor
}
void assign();
void input_for_modification();
void issue(char m_name[20]);
void rent_cd(char m_name[60]);
char* get_moviename()
{
return movie_title; //Function to return Movie Title
}
int get_code()
{
return movie_code; //Function to return Movie Code
}
void display_det();
void display_list();
void disp_full_det();
};
void vlib::assign()
{
cout<<"Enter the movie code:\n";
cin>>movie_code;
cout<<"Enter the movie name:\n";
gets(movie_title);
cout<<"Enter the director:\n";
gets(director);
cout<<"Enter the actor:\n"; //Function to Enter the details of a movie
gets(actor);
cout<<"Enter the actress:\n";
gets(actress);
cout<<"Enter the no.of copies available:\n";
cin>>no_of_copies;
cout<<"Enter the no.of copies issued:\n";
cin>>no_issued;
}
void vlib::input_for_modification()
{
cout<<"Enter the movie code:\n";
cin>>movie_code;
cout<<"Enter the movie name:\n";
gets(movie_title);
cout<<"Enter the director:\n"; //Function to Modify the various details
gets(director);
cout<<"Enter the actor:\n";
gets(actor);
cout<<"Enter the actress:\n";
gets(actress);
}
void vlib::issue(char m_name[60])
{
char ch;
do
{
cout<<"Enter the no.of DVD's of "<<m_name<<" you want to issue:\n";
cin>>no_issued;
if((no_of_copies)>=(no_issued))
{
no_of_copies-=no_issued;
cout<<no_issued<<"DVDs";
if(no_issued>1)
cout<<" 's has been issued \n"; //Function to issue the DVD's
break;
}
else
{
cout<<" Sorry!!Not enough DVD's available\n";
cout<<" Do you want to issue less DVD's ???";
cin>>ch;
}
}
while((ch=='y')||(ch=='Y'));
}
void vlib::rent_cd(char m_name[60])
{
int num;
cout<<"\n Enter the no.f DVD's of "<<m_name<<" you want to return :\n";
cin>>num;
no_of_copies+=num;
no_issued-=num;
cout<<endl<<num<<"DVD";
//Function to return the DVS's
if(num>1)
cout<<" 's have been returned \n";
else
cout<<" has been returned \n";
}
void vlib::display_det()
{
cout<<"\nMovie code : "<<movie_code<<endl;
cout<<"Movie name : ";
puts(movie_title);
cout<<"Movie director : ";
puts(director); //Function to display the details of the movie
cout<<"Movie actor : ";
puts(actor);
cout<<"Movie actress : ";
puts(actress);
cout<<endl;
}
void vlib::display_list()
{
cout<<endl;
cout<<"MOVIE CODE :"<<movie_code<<endl;
cout<<"MOVIE TITLE :"<<movie_title; //Function to display the list of movies
}
void vlib::disp_full_det()
{
cout<<"\n The movie code : "<<movie_code<<endl;
cout<<"Movie title : ";
puts(movie_title);
cout<<"The director of movie : ";
puts(director);
cout<<"The actor of movie : ";
puts(actor); //Function to display the complete details of the movie
cout<<"The actress of movie : ";
puts(actress);
cout<<"The no.of copies available : "<<no_of_copies<<endl;
cout<<"The no.of copies issued : "<<no_issued<<endl<<endl;
}
void createfile()
{
ofstream fout("vlib.dat",ios::binary);
vlib v;
char ch;
do
{
cout<<"Enter your record \n\n";
v.assign(); //create movie record
fout.write((char*)&v,sizeof(v));
cout<<"Do you want to enter more \n";
cin>>ch;
cout<<endl;
}
while((ch=='y')||(ch=='Y'));
fout.close();
}
void display_full_det()
{
ifstream fin("vlib.dat",ios::binary);
vlib v;
fin.read((char*)&v,sizeof(v));
while(fin)
{ //Function to display the full details
v.disp_full_det();
fin.read((char*)&v,sizeof(v));
}
fin.close();
}
void append()
{
ofstream fout("vlib.dat",ios::binary|ios::app);
vlib v;
char ch;
do
{
cout<<"Enter the movie record :\n";
v.assign();
fout.write((char*)&v,sizeof(v)); //Function to append a new record
cout<<"Do you want to continue ??";
cin>>ch;
}
while((ch=='y')||(ch=='Y'));
fout.close();
}
void insertion()
{
fstream file1,file2;
vlib v,vnew;
file1.open("vlib.dat",ios::binary|ios::in);
file2.open("vlibnew.dat",ios::binary|ios::out);
cout<<"Insert the movie record :\n\n";
vnew.assign();
int insert=0;
file1.read((char*)&v,sizeof(v));
while(file1) //Function to insert a new record
{
if(vnew.get_code()<v.get_code()&& (!insert))
{
file2.write((char*)&vnew,sizeof(vnew));
insert++;
}
file2.write((char*)&v,sizeof(v));
file1.read((char*)&v,sizeof(v));
}
if(!insert)
file2.write((char*)&vnew,sizeof(vnew));
file1.close();
file2.close();
remove("vlib.dat");
rename("vlibnew.dat","vlib.dat");
}
void deletion()
{
fstream file1,file2;
vlib v;
int code;
cout<<"\nEnter the movie code whose record you want to delete:";
cin>>code;
file1.open("vlib.dat",ios::binary|ios::in);
file2.open("vlibnew.dat",ios::binary|ios::out);
int del=0;
while(file1.read((char*)&v,sizeof(v)))
{
if(v.get_code()!=code) //Function to delete a record
file2.write((char*)&v,sizeof(v));
else
del++;
}
if(!del)
cout<<"Movie record not found\n";
else
cout<<"\nMovie record deleted\n";
file1.close();
file2.close();
remove("vlib.dat");
rename("vlibnew.dat","vlib.dat");
}
void modify()
{
fstream file("vlib.dat",ios::in|ios::out|ios::binary);
vlib v;
int code;
cout<<"Enter the movie code to be modified\n";
cin>>code;
int found=0;
long pos=sizeof(vlib);
file.read((char*)&v,sizeof(v));
while(file &&(!found))
{
if(v.get_code()==code)
{
found ++; //Function to Modify the details
cout<<"New Record\n";
v.input_for_modification();
file.seekp(-pos,ios::cur);
file.write((char*)&v,sizeof(v));
break;
}
file.read((char*)&v,sizeof(v));
}
if(!found)
cout<<"Movie record not found for editing\n";
file.close();
}
void display_records()
{ifstream fin("vlib.dat",ios::binary);
vlib v;
fin.read((char*)&v,sizeof(v));
while(fin)
{ //Function to display the records
v.display_det();
fin.read((char*)&v,sizeof(v));
}
fin.close();
}
void display_list()
{
ifstream fin("vlib.dat",ios::binary);
vlib v;
fin.read((char*)&v,sizeof(v));
while(fin)
{ //Function to display the list
v.display_list();
fin.read((char*)&v,sizeof(v));
}
fin.close();
}
void issue_cd()
{
fstream file("vlib.dat",ios::in|ios::out|ios::binary);
vlib v;
int code;
cout<<"\nEnter the movie code you want to rent\n";
cin>>code;
int found=0;
char m_name[60];
long pos=sizeof(vlib);
file.read((char*)&v,sizeof(v));
while(file&&!found)
{
if(v.get_code()==code) //Function to issue a dvd
{
found ++;
strcpy(m_name,v.get_moviename());
v.issue(m_name);
file.seekp(-pos,ios::cur);
file.write((char*)&v,sizeof(v));
break;
}
file.read((char*)&v,sizeof(v));
}
if(found==0)
cout<<"Wrong code entered\n";
file.close();
}
void return_cd()
{
fstream file("vlib.dat",ios::in|ios::out|ios::binary);
vlib v;
int code;
cout<<"\nEnter the movie code that you want to return\n";
cin>>code;
int found=0;
char m_name[60];
long pos=sizeof(vlib);
file.read((char*)&v,sizeof(v));
while(file&&!found)
{
if(v.get_code()==code)
{ //Function to return a DVD
found++;
strcpy(m_name,v.get_moviename());
v.rent_cd(m_name);
file.seekp(-pos,ios::cur);
file.write((char*)&v,sizeof(v));
break;
}
file.read((char*)&v,sizeof(v));
}
if(found==0)
cout<<"Wrong Code\n";
file.close();
}
int admin_login()
{
char pass[6];
int i=0;char ch;
admin a;
ifstream fin("Administrator.dat",ios::binary);
fin.read((char*)&a, sizeof(a));
fin.close();
cout<<"\n\nPlease Enter The Six Digit Password\n\n";
do
{
ch=getch();
if(ch=='\b')
{
if(i!=0)
{
i--;
cout<<"\b";
}
}
else
{
pass[i++]=ch;
cout<<"*";
}
}while(i!=a.count());
pass[i]='\0';
if(a.check_pass(pass)==1)
{cout<<"\n\nWELCOME\n\n";
return 1; //Function for entering a password
}
else
{cout<<"\n\nWRONG PASSWORD!!\n\n";
return 0;
}
}
void main()
{
{
admin a;
ofstream fout("Administrator.dat",ios::binary);
fout.write((char*)&a, sizeof(a));
fout.close();
}
int c,c1,c2;
char a,b,d;
cout<<"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n";
cout<<"*******************JUST ADDD POPCORN*****************************\n";
cout<<"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n";
cout<<"\nBuy the latest DVDs & intoxicate yourself into the majestic world of Movies \n";
cout<<" && Ofcourse,JUST ADDD POPCORN TO IT!!!!!!\n\n\n\n";
do
{
cout<<"\n1:If you are a Customer,Please Press 1\n";
cout<<"2:If you are the Admin, Please Press 2\n";
cout<<"3:If you want to View the Contact Card,Please Press 3\n";
cout<<"4:If you want to Exit,Please Press 4\n";
cin>>c;
switch(c)
{
case 1: do
{
cout<<"\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n";
cout<<"\n############CUSTOMER MENU#############\n";
cout<<"1.View the list of Movie DVDs\n";
cout<<"2.View the list of movie DVDs with all the details\n";
cout<<"3.Rent a movie DVD\n";
cout<<"4.Return a movie DVD\n";
cout<<"5.Exit from menu\n";
cin>>c1;
switch(c1)
{
case 1:cout<<" MOVIE LIST \n";
display_list();
break;
case 2:cout<<" MOVIE DETAILS \n";
display_records();
break;
case 3:display_list();
issue_cd();
break;
case 4: display_list();
return_cd();
break;
case 5: cout<<"\nExiting from the menu\n";
break;
}
cout<<"\nDo you want to return to MOVIE MENU?\n";
cin>>a;
}
while(a=='y');
break;
case 2: if(admin_login())
do
{ cout<<"\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n";
cout<<"\n@@@@@ADMIN MENU@@@@@@@@\n";
cout<<"\n1.Create Movie Records\n";
cout<<"2.Append Records\n";
cout<<"3.Display Movie Records\n";
cout<<"4.Insert a Movie Record\n";
cout<<"5.Delete a Movie Record\n";
cout<<"6.Modify an existing movie record\n";
cout<<"7.Exit\n";
cin>>c2;
switch(c2)
{
case 1: createfile();
break;
case 2: append();
break;
case 3: cout<<"MOVIE MENU\n";
display_full_det();
break;
case 4: insertion();
break;
case 5: deletion();
break;
case 6: modify();
break;
case 7:cout<<"Exiting\n";
break;
}
cout<<"\nDo you want to return to MOVIE MENU again?\n";
cin>>b;
}
while(b=='y');
break;
case 3: cout<<"\\\\\CONTACT CARD\\\\\\\\\\\n\n\n";
cout<<"/////////////////////////////////////////////////////";
cout<<endl;
cout<<"///!!!!!!!!!!!!!JUST ADDD POPCORN!!!!!!!!!!!!!!!! ///\n";
cout<<"/// The ultimate place for MOVIE LOVERS!! /// \n";
cout<<"/// ADDRESS:: Shop 23,Ground Floor, FUN MALL /// \n";
cout<<"/// Lajpat Nagar,New Delhi /// \n";
cout<<"/// CONTACT:: 9910254141(Aditya Chaudhary) ///\n";
cout<<"/// 9745874598(Abhijit Anand) ///\n";
cout<<"// E-MAIL ::adityachd123@gmail.com ///\n";
cout<<"/// ALWAYZZ READY TO SERVE YOU!!!!! ///\n";
cout<<"/////////////////////////////////////////////////////";
cout<<"\n\n";
break;
case 4:cout<<"Exiting";
exit(0);
break;
}
cout<<"\nDo you want to continue AND return to the Main Menu(Y/y)";
cin>>d;
}
while((d=='y')||(d=='Y'));
}
| true |
238ca6d1f7c26fab58b9ae87676e314a2437a463
|
C++
|
jcespinoza/TDA
|
/avl.h
|
UTF-8
| 607 | 2.90625 | 3 |
[] |
no_license
|
#ifndef AVL_H
#define AVL_H
#include "nodetree.h"
#include <iostream>
using namespace std;
template <class T>
class AVL
{
public:
AVL(){
rootNode = 0;
}
void insert(T nValue);
void printTree();
protected:
NodeTree<T>* rootNode;
private:
void insert(NodeTree<T>** root, T nValue);
void printNode(NodeTree<T>* root, int indent=0);
void rotateLeftTwice(NodeTree<T>** root);
void rotateLeftOnce(NodeTree<T>** root);
void rotateRightOnce(NodeTree<T>** root);
void rotateRightTwice(NodeTree<T>** root);
int height(NodeTree<T>* root);
};
#endif // AVL_H
| true |
e374b94c77ddeef94d64eec8e51151e8b306a632
|
C++
|
Girl-Code-It/Beginner-CPP-Submissions
|
/Kumari Mansi/Milestone 2/CodesDope - Decide If or Else/Q10.cpp
|
UTF-8
| 364 | 3.734375 | 4 |
[] |
no_license
|
/* If
x = 2
y = 5
z = 0
then find values of the following expressions:
a. x == 2
b. x != 5
c. x != 5 && y >= 5
d. z != 0 || x == 2
e. !(y < 10) */
#include <iostream>
using namespace std;
int main()
{
int x = 2;
int y = 5;
int z = 0;
cout << (x == 2);
cout << (x != 5);
cout << (x != 5 && y >= 5);
cout << (!(y < 10));
return 0;
}
| true |
1a60e9c4df3d2f48ca5707588e106f58ac0ca902
|
C++
|
Alex0Blackwell/c-cpp-DSA
|
/Algorithms/reverseCharOnly.cpp
|
UTF-8
| 635 | 3.46875 | 3 |
[
"MIT"
] |
permissive
|
class Solution {
private:
bool isLetter(char ch) {
return ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'));
}
public:
string reverseOnlyLetters(string S) {
vector<char> letters;
string res;
for(char el : S) {
if(isLetter(el))
letters.push_back(el);
}
std::reverse(letters.begin(), letters.end());
for(int i = 0; i < S.size(); ++i) {
if(!isLetter(S[i]))
letters.insert(letters.begin()+i, S[i]);
}
for(auto el : letters) {
res += el;
}
return res;
}
};
| true |
ede8b490a29b2d4d5c0a9ddc25e87758be31cfdc
|
C++
|
erikperillo/pchat
|
/src/chat.cpp
|
UTF-8
| 3,590 | 3.046875 | 3 |
[] |
no_license
|
#include "chat.h"
Chat::Chat()
{;}
bool Chat::addGroup(const std::string& group_name)
{
//checking to see if group is already inserted
for(auto const& g: this->groups)
if(g.getName() == group_name)
return false;
this->groups.push_back(Group(group_name));
return true;
}
bool Chat::delGroup(const std::string& group_name)
{
for(unsigned i=0; i<this->groups.size(); i++)
if(this->groups[i].getName() == group_name)
{
this->groups.erase(this->groups.begin() + i);
return true;
}
return false;
}
bool Chat::hasGroup(const std::string& group_name)
{
for(auto const& g: this->groups)
if(g.getName() == group_name)
return true;
return false;
}
Group Chat::getGroup(const std::string& group_name) const throw(ElementNotFound)
{
for(auto const& g: this->groups)
if(g.getName() == group_name)
return g;
throw ElementNotFound("group " + group_name + " could not be found");
}
std::vector<std::string> Chat::getGroupsNames() const
{
std::vector<std::string> names;
for(auto const& g: this->groups)
names.push_back(g.getName());
return names;
}
bool Chat::addUser(const User& user, int socket)
{
//checking to see if group is already inserted
for(auto& u: this->users)
if(u.second.getName() == user.getName())
return false;
this->users[socket] = user;
return true;
}
bool Chat::delUser(const std::string& user_name)
{
for(auto const& u: this->users)
if(u.second.getName() == user_name)
{
this->users.erase(u.first);
return true;
}
return false;
}
bool Chat::hasUser(const std::string& user_name)
{
for(auto const& u: this->users)
if(u.second.getName() == user_name)
return true;
return false;
}
User Chat::getUser(const std::string& user_name) const throw(ElementNotFound)
{
for(auto const& u: this->users)
if(u.second.getName() == user_name)
return u.second;
throw ElementNotFound("user " + user_name + " could not be found");
}
std::vector<std::string> Chat::getUsersNames() const
{
std::vector<std::string> names;
for(auto const& u: this->users)
names.push_back(u.second.getName());
return names;
}
int Chat::getSocketFromUser(const std::string& user_name)
{
for(auto const& u: this->users)
if(u.second.getName() == user_name)
return u.first;
return -1;
}
bool Chat::addUserToGroup(const std::string& user_name,
const std::string& group_name)
{
if(!this->hasUser(user_name))
return false;
for(auto& g: this->groups)
if(g.getName() == group_name)
return g.addUser(user_name);
return false;
}
bool Chat::delUserFromGroup(const std::string& user_name,
const std::string& group_name)
{
for(auto& g: this->groups)
if(g.getName() == group_name)
return g.delUser(user_name);
return false;
}
bool Chat::addMessage(const Message& msg)
{
std::size_t msg_id = std::hash<Message>{}(msg);
auto it = this->messages.find(msg_id);
if(it != this->messages.end())
return false;
this->messages[msg_id] = msg;
return true;
}
bool Chat::delMessage(const std::size_t& msg_id)
{
auto it = this->messages.find(msg_id);
if(it == this->messages.end())
return false;
this->messages.erase(msg_id);
return true;
}
bool Chat::hasMessage(const std::size_t& msg_id)
{
return this->messages.find(msg_id) != this->messages.end();
}
Message Chat::getMessage(const std::size_t& msg_id) const throw(ElementNotFound)
{
return this->messages.find(msg_id)->second;
}
std::vector<std::size_t> Chat::getMessagesIds() const
{
std::vector<std::size_t> ids;
for(auto it = this->messages.begin(); it != this->messages.end(); it++)
ids.push_back(it->first);
return ids;
}
| true |
5eb8ab987f8ef208d04b5addef826f00969bf591
|
C++
|
code-shiwu/data-struct
|
/sort/select_sort.cpp
|
UTF-8
| 731 | 4.09375 | 4 |
[] |
no_license
|
/**
* @brief 本程序实现选择排序算法
*/
#include <iostream>
void selcet_sort(int *arr, const int &count)
{
if (1 >= count)
{
std::cout << "数组中元素无需排序" << std::endl;
return;
}
for (int i = 0; i < count - 1; ++i)
{
int minpos = i;
for (int j = i; j < count; ++j)
{
if (arr[j] < arr[minpos])
{
minpos = j;
}
}
int ntemp = arr[minpos];
arr[minpos] = arr[i];
arr[i] = ntemp;
}
}
int main()
{
int arr[] = {4, 5, 6, 1, 2, 3};
selcet_sort(arr, sizeof(arr) / sizeof(int));
for (auto value : arr)
{
std::cout << value << " ";
}
}
| true |
8f645c64ac70df775d4dc71b9b95eca196382f19
|
C++
|
thallolang/thallo
|
/tests/shared/CudaArray.h
|
UTF-8
| 2,263 | 2.78125 | 3 |
[] |
no_license
|
#pragma once
#include <cuda_runtime.h>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
// Enable run time assertion checking in kernel code
#define cudaAssert(condition) if (!(condition)) { printf("ASSERT: %s %s\n", #condition, __FILE__); }
#define cudaSafeCall(err) _internal_cudaSafeCall(err,__FILE__,__LINE__)
// Adapted from the G3D innovation engine's debugAssert.h
# if defined(_MSC_VER)
# define rawBreak() __debugbreak();
# elif defined(__i386__)
// gcc on intel
# define rawBreak() __asm__ __volatile__ ( "int $3" );
# else
// some other gcc
# define rawBreak() ::abort()
# endif
inline void _internal_cudaSafeCall(cudaError err, const char *file, const int line){
if (cudaSuccess != err) {
printf("%s(%i) : cudaSafeCall() error: %s\n", file, line, cudaGetErrorString(err));
rawBreak();
}
}
#include <assert.h>
#include <vector>
template <class T>
class CudaArray {
public:
void update(const T* newData, size_t count) {
destructiveResize(count);
cudaSafeCall(cudaMemcpy(m_data, newData, sizeof(T)*m_size, cudaMemcpyHostToDevice));
}
void update(const std::vector<T>& newData) {
update(newData.data(), newData.size());
}
void readBack(T* cpuBuffer, size_t count) {
cudaSafeCall(cudaMemcpy(cpuBuffer, m_data, sizeof(T)*std::min(count,m_size), cudaMemcpyDeviceToHost));
}
void readBack(std::vector<T>& cpuBuffer) {
cpuBuffer.resize(m_size);
readBack(cpuBuffer.data(), m_size);
}
void destructiveResize(size_t count) {
if (count > m_allocated) {
if (m_data) {
cudaSafeCall(cudaFree(m_data));
}
m_allocated = count;
cudaSafeCall(cudaMalloc(&m_data, sizeof(T)*count));
}
m_size = count;
}
void alloc(size_t count) {
assert(m_size == 0);
destructiveResize(count);
}
size_t size() const {
return m_size;
}
T* data() const {
return m_data;
}
CudaArray() {}
~CudaArray() {
if (m_data) {
cudaSafeCall(cudaFree(m_data));
}
}
protected:
size_t m_allocated = 0;
size_t m_size = 0;
T* m_data = nullptr;
};
| true |
bca883b3b119b0e67124e5a34c6f35286dbcb455
|
C++
|
TigerJr/Object-Oriented-Software-Development
|
/ReversiGame.h
|
UTF-8
| 1,155 | 2.734375 | 3 |
[] |
no_license
|
#ifndef REVERSIGAME_H
#define REVERSIGAME_H
#include <string>
#include "Game.h"
using namespace std;
const game_piece BLACK_PIECE = game_piece(black, "Black_Piece", "X");
const game_piece WHITE_PIECE = game_piece(white, "White_Piece", "O");
class ReversiGame : public Game {
friend ostream & operator<< (ostream&, const ReversiGame&);
public:
ReversiGame();
ReversiGame(string, string);
virtual void print() override;
virtual bool done() override;
virtual bool stalemate()override;
virtual int turn()override;
private:
protected:
string pB;
string pW;
virtual bool is_vaild(unsigned int, unsigned int) override;
static string current;
vector<int> neighbor(unsigned int i, unsigned int j);
bool is_boundary(unsigned int);
bool movesRemain();
bool isValidMove(game_piece, int, int, int, piece_color, vector<int> &);
bool movesRemain(string);
bool bound(int, int, game_piece, int);
bool findValidNeighbor(int, int, int, int, game_piece, int);
bool iterateThroughNeighbor(int, int, game_piece, int, int);
};
ostream & operator<< (ostream&, const ReversiGame&);
#endif
| true |
9e9664c37bd7e025c832e8b3392991deef7e4020
|
C++
|
wyrover/Advanced-Process-Terminator---Suspender
|
/ProcessTerminator/main.cpp
|
UTF-8
| 1,885 | 2.625 | 3 |
[] |
no_license
|
#include <Windows.h>
#include <iostream>
#include <assert.h>
#include <string>
#include "../TerminatorCore/TerminatorCore.h"
#ifdef _DEBUG
#pragma comment( lib, "../Debug/TerminatorCore.lib" )
#else
#pragma comment( lib, "../Release/TerminatorCore.lib" )
#endif
using namespace TerminatorCore;
static CTerminatorCore terminatorCore;
typedef NTSTATUS(NTAPI* lpRtlAdjustPrivilege)(ULONG, BOOLEAN, BOOLEAN, PBOOLEAN);
lpRtlAdjustPrivilege RtlAdjustPrivilege = nullptr;
int main()
{
HMODULE hNtdll = LoadLibraryA("ntdll");
assert(hNtdll);
RtlAdjustPrivilege = (lpRtlAdjustPrivilege)GetProcAddress(LoadLibraryA("ntdll"), "RtlAdjustPrivilege");
assert(RtlAdjustPrivilege);
BOOLEAN boAdjustPrivRet;
RtlAdjustPrivilege(20, TRUE, FALSE, &boAdjustPrivRet);
printf("Advanced process terminator started!\n");
Sleep(2000);
printf("Kill methods: \n");
for (int iCurrentMethod = KILL_METHOD_MIN + 1; iCurrentMethod != KILL_METHOD_MAX; iCurrentMethod++)
{
EKillMethods kmCurrentMethod = static_cast<EKillMethods>(iCurrentMethod);
printf("%d) %s\n", iCurrentMethod, terminatorCore.GetKillMethodName(kmCurrentMethod).c_str());
}
printf("\nKill method: ");
int iKillMethod = 0;
std::cin >> iKillMethod;
if (iKillMethod <= KILL_METHOD_MIN || iKillMethod >= KILL_METHOD_MAX) {
printf("Unknown kill method: %d\n", iKillMethod);
return 0;
}
terminatorCore.ListProcesses();
printf("\nTarget Process: ");
DWORD dwTargetPID = 0;
std::cin >> dwTargetPID;
auto bKillRet = terminatorCore.KillProcess(static_cast<EKillMethods>(iKillMethod), dwTargetPID);
std::string szMsgOK = "Process: " + std::to_string(dwTargetPID) + " succesfully terminated!\n";
std::string szMsgFail = "Process: " + std::to_string(dwTargetPID) + " can NOT terminated!\n";
printf("%s", bKillRet ? szMsgOK.c_str() : szMsgFail.c_str());
printf("Completed!\n");
Sleep(INFINITE);
return 0;
}
| true |
82948fa5edb01cd866e4a8bc45bf1d5fd6573fbc
|
C++
|
Martin-BG/SoftUni-CPP-Programming
|
/06.Full-Cpp-OOP/Demos/01.Class-Members-with-Static-and-Const/SmartArray.cpp
|
UTF-8
| 2,125 | 3.65625 | 4 |
[] |
no_license
|
#include "SmartArray.h"
#include<sstream>
SmartArray::SmartArray() :
length(0),
data(new DataType[0]) {
}
SmartArray::SmartArray(int length) :
length(length),
data(new DataType[length]) {
}
SmartArray::SmartArray(const SmartArray & other) :
length(other.length),
data(new DataType[other.length]) {
copyData(other.data, other.length, this->data, this->length);
}
SmartArray& SmartArray::operator=(const SmartArray & other) {
if (this != &other) {
delete[] this->data;
this->length = other.length;
this->data = new DataType[other.length];
copyData(other.data, other.length, this->data, this->length);
}
return *this;
}
SmartArray::~SmartArray() {
delete[] data;
}
DataType SmartArray::getElement(int index) {
ensureIndexInBounds(index);
return this->data[index];
}
void SmartArray::setElement(int index, DataType value) {
ensureIndexInBounds(index);
this->data[index] = value;
}
void SmartArray::changeLength(int newLength) {
DataType * newData = new DataType[newLength]();
copyData(this->data, this->length, newData, newLength);
delete[] this->data;
this->data = newData;
this->length = newLength;
}
std::string SmartArray::toString() {
std::stringstream stringResult;
for (int i = 0; i < this->length; i++) {
stringResult << this->data[i] << " ";
}
return stringResult.str();
}
DataType& SmartArray::operator[](int index) {
ensureIndexInBounds(index);
return this->data[index];
}
void SmartArray::ensureIndexInBounds(int index) {
if (index < 0 || index >= this->length) {
throw "index out of bounds";
}
}
void SmartArray::copyData(DataType * source, int sourceLength,
DataType * dest, int destLength) {
for (int i = 0; i < sourceLength && i < destLength; i++) {
dest[i] = source[i];
}
}
SmartArray SmartArray::fromString(std::string s) {
SmartArray arr;
std::istringstream stream(s);
int number;
while(stream >> number) {
// NOTE: this is terribly inefficient, since for each new element we copy all of the others
arr.changeLength(arr.length + 1);
arr.setElement(arr.length - 1, number);
}
return arr;
}
| true |
a376edfa5979b6d888b442319b7924eea7e9655a
|
C++
|
xiaojianwu/QtQiNiuSDK
|
/libQiniu/libQiniu/putpolicy.cpp
|
GB18030
| 1,984 | 2.5625 | 3 |
[] |
no_license
|
#include "putpolicy.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QDateTime>
#include "auth.h"
PutPolicy::PutPolicy()
{
}
PutPolicy::~PutPolicy()
{
}
QString PutPolicy::token(QString ak, QString sk, QString scope)
{
QJsonDocument doc;
QJsonObject obj;
// ָϴĿԴռ(Bucket) Դ(Key)
// ָʽ
// <bucket>ʾûϴļָ bucketָʽļֻܡѴͬԴϴʧܡ
// <bucket> : <key>ʾֻûϴָkeyļָʽļĬġ
// ѴͬԴᱻǡֻϣϴָkeyļҲģôԽ insertOnly ֵΪ1
obj["scope"] = scope;
// ļڶɾţļϴʱָdeleteAfterDaysӣ
// õʱ뵽һҹ(CST, йʱ)Ӷõļɾʼʱ䡣
//ļ20151110:00 CSTϴָdeleteAfterDaysΪ3죬ô20151500 : 00 CST֮ɾļ
obj["deleteAfterDays"] = 7;
// Ϊ⡣
// Ϊ0ֵscopeΪʲôʽԡģʽϴļ
obj["insertOnly"] = 0;
// ϴƾ֤Чֹʱ䡣
// Unixʱλ롣ýֹʱΪϴɺţռļУʱ䣬ϴĿʼʱ䣬
// һ㽨Ϊϴʼʱ + 3600sûɸݾҵƾֹ֤ʱе
int deadline = QDateTime::currentDateTimeUtc().toTime_t() + 3600;
obj["deadline"] = deadline;
doc.setObject(obj);
return Auth::genUploadToken(ak, sk, doc.toJson(QJsonDocument::Compact));
}
| true |
715f50e456d8f8199e4b5ae7a8a217b9808a64c3
|
C++
|
Monirul1/Heap-Sort
|
/Heap Sort/main.cpp
|
UTF-8
| 863 | 3.765625 | 4 |
[] |
no_license
|
#include <iostream>
using namespace std;
void heapify(int arr[], int n, int i) {
int larger = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[larger]) {
larger = left;
}
if (right < n && arr[right] > arr[larger]) {
larger = right;
}
if (larger != i) {
swap(arr[i], arr[larger]);
heapify(arr, n, larger);
}
}
void heapSort(int arr[], int n) {
for (int i = n/2; i >= 0; i--) {
heapify(arr, n, i);
}
for (int i = n - 1; i >=0; i--) {
swap(arr[0], arr[i]);
heapify(arr, i, 0);
}
}
int main() {
int arr[] = {4, 2, 3, 1, 6};
int size = sizeof(arr)/sizeof(arr[0]);
heapSort(arr, size);
cout << "The sorted array is ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
| true |
c9fc1c8a7fb4212e97794068cdecb130c3d1a844
|
C++
|
wenlongx/UCLA_CS
|
/CS 32 - Introduction to Computer Science (Data Structures and OOP)/Homework3/Homework 3/maze.cpp
|
UTF-8
| 1,007 | 3.28125 | 3 |
[] |
no_license
|
//
// maze.cpp
// Homework 3
//
// Created by Wenlong Xiong on 2/7/15.
// Copyright (c) 2015 Wenlong Xiong. All rights reserved.
//
bool pathExists(std::string maze[], int nRows, int nCols, int sr, int sc, int er, int ec)
{
// if start == end, maze is solved
if (sr == er && sc == ec)
return true;
// marked as visited
maze[sr][sc] = 'A';
//NORTH
if ((sr > 0) && (maze[sr-1][sc] == '.'))
if (pathExists(maze, nRows, nCols, sr-1, sc, er, ec))
return true;
//EAST
if ((sc < nCols-1) && (maze[sr][sc+1] == '.'))
if (pathExists(maze, nRows, nCols, sr, sc+1, er, ec))
return true;
//SOUTH
if ((sr < nRows-1) && (maze[sr+1][sc] == '.'))
if (pathExists(maze, nRows, nCols, sr+1, sc, er, ec))
return true;
//WEST
if ((sr < nCols-1) && (maze[sr][sc-1] == '.'))
if (pathExists(maze, nRows, nCols, sr, sc-1, er, ec))
return true;
return false;
}
| true |
f783813bd043b382cb6c0e1cca877fa881e88b6f
|
C++
|
moevm/oop
|
/8383/syrtsova/sourse/Landscape.cpp
|
UTF-8
| 1,536 | 3.296875 | 3 |
[] |
no_license
|
#include "pch.h"
#include "Landscape.h"
#include "Object.h"
#include "Map.h"
#include "ctime"
#include <Windows.h>
Land::Land(char N, int width, int height, int col) : name(N), width(width), height(height){
object = name;
max_size = width*height;
color = col;
if (name == '~') max_water = max_size * 0.2;
else max_water = 0;
if (name == '*') max_grass = max_size;
else max_grass = 0;
if (name == '^') max_stones = max_size * 0.3;
else max_stones = 0;
}
void Land::generation(Map *field)
{
srand(time(0));
while (max_grass != 0)
{
x = 1;
y = 1;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++)
{
(*field).addOnMap(x, y, this);
max_grass--;
y++;
}
x++;
y = 1;
}
}
while (max_water != 0)
{
x = rand() % width;
y = rand() % height;
(*field).addOnMap(x, y, this);
max_water--;
}
while (max_stones != 0)
{
x = rand() % width;
y = rand() % height;
(*field).addOnMap(x, y, this);
max_stones--;
}
}
Water::Water(int width, int height, Map* field) : Land('~', width, height, colorLand::blue) {
generation(field);
}
Grass::Grass(int width, int height, Map *field) : Land('*', width, height, colorLand::green) {
generation(field);
}
Stones::Stones(int width, int height, Map *field) : Land('^', width, height, colorLand::grey) {
generation(field);
}
Landscape::Landscape(int x_max, int y_max, Map* field)
{
grass = new Grass(x_max, y_max, field);
stones = new Stones(x_max, y_max, field);
water = new Water(x_max, y_max, field);
}
| true |
353a64e7b471d25663550fe36eea9a840124c3c5
|
C++
|
OstapHEP/ostap
|
/source/include/Ostap/Polynomials.h
|
UTF-8
| 110,738 | 3.15625 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
// ============================================================================
#ifndef OSTAP_POLYNOMIALS_H
#define OSTAP_POLYNOMIALS_H 1
// ============================================================================
// Include files
// ============================================================================
// STD& STL
// ============================================================================
#include <functional>
#include <type_traits>
#include <initializer_list>
#include <vector>
#include <cmath>
// ============================================================================
// Ostap
// ============================================================================
#include "Ostap/Math.h"
#include "Ostap/Parameters.h"
#include "Ostap/Clenshaw.h"
// ============================================================================
/** @file Ostap/Polynomials.h
* various polinomials:
* - Chebyshev of the 1st kind
* - Chebyshev of the 2nd kind
* - Chebyshev of the 3rd kind
* - Chebyshev of the 4th kind
* - Legendre
* - Associate Legendre
* - Hermite
* @author Vanya BELYAEV Ivan.Belyaev@itep.ru
* @date 2010-04-19
*/
// ============================================================================
namespace Ostap
{
// ==========================================================================
namespace Math
{
// ========================================================================
namespace detail
{
// ======================================================================
template <typename F, std::size_t ... Is>
auto make_array(F f, std::index_sequence<Is...>)
-> std::array<std::decay_t<decltype(f(0u))>, sizeof...(Is)>
{ return {{f(Is)...}}; }
// ======================================================================
}
// ========================================================================
// Chebyshev
// ========================================================================
/** Evaluate Chebyshev polynomial of the first kind \f$ T_N(x) \f$
* using the recurrence relation
* \f[ T_{n+1}(x) = 2xT_n(x) - T_{n-1}(x) \f] with
* \f$ T_0(x) = 1 \f$ and \f$ T_1(x) = x \f$,
* @param N (input) the order of Chebyshev polynomial
* @param x (input) the point
* @return the value of Chebyshev polynomial of the first kind
* of order <code>N</code> at point <code>x</code>
* @author Vanya BELYAEV Ivan.Belyaev@itep.ru
* @date 2019-06-24
*/
inline double chebyshev_value
( const unsigned int N ,
const double x )
{
//
if ( 0 == N ) { return 1 ; }
else if ( 1 == N ) { return x ; }
//
long double phi_0 = 1 ;
long double phi_1 = x ;
long double phi_2 = 0 ;
//
for ( unsigned int k = 1 ; k < N ; ++ k )
{
phi_2 = 2 * x * phi_1 - phi_0 ; // recurrence rrelation here
phi_0 = phi_1 ;
phi_1 = phi_2 ;
}
//
return phi_2 ;
}
// ========================================================================
/** Evaluate Chebyshev polynomial of the second kind \f$ U_N(x) \f$
* using the recurrence relation
* \f[ U_{n+1}(x) = 2xU_n(x) - U_{n-1}(x) \f] with
* \f$ U_0(x) = 1 \f$ and \f$ U_1(x) = 2x \f$,
* @param N (input) the order of Chebyshev polynomial
* @param x (input) the point
* @return the value of Chebyshev polynomial of second kind of order
* <code>N</code> at point <code>x</code>
* @author Vanya BELYAEV Ivan.Belyaev@itep.ru
* @date 2019-06-24
*/
inline double chebyshev2_value
( const unsigned int N ,
const double x )
{
//
if ( 0 == N ) { return 1 ; }
else if ( 1 == N ) { return 2*x ; }
//
long double phi_0 = 1 ; // initial values
long double phi_1 = 2*x ; // initial values
long double phi_2 = 0 ;
//
for ( unsigned int k = 1 ; k < N ; ++ k )
{
phi_2 = 2 * x * phi_1 - phi_0 ; // recurrence rrelation here
phi_0 = phi_1 ;
phi_1 = phi_2 ;
}
//
return phi_2 ;
}
// ========================================================================
/** Evaluate Chebyshev polynomial of the third kind \f$ V_N(x) \f$
* using the recurrence relation
* \f[ V_{n+1}(x) = 2xV_n(x) - V_{n-1}(x) \f] with
* \f$ U_0(x) = 1 \f$ and \f$ U_1(x) = 2x-1 \f$.
* Explicit expression is
* \f[ V_n^{(3)} = \frac{ \cos \left( n+\frac{1}{2}\right) \theta}
* { \cos \frac{1}{2} \theta} \f], where
* \f$ x = \cos \theta\f$
* Also known as "Air-flow or airfoil polynomials"
* @param N (input) the order of Chebyshev polynomial
* @param x (input) the point
* @return the value of Chebyshev polynomial of thirf kind of order
* <code>N</code> at point <code>x</code>
* @author Vanya BELYAEV Ivan.Belyaev@itep.ru
* @date 2019-06-24
*/
inline double chebyshev3_value
( const unsigned int N ,
const double x )
{
//
if ( 0 == N ) { return 1 ; }
else if ( 1 == N ) { return 2 * x - 1 ; }
//
long double phi_0 = 1 ; // initial values
long double phi_1 = 2 * x -1 ; // initial values
long double phi_2 = 0 ;
//
for ( unsigned int k = 1 ; k < N ; ++ k )
{
phi_2 = 2 * x * phi_1 - phi_0 ; // recurrence rrelation here
phi_0 = phi_1 ;
phi_1 = phi_2 ;
}
//
return phi_2 ;
}
// ========================================================================
/** Evaluate Chebyshev polynomial of the fourth kind \f$ W_N(x)\f$
* \f$ W_n^{(4)} = \frac{ \sin \left( n+\frac{1}{2}\right) \theta}
* { \sin \frac{1}{2} \theta} \f$, where
* \f$ x = \cos \theta\f$
* Also known as "Air-flow or airfoil polynomials"
* @param N (input) the order of Chebyshev polynomial
* @param x (input) the point
* @return the value of Chebyshev polynomial of thirf kind of order
* <code>N</code> at point <code>x</code>
* @author Vanya BELYAEV Ivan.Belyaev@itep.ru
* @date 2019-06-24
*/
inline double chebyshev4_value
( const unsigned int N ,
const double x )
{ return ( N % 2 ? -1 : 1 ) * chebyshev3_value( N , -x ) ; }
// ========================================================================
// Chebyshev 1st kind
// ========================================================================
template <unsigned int N> class Chebyshev_ ;
// ========================================================================
/** @class Chebychev_
* Efficient evaluator of Chebyshev polynomial
* @author Vanya BELYAEV Ivan.Belyaev@itep.ru
* @date 2011-04-19
*/
template <unsigned int N>
class Chebyshev_
{
public:
// ======================================================================
/// the only one important method
inline double operator() ( const double x ) const
{ return evaluate ( x ) ; }
/// evaluate the polynomial
static inline double evaluate ( const double x ) ;
// ======================================================================
/// get the value of the derivative
static inline double derivative ( const double x ) ;
// ======================================================================
/// get the value of the integral
static inline double integral ( const double xlow ,
const double xhigh ) ;
// ======================================================================
/// get the value of the integral between -1 and 1
static inline double integral ( ) ;
// ======================================================================
public:
// ======================================================================
/// get the array of roots
static inline const std::array<double,N>& roots () ;
/// get the array of extrema (the endpoints are not included)
static inline const std::array<double,N-1>& extrema () ;
// ======================================================================
} ;
// ========================================================================
/// specialization for N=0
template <>
class Chebyshev_<0>
{
public:
// ======================================================================
/// evaluate it!
inline double operator () ( const double /* x */ ) const { return 1 ; }
/// evaluate it!
static inline double evaluate ( const double /* x */ ) { return 1 ; }
// ======================================================================
/// get the value of the derivative
static inline double derivative ( const double /* x */ ) { return 0 ; }
// ======================================================================
/// get the value of the integral
static inline double integral ( const double xlow ,
const double xhigh )
{ return xhigh - xlow ;}
// ======================================================================
/// get the value of the integral between -1 and 1
static inline double integral () { return 2 ; }
// ======================================================================
public:
// ======================================================================
/// get roots
static inline std::array<double,0> roots () { return {{}} ; }
/// get extrema
static inline std::array<double,0> extrema () { return {{}} ; }
// ======================================================================
} ;
// ========================================================================
/// specialization for N=1
template <>
class Chebyshev_<1>
{
public:
// ======================================================================
/// the only one important method
inline double operator() ( const double x ) const { return x ; }
/// the only one important method
static inline double evaluate ( const double x ) { return x ; }
// ======================================================================
/// get the value of the derivative
static inline double derivative ( const double /* x */ ) { return 1 ; }
// ======================================================================
/// get the value of the integral
static inline double integral ( const double xlow ,
const double xhigh )
{ return 0.5 * ( xhigh - xlow ) * ( xhigh + xlow ) ; }
// ======================================================================
/// get the value of the integral between -1 and 1
static inline double integral () { return 0 ; }
// ======================================================================
public:
// ======================================================================
/// get roots
static inline std::array<double,1> roots () { return {{ 0.0 }} ; }
/// extrema
static inline std::array<double,0> extrema () { return {{}} ; }
// ======================================================================
} ;
// ========================================================================
/// the basic recursive method
template <unsigned int N>
inline double Chebyshev_<N>::evaluate ( const double x )
{ return chebyshev_value ( N , x ) ; }
// ========================================================================
/// get the array of roots
template <unsigned int N>
inline const std::array<double,N>& Chebyshev_<N>::roots ()
{
auto root = []( unsigned int k ) -> double
{ return -std::cos ( ( 2 * k + 1 ) * M_PIl / ( 2 * N ) ) ; } ;
static const std::array<double,N> s_roots =
detail::make_array ( root , std::make_index_sequence<N>() ) ;
return s_roots ;
}
// ========================================================================
/// get the array of extrema (the endpoints are not included)
template <unsigned int N>
inline const std::array<double,N-1>& Chebyshev_<N>::extrema ()
{
auto extremum = []( unsigned int k ) -> double
{ return -std::cos ( ( k + 1 ) * M_PIl / N ) ; } ;
static const std::array<double,N-1> s_extrema =
detail::make_array ( extremum , std::make_index_sequence<N-1>() ) ;
return s_extrema ;
}
// ========================================================================
/// get the value of the integral
template <unsigned int N >
inline double Chebyshev_<N>::integral ( const double xlow ,
const double xhigh )
{
return
( Chebyshev_<N+1>::evaluate ( xhigh ) -
Chebyshev_<N+1>::evaluate ( xlow ) ) / ( 2 * ( N + 1 ) ) -
( Chebyshev_<N-1>::evaluate ( xhigh ) -
Chebyshev_<N-1>::evaluate ( xlow ) ) / ( 2 * ( N - 1 ) ) ;
}
// ========================================================================
/// get the value of the integral between -1 and 1
template <unsigned int N >
inline double Chebyshev_<N>::integral ( )
{ return 1 == N % 2 ? 0 : 2.0 / ( 1.0 - N * N ) ; }
// ========================================================================
// ========================================================================
// Chebyshev 2nd kind
// ========================================================================
template <unsigned int N> class ChebyshevU_ ;
// ========================================================================
/** @class ChebychevU_
* Efficient evaluator of Chebyshev polynomial of the second kind
* @author Vanya BELYAEV Ivan.Belyaev@itep.ru
* @date 2011-04-19
*/
template <unsigned int N>
class ChebyshevU_
{
public:
// ======================================================================
/// the only one important method
inline double operator() ( const double x ) const { return evaluate ( x ) ; }
/// the only one important method
static inline double evaluate ( const double x ) ;
// ======================================================================
public:
// ======================================================================
/// get the array of roots
static inline const std::array<double,N>& roots () ;
// ======================================================================
} ;
// ========================================================================
/// specialization for N=0
template <>
class ChebyshevU_<0>
{
public:
// ======================================================================
/// the only one important method
inline double operator() ( const double /* x */ ) const { return 1 ; }
/// the only one important method
static inline double evaluate ( const double /* x */ ) { return 1 ; }
// ======================================================================
public:
// ======================================================================
/// roots
static inline std::array<double,0> roots () { return {{}} ; }
// ======================================================================
} ;
// ========================================================================
/// specialization for N=1
template <>
class ChebyshevU_<1>
{
public:
// ======================================================================
/// the only one important method
inline double operator() ( const double x ) const { return 2 * x ; }
// ======================================================================
static inline double evaluate ( const double x ) { return 2 * x ; }
// ======================================================================
public:
// ======================================================================
/// roots
static inline std::array<double,1> roots () { return {{ 0.0 }} ; }
// ======================================================================
} ;
// ========================================================================
/// specialization for N=2
template <>
class ChebyshevU_<2>
{
// ======================================================================
public: // evaluate
// ======================================================================
/// the only one important method
inline double operator() ( const double x ) const { return 4 * x * x - 1 ; }
/// the only one important method
static inline double evaluate ( const double x ) { return 4 * x * x - 1 ; }
// ======================================================================
public: // roots & extrema
// ======================================================================
/// roots
// ======================================================================
static inline std::array<double,2> roots () { return {{ -0.5 , 0.5 }} ; }
// ======================================================================
} ;
// ========================================================================
/// the basic recurrence
template <unsigned int N>
inline double ChebyshevU_<N>::evaluate ( const double x )
{ return chebyshev2_value ( N , x ) ; }
// ========================================================================
/// get the array of roots
template <unsigned int N>
inline const std::array<double,N>& ChebyshevU_<N>::roots ()
{
auto root = []( unsigned int k ) -> double
{ return - std::cos ( ( k + 1 ) * M_PIl / ( N + 1 ) ) ; } ;
static const std::array<double,N> s_roots =
detail::make_array ( root , std::make_index_sequence<N>() ) ;
return s_roots ;
}
// ========================================================================
template <unsigned int N>
inline double Chebyshev_<N>::derivative ( const double x )
{ return N * ChebyshevU_<N-1>::evaluate ( x ) ; }
// ========================================================================
// ========================================================================
// Chebyshev 3rd kind
// ========================================================================
template <unsigned int N> class Chebyshev3_ ;
// ========================================================================
/** @class Chebychev3_
* Efficient evaluator of Chebyshev polynomial of the third kind:
* \f$ V_n^{(3)} = \frac{ \cos \left( n+\frac{1}{2}\right) \theta}
* { \cos \frac{1}{2} \theta} \f$, where
* \f$ x = \cos \theta\f$
* Also known as "Air-flow or airfoil polynomials"
* @author Vanya BELYAEV Ivan.Belyaev@itep.ru
* @date 2011-04-19
*/
template <unsigned int N>
class Chebyshev3_
{
public:
// ======================================================================
/// the only one important method
inline double operator() ( const double x ) const { return evaluate ( x ) ; }
/// the only one important method
static inline double evaluate ( const double x ) ;
// ======================================================================
public:
// ======================================================================
/// roots
static inline const std::array<double,N>& roots () ; // roots
// ======================================================================
} ;
// ========================================================================
/// specialization for N=0
template <>
class Chebyshev3_<0>
{
public:
// ======================================================================
/// the only one important method
inline double operator() ( const double /* x */ ) const { return 1 ; }
/// the only one important method
static inline double evaluate ( const double /* x */ ) { return 1 ; }
// ======================================================================
public:
// ======================================================================
/// roots
static inline std::array<double,0> roots () { return {{}} ; }
// ======================================================================
} ;
// ========================================================================
/// specialization for N=1
template <>
class Chebyshev3_<1>
{
public:
// ======================================================================
/// the only one important method
inline double operator() ( const double x ) const { return 2 * x - 1 ; }
// ======================================================================
static inline double evaluate ( const double x ) { return 2 * x - 1 ; }
// ======================================================================
public:
// ======================================================================
/// roots
static inline std::array<double,1> roots () { return {{ 0.5 }} ; }
// ======================================================================
} ;
// ========================================================================
/// the basic recursive method
template <unsigned int N>
inline double Chebyshev3_<N>::evaluate ( const double x )
{ return chebyshev3_value ( N , x ) ; } ;
// ========================================================================
/// get the array of roots
template <unsigned int N>
inline const std::array<double,N>& Chebyshev3_<N>::roots ()
{
auto root = []( unsigned int k ) -> double
{ return std::cos ( ( 2 * N - 2 * k - 1 ) * M_PIl / ( 2 * N + 1 ) ) ; } ;
static const std::array<double,N> s_roots =
detail::make_array ( root , std::make_index_sequence<N>() ) ;
return s_roots ;
}
// ========================================================================
// ========================================================================
// Chebyshev 4th kind
// ========================================================================
template <unsigned int N> class Chebyshev4_ ;
// ========================================================================
/** @class Chebychev4_
* Efficient evaluator of Chebyshev polynomial of the third kind:
* \f$ W_n^{(4)} = \frac{ \sin \left( n+\frac{1}{2}\right) \theta}
* { \sin \frac{1}{2} \theta} \f$, where
* \f$ x = \cos \theta\f$
* Also known as "Air-flow or airfoil polynomials"
* @author Vanya BELYAEV Ivan.Belyaev@itep.ru
* @date 2011-04-19
*/
template <unsigned int N>
class Chebyshev4_
{
public:
// ======================================================================
/// the only one important method
inline double operator() ( const double x ) const { return evaluate ( x ) ; }
/// the only one important method
static inline double evaluate ( const double x ) ;
// ======================================================================
public:
// ======================================================================
/// roots
static inline const std::array<double,N>& roots () ; // roots
// ======================================================================
} ;
// ========================================================================
/// the basic evaluation method
template <unsigned int N>
inline double Chebyshev4_<N>::evaluate ( const double x )
{ return chebyshev4_value ( N , x ) ; } ;
// ========================================================================
/// get the array of roots
template <unsigned int N>
inline const std::array<double,N>& Chebyshev4_<N>::roots ()
{
auto root = []( unsigned int k ) -> double
{ return std::cos ( ( 2 * N - 2 * k ) * M_PIl / ( 2 * N + 1 ) ) ; } ;
static const std::array<double,N> s_roots =
detail::make_array ( root , std::make_index_sequence<N>() ) ;
return s_roots ;
}
// ========================================================================
/** Calculate the k-th root of Legendre polynomial of order n
* @param k root number
* @param n legendre polynomial order
* @return k-th root of Legendre polynomial of order n
*/
double legendre_root ( const unsigned short k ,
const unsigned short n ) ;
// ========================================================================
/** Evaluate Legendre \f$ P_N(x) \f$
* using the recurrence relation
* \f[ (n+1)P_{n+1}(x) = (2n+1) x P_n(x) - n P_{n-1}(x) \f] with
* \f$ P_0(x) = 1 \f$ and \f$ P_1(x) = x \f$,
* @param N (input) the order of Legendre polynomial
* @param x (input) the point
* @return the value of Legendre polynomial of order <code>N</code> at point <code>x</code>
* @author Vanya BELYAEV Ivan.Belyaev@itep.ru
* @date 2019-06-24
*/
inline double legendre_value
( const unsigned int N ,
const double x )
{
//
if ( 0 == N ) { return 1 ; }
else if ( 1 == N ) { return x ; }
//
long double phi_0 = 1 ;
long double phi_1 = x ;
long double phi_2 = 0 ;
//
for ( unsigned int k = 1 ; k < N ; ++ k )
{
// recurrence rrelation here
phi_2 = ( ( 2 * k + 1 ) * x * phi_1 - k * phi_0 ) / ( k + 1 ) ;
phi_0 = phi_1 ;
phi_1 = phi_2 ;
}
//
return phi_2 ;
}
// ========================================================================
/** calculate sequence of Legendre polynomials \f$ a_i = P_i(x) \f$
* @param begin start of the sequence
* @param end end of the sequence
* @param x x-value
*/
template <class ITERATOR,
typename value_type = typename std::iterator_traits<ITERATOR>::value_type,
typename = std::enable_if<std::is_convertible<value_type,long double>::value> >
inline void legendre_values
( ITERATOR begin,
ITERATOR end ,
const long double x )
{
if ( begin == end ) { return ; }
long double p_0 = 1 ;
*begin = p_0 ; ++begin;
if ( begin == end ) { return ; }
long double p_1 = x ;
*begin = p_1 ; ++begin;
if ( begin == end ) { return ; }
long double p_i = 0 ;
unsigned int i = 2 ;
while ( begin != end )
{
//
p_i = ( ( 2 * i - 1 ) * x * p_1 - ( i - 1 ) * p_0 ) / i ;
p_0 = p_1 ;
p_1 = p_i ;
//
*begin = p_i ;
++begin ;
++i ;
}
}
// ========================================================================
/** calculate the integral for Legendre polynomial:
* \f[ \int_{x_{low}}^{x_{high}}P_N(x){\mathrm{d}} x =
* \frac{1}{2N+1} \left.\left( P_{N+1}(x)-P_{N-1}(x)\right|_{x_{low}}^{x_{high}})\f]
* @param N the order/degree of Legendre polynomial
* @param xlow the low edge
* @param xhigh the high edge
* @return the integral
*/
inline long double legendre_integral
( const unsigned int N ,
const long double xlow ,
const long double xhigh )
{
return
0 == N ? xhigh - xlow :
0 == 1 ? 0.5 * ( xhigh - xlow ) * ( xhigh + xlow ) :
( legendre_value ( N + 1 , xhigh ) -
legendre_value ( N + 1 , xlow ) -
legendre_value ( N - 1 , xhigh ) +
legendre_value ( N - 1 , xlow ) ) / ( 2 * N + 1 ) ;
}
// ========================================================================
// Legendre
// ========================================================================
template <unsigned int N> class Legendre_ ;
// ========================================================================
/** @class Legendre_
* Efficient evaluator of Legendre polynomial
* @author Vanya BELYAEV Ivan.Belyaev@itep.ru
* @date 2011-04-19
*/
template <unsigned int N>
class Legendre_
{
public:
// ======================================================================
/// the only one important method
inline double operator() ( const double x ) const { return evaluate ( x ) ; }
/// calculate the polynomial
static inline double evaluate ( const double x ) ;
/// calculate the derivative
static inline double derivative ( const double x ) ;
// ======================================================================
/// get the roots of Legendre polynomial
static inline const std::array<double,N>& roots() ;
// ======================================================================
} ;
// ========================================================================
/// specialization for 0
template <>
class Legendre_<0>
{
public:
// ======================================================================
/// the only one important method
inline double operator() ( const double /* x */ ) const { return 1 ; }
/// calculate the polynomial
static inline double evaluate ( const double /* x */ ) { return 1 ; }
/// calculate the derivative
static inline double derivative ( const double /* x */ ) { return 0 ; }
/// get the roots of Legendre polymonial
static inline std::array<double,0> roots() { return {{}} ; }
// ======================================================================
} ;
// ========================================================================
/// specialization for N=1
template <>
class Legendre_<1>
{
public:
// ======================================================================
/// the only one important method
inline double operator() ( const double x ) const { return x ; }
/// calculaet the polynomial
static inline double evaluate ( const double x ) { return x ; }
/// calculate the derivative
static inline double derivative ( const double /* x */ ) { return 1 ; }
/// get the roots of Legendre polymonial
static inline std::array<double,1> roots() { return {{ 0.0 }} ; }
// ======================================================================
} ;
// ========================================================================
/// should one use here legendre_eval ?
template <unsigned int N>
inline double Legendre_<N>::evaluate ( const double x )
{ return legendre_value ( N , x ) ; }
// ========================================================================
/// get the array of roots
template <unsigned int N>
inline const std::array<double,N>& Legendre_<N>::roots ()
{
auto root = []( unsigned int k ) -> double { return legendre_root ( k , N ) ; } ;
static const std::array<double,N> s_roots =
detail::make_array ( root , std::make_index_sequence<N>() ) ;
return s_roots ;
}
// =======================================================================
/// calculate the derivative
template <unsigned int N>
inline double Legendre_<N>::derivative ( const double x )
{
// /// 1) naive recursive algorithm, not safe when |x| is close to 1
// static const Ostap::Math::Equal_To<double> s_equal {} ;
// return
// x > 0.999 && s_equal ( x , 1 ) ? 0.5 * N * ( N + 1 ) :
// x < -0.999 && s_equal ( x , -1 ) ? 0.5 * N * ( N + 1 ) * ( N % 2 ? 1 : -1 ) :
// N * ( x * Legendre_<N>::evaluate ( x ) - Legendre_<N-1>::evaluate ) / ( x * x - 1 ) ;
//
// /// 2) the recursive algorithm that is safe for |x| close to 1
// return
// N * Legendre_<N-1>::evaluate ( x ) +
// x * Legendre_<N-1>::derivative ( x ) ;
//
/// 3) and this algorithm is much faster (linear):
auto ak = [] ( const unsigned int k ) -> unsigned int
{ return (k+N)%2 ? 2*k+1 : 0 ; };
auto alpha = [] ( const unsigned int k , const long double y ) -> long double
{ return (2*k+1)*y/(k+1) ; } ;
auto beta = [] ( const unsigned int k , const long double /* y */ ) -> long double
{ return -1.0L*k*1.0L/(k+1) ; } ;
auto phi0 = [] ( const long double /* y */ ) -> long double { return 1 ; } ;
auto phi1 = [] ( const long double y ) -> long double { return y ; } ;
//
return Ostap::Math::Clenshaw::sum
( x , N - 1 , ak , alpha , beta , phi0 , phi1 );
}
// ========================================================================
// Hermite
// ========================================================================
/** Evaluate (probabilistic)
* Hermite polynom \f$ He_N(x) \f$ using the recurrence relation
* \f$ He_{n+1}(x) = xHe_{n}(x) - n He_{n-1}(x)\f]
* @param N (input) the order of Hermite polynomial
* @param x (input) the point
* @return the value of Hermite polynomial of order <code>N</code> at point <code>x</code>
* @author Vanya BELYAEV Ivan.Belyaev@itep.ru
* @date 2019-06-24
*/
inline double hermite_value
( const unsigned int N ,
const double x )
{
//
if ( 0 == N ) { return 1 ; }
else if ( 1 == N ) { return x ; }
//
long double phi_0 = 1 ;
long double phi_1 = x ;
long double phi_2 = 0 ;
//
for ( unsigned int k = 1 ; k < N ; ++ k )
{
// recurrence relation here
phi_2 = x * phi_1 - k * phi_0 ;
phi_0 = phi_1 ;
phi_1 = phi_2 ;
}
//
return phi_2 ;
}
// ========================================================================
// Hermite
// ========================================================================
template <unsigned int N> class Hermite_ ;
// ========================================================================
/** @class Hermite_
* Efficient evaluator of Hermite polynomial
* These are "probabilistic" polinomials,
* \f$He(x)\f$
* such as coefficienst at maximar degree is always equal to 1
* @author Vanya BELYAEV Ivan.Belyaev@itep.ru
* @date 2011-04-19
*/
template <unsigned int N>
class Hermite_
{
public:
// ======================================================================
/// the only one important method
inline double operator() ( const double x ) const
{ return evaluate ( x ) ; }
// ======================================================================
static inline double evaluate ( const double x ) ;
// ======================================================================
} ;
// ========================================================================
/// specialization for 0
template <>
class Hermite_<0>
{
public:
// ======================================================================
inline double operator() ( const double /* x */ ) const { return 1 ; }
// ======================================================================
static inline double evaluate ( const double /* x */ ) { return 1 ; }
// ======================================================================
} ;
// ========================================================================
/// specialization for N=1
template <>
class Hermite_<1>
{
public:
// ======================================================================
/// the only one important method
inline double operator() ( const double x ) const { return x ; }
// ======================================================================
static inline double evaluate ( const double x ) { return x ; }
// ======================================================================
} ;
// ========================================================================
template <unsigned int N>
inline double Hermite_<N>::evaluate ( const double x )
{
// naive recursion
// return x * Hermite_<N-1>::evaluate ( x ) - ( N - 1 ) * Hermite_<N-2>::evaluate ( x ) ;
// optimized recursion
return hermite_value ( N , x ) ;
}
// ========================================================================
// Associated Legendre functions
// ========================================================================
namespace detail
{
// ======================================================================
/// evaluate normalized assiciated Legendre polynomials/functions
template <unsigned int L, unsigned int M , typename = void>
class PLegendre_helper_ ;
//
template <unsigned int L, unsigned int M>
class PLegendre_helper_<L,M,typename std::enable_if<L==0&&M==0>::type>
{
public :
inline double operator() ( const double x ) const { return evaluate ( x ) ; }
static inline double evaluate ( const double /* x */ )
{
static const long double s_P00 = std::sqrt ( 1.0L / ( 4 * M_PIl ) ) ;
return s_P00 ;
}
};
//
template <unsigned int L, unsigned int M>
class PLegendre_helper_<L,M,typename std::enable_if<L==1&&M==1>::type>
{
public :
inline double operator() ( const double x ) const { return evaluate ( x ) ; }
static inline double evaluate ( const double x )
{
static const long double s_n = - std::sqrt( 3.0L / 2.0L ) *
PLegendre_helper_<0,0>::evaluate ( 0 ) ;
return s_n * std::sqrt ( 1.0L - x * x ) ;
}
};
//
template <unsigned int L, unsigned int M>
class PLegendre_helper_<L,M,typename std::enable_if<L==M&&L!=0&&L!=1>::type>
{
public :
inline double operator() ( const double x ) const { return evaluate ( x ) ; }
static inline double evaluate ( const double x )
{
static const long double s_n =
std::sqrt ( ( 2 * M + 1 ) * ( 2 * M - 1 ) * 0.25L / ( M * ( M - 1 ) ) ) ;
return s_n * ( 1.0L - x * x ) * PLegendre_helper_<L-2,L-2>::evaluate ( x ) ;
}
};
//
template <unsigned int L, unsigned int M>
class PLegendre_helper_<L,M,typename std::enable_if<L==M+1>::type>
{
public :
inline double operator() ( const double x ) const { return evaluate ( x ) ; }
static inline double evaluate ( const double x )
{
static const long double s_n = std::sqrt ( 2 * M + 3.0L ) ;
return s_n * x * PLegendre_helper_<M,M>::evaluate ( x ) ;
}
};
//
template <unsigned int L, unsigned int M>
class PLegendre_helper_<L,M,typename std::enable_if<M+2<=L>::type>
{
public :
inline double operator() ( const double x ) const { return evaluate ( x ) ; }
static inline double evaluate ( const double x )
{
//
long double p0 = PLegendre_helper_<M ,M>::evaluate ( x ) ;
long double p1 = PLegendre_helper_<M+1,M>::evaluate ( x ) ;
long double pN = 0 ;
//
unsigned int N = M + 2 ;
while ( L >= N )
{
pN = a ( N ) * x * p1 - b ( N ) * p0 ;
p0 = p1 ;
p1 = pN ;
++N ;
}
//
return pN ;
}
private :
// ====================================================================
static inline long double a ( const unsigned int J )
{
auto afun = [] ( const unsigned int K ) -> long double
{
const unsigned int I = K + M + 1 ;
return std::sqrt ( ( 2 * I - 1 ) * 1.0L * ( 2 * I + 1 ) / ( I * I - M * M ) ) ;
} ;
static const std::array<long double, L-M> s_a =
detail::make_array ( afun , std::make_index_sequence<L-M>() ) ;
return s_a [ J - ( M + 1 ) ] ;
}
static inline long double b ( const unsigned int J )
{
auto bfun = [] ( const unsigned int K ) -> long double
{
const unsigned int I = K + M + 2 ;
return PLegendre_helper_<L,M>::a(I)/PLegendre_helper_<L,M>::a(I-1) ;
} ;
static const std::array<long double, L-M-1> s_b =
detail::make_array ( bfun , std::make_index_sequence<L-M-1>() ) ;
return s_b [ J - ( M + 2 ) ] ;
}
// ====================================================================
};
// =====================================================================
/** evaluate the normalized associated legendre polynomials/function
* \$ P^{m}_{l}(z)\$ with normalization suitbale for spherical harmonics :
* \f$ \int_{-1}{+1}P^m_l(x)P^m_{l}(x){\mathrm{d}} x = \frac{1}{2\pi}\f$
*/
inline long double plegendre_eval_
( const unsigned int L ,
const unsigned int M ,
const long double x )
{
//
if ( M > L ){ return 0 ; }
else if ( L == 0 && M == 0 ) { return PLegendre_helper_<0,0>::evaluate ( x ) ; }
else if ( L == 1 && M == 1 ) { return PLegendre_helper_<1,1>::evaluate ( x ) ; }
else if ( L == M )
{
long double result = ( 0 == L%2 ) ?
PLegendre_helper_<0,0>::evaluate ( x ) :
PLegendre_helper_<1,1>::evaluate ( x ) ;
const unsigned int L0 = ( 0 == L%2 ) ? 2 : 3 ;
for ( unsigned int l = L0 ; l <= M ; l += 2 )
{
result *= ( 1.0L - x * x ) *
std::sqrt ( ( l + 0.5L ) * ( l - 0.5L ) / ( ( l - 1.0L ) * l ) ) ;
}
return result ;
}
else if ( L == M && 0 == L%2 )
{
long double result = PLegendre_helper_<0,0>::evaluate ( x ) ;
for ( unsigned int l = 2; l <= M ; l += 2 )
{
result *= ( 1.0L - x * x ) *
std::sqrt ( ( l + 0.5L ) * ( l - 0.5L ) / ( ( l - 1.0L ) * l ) ) ;
}
return result ;
}
else if ( L == M + 1 )
{ return std::sqrt ( 2 * M + 3.0L ) * x * plegendre_eval_ ( M , M , x ) ; }
//
/// regular case
//
long double p0 = plegendre_eval_ ( M , M , x ) ;
long double p1 = plegendre_eval_ ( M + 1 , M , x ) ;
// long double p1 = std::sqrt ( 2 * M + 3.0L ) * x * p0 ;
long double pN = 0 ;
//
auto afun = [] ( const unsigned int J , const unsigned int M ) -> long double
{ return std::sqrt ( ( 2 * J - 1 ) * 1.0L * ( 2 * J + 1 ) / ( J * J - M * M ) ) ; } ;
auto bfun = [&afun] ( const unsigned int J , const unsigned int M ) -> long double
{ return afun ( J , M ) / afun ( J - 1 , M ) ; } ;
//
unsigned int N = M + 2 ;
while ( L >= N )
{
pN = afun ( N , M ) * x * p1 - bfun ( N , M ) * p0 ;
p0 = p1 ;
p1 = pN ;
++N ;
}
//
return pN ;
} ;
// ======================================================================
}
// ========================================================================
/** @class PLegendre_
* The normalized associated Legendre polynomials/functions
* Normalization is suitable for usage of them for the spherical harmonics.
* @see https://arxiv.org/abs/1410.1748
* \f$ \int _{-1}^{1} P_l^m(x)P_l^{m}(x) {\mathrm{d}} x = \frac{1}{2\pi}\f$
* @author Vanya BELYAEV Ivan.Belyaev@itep.ru
* @date 2019-06-27
*/
template <unsigned int L , unsigned int M>
class PLegendre_ : public detail::PLegendre_helper_<L,M>
{ static_assert ( M <= L , "PLegendre_ : M must me M <= L" ); };
// =====================================================================
/** evaluate the normalized associated legendre polynomials/function
* \$ P^{m}_{l}(z)\$ with normalization suitbale for spherical harmonics :
* \f$ \int_{-1}{+1}P^m_l(x)P^m_{l}(x){\mathrm{d}} x = \frac{1}{2\pi}\f$
*/
inline double plegendre_value
( const unsigned int L ,
const unsigned int M ,
const double x )
{ return detail::plegendre_eval_ ( L , M , x ) ; }
// ========================================================================
// Non-templated
// ========================================================================
/** @class Chebyshev
* evaluate the chebyshev polynomials
* @author Vanya BELYAEV Ivan.Belyaev@itep.ru
* @date 2011-04-19
*/
class Chebyshev
{
public :
// ======================================================================
/// constructor
Chebyshev ( const unsigned int N = 0 ) : m_N ( N ) {}
// ======================================================================
public:
// ======================================================================
/// evaluate the polynomial
inline double operator() ( const double x ) const { return evaluate ( x ) ; }
/// evaluate the polynomial
inline double evaluate ( const double x ) const
{ return chebyshev_value ( m_N , x ) ; }
// ======================================================================
public:
// ======================================================================
unsigned int degree () const { return m_N ; }
// ======================================================================
public:
// ======================================================================
/// derivative
double derivative ( const double x ) const ;
// ======================================================================
/// get integral between low and high
double integral ( const double low ,
const double high ) const ;
// ======================================================================
/// get the integral between -1 and 1
double integral () const
{ return 1 == m_N % 2 ? 0.0 : 2.0 / ( 1.0 - m_N * m_N ) ; }
// ======================================================================
public: // roots & extrema
// ======================================================================
/// get all roots of the polynomial
std::vector<double> roots () const ;
/// get all extrema of the polynomial
std::vector<double> extrema () const ;
// ======================================================================
private:
// ======================================================================
unsigned int m_N ;
// ======================================================================
} ;
// ========================================================================
/** @class ChebyshevU
* evaluate the chebyshev polynomials of the second kind
* @author Vanya BELYAEV Ivan.Belyaev@itep.ru
* @date 2011-04-19
*/
class ChebyshevU
{
public :
// ======================================================================
/// constructor
ChebyshevU ( const unsigned int N = 0 ) : m_N ( N ) {}
// ======================================================================
public:
// ======================================================================
/// evaluate the polynomial
double operator() ( const double x ) const ;
// ======================================================================
public:
// ======================================================================
unsigned int degree () const { return m_N ; }
// ======================================================================
public:
// ======================================================================
/// derivative
double derivative ( const double x ) const ;
// ======================================================================
/// get integral between low and high
double integral ( const double low ,
const double high ) const ;
// ======================================================================
private:
// ======================================================================
unsigned int m_N ;
// ======================================================================
} ;
// ========================================================================
/** @class Hermite
* evaluate the Hermite polynomials
* @author Vanya BELYAEV Ivan.Belyaev@itep.ru
* @date 2011-04-19
*/
class Hermite
{
public :
// ======================================================================
/// constructor
Hermite ( const unsigned int N = 0 ) ;
// ======================================================================
public:
// ======================================================================
/// evaluate the polynomial
inline double operator() ( const double x ) const { return evaluate ( x ) ; }
inline double evaluate ( const double x ) const
{ return hermite_value ( m_N , x ) ; }
// ======================================================================
public:
// ======================================================================
unsigned int degree () const { return m_N ; }
// ======================================================================
public:
// ======================================================================
/// derivative
double derivative ( const double x ) const
{ return 0 == m_N ? 0 : m_N * hermite_value ( m_N - 1 , x ) ; }
// ======================================================================
/// get integral between low and high
double integral ( const double low , const double high ) const ;
// ======================================================================
private:
// ======================================================================
unsigned int m_N ;
// ======================================================================
} ;
// ========================================================================
/** @class Legendre
* evaluate the Legendre polynomials
* @author Vanya BELYAEV Ivan.Belyaev@itep.ru
* @date 2011-04-19
*/
class Legendre
{
public :
// ======================================================================
/// constructor
Legendre ( const unsigned int N = 0 ) : m_N ( N ) {}
// ======================================================================
public:
// ======================================================================
/// evaluate the polynomial
inline double operator() ( const double x ) const { return evaluate ( x ) ; }
inline double evaluate ( const double x ) const
{ return legendre_value ( m_N , x ) ; }
// ======================================================================
public:
// ======================================================================
unsigned int degree () const { return m_N ; }
// ======================================================================
public:
// ======================================================================
/// derivative
double derivative ( const double x ) const ;
// ======================================================================
/// get integral between low and high
double integral
( const double low ,
const double high ) const ;
// ======================================================================
public: // roots
// ======================================================================
/// get the root of the Legendre polynomial
double root ( const unsigned short i ) const ;
/// get all roots of the Legendre polynomial
const std::vector<double>& roots () const ;
// ======================================================================
public:
// ======================================================================
/// get the root of the Legendre polynomial
double calculate_root ( const unsigned short i ) const ;
// ======================================================================
private:
// ======================================================================
unsigned int m_N ;
// ======================================================================
} ;
// ========================================================================
/** @class PLegendre
* evaluate the associative Legendre polynomials/functions
* \f$P^{m}_{l}(x)\f$
* Normalization is sutable for spherical harmonics
* \f$ \int_{-1}^{+1} P^{m}_{l}(x)P^{m}_{l}(x) {\mathrm{d}} x = \frac{1}{2\pi} \f$
* @author Vanya BELYAEV Ivan.Belyaev@itep.ru
* @date 2011-04-19
*/
class PLegendre
{
public :
// ======================================================================
/// constructor
PLegendre ( const unsigned int L = 0 ,
const unsigned int M = 0 ) ;
// ======================================================================
public:
// ======================================================================
/// evaluate the polynomial
inline double operator() ( const double x ) const { return evaluate ( x ) ; }
inline double evaluate ( const double x ) const
{ return plegendre_value ( m_L , m_M , x ) ; }
// ======================================================================
public:
// ======================================================================
unsigned int L () const { return m_L ; }
unsigned int M () const { return m_M ; }
unsigned int l () const { return m_L ; }
unsigned int m () const { return m_M ; }
// ======================================================================
public:
// ======================================================================
unsigned int m_L ;
unsigned int m_M ;
// ======================================================================
} ;
// ========================================================================
/** affine transformation of polynomial
* \f$ x ^{\prime} = \alpha x + \beta \f$
* @param input (INPUT) input polynomial coefficients
* @param result (UPDATE) coefficients of transformed polynomial
* @param alpha (INPUT) alpha
* @param beta (INPUT) beta
* @return true for valid transformations
* @author Vanya BELYAEV Ivan.Belyaev@itep.ru
* @date 2015-03-09
*/
bool affine_transform
( const std::vector<double>& input ,
std::vector<double>& result ,
const double alpha = 1 ,
const double beta = 0 ) ;
// ========================================================================
/// forward declarations
class Bernstein ; // forward declarations
// ========================================================================
/** @class PolySum
* Base class for polynomial sums
* \f$ f(x) = \sum_i \alpha_i P_i(x) \f$
* @author Vanya BELYAEV Ivan.Belyaev@itep.ru
* @date 2015-02-10
*/
class PolySum : public Parameters
{
public:
// ======================================================================
/// constructor from polynomial degree
PolySum ( const unsigned short degree = 0 ) ;
/// constructor from vector of parameters
PolySum ( const std::vector<double>& pars ) ;
/// constructor from vector of parameters
PolySum ( std::vector<double>&& pars ) ;
/// constructor from sequence of parameters
template <typename ITERATOR,
typename value_type = typename std::iterator_traits<ITERATOR>::value_type,
typename = std::enable_if<std::is_convertible<value_type,long double>::value> >
PolySum
( ITERATOR begin ,
ITERATOR end )
: Parameters ( begin , end )
{ if ( m_pars.empty() ) { m_pars.push_back ( 0 ) ; } }
// ======================================================================
public:
// ======================================================================
/// degree of polynomial
unsigned short degree () const { return m_pars.empty() ? 0 : m_pars.size() - 1 ; }
/// degree of polynomial
unsigned short n () const { return degree () ; }
// ======================================================================
} ;
// ========================================================================
/// forward declarations
class Bernstein ; // forward declaration
class Polynomial ; // forward declaration
class LegendreSum ; // forward declaration
class ChebyshevSum ; // forward declaration
class HermiteSum ; // forward declaration
class KarlinShapley ; // forward declaration
class KarlinStudden ; // forward declaration
class BernsteinEven ; // forward declaration
class Positive ; // forward declaration
class Monotonic ; // forward declaration
class Convex ; // forward declaration
class ConvexOnly ; // forward declaration
// ========================================================================
// Polynomial sums
// ========================================================================
/** @class Polynomial
* Trivial polynomial
* \f$ f(x) = \sum_i p_i x^i\f$
* @author Vanya BELYAEV Ivan.Belyaev@itep.ru
* @date 2015-02-22
*/
class Polynomial : public PolySum
{
public:
// =====================================================================
/// constructor from the degree
Polynomial
( const unsigned short degree = 0 ,
const double xmin = -1 ,
const double xmax = 1 ) ;
// ======================================================================
/// constructor from the parameter list
Polynomial
( const std::vector<double>& pars ,
const double low = -1 ,
const double high = 1 ) ;
/// template constructor from sequence of parameters
template <class ITERATOR,
typename value_type = typename std::iterator_traits<ITERATOR>::value_type,
typename = std::enable_if<std::is_convertible<value_type,double>::value> >
Polynomial
( ITERATOR first ,
ITERATOR last ,
const double xmin ,
const double xmax )
: Ostap::Math::PolySum ( first , last )
, m_xmin ( std::min ( xmin, xmax ) )
, m_xmax ( std::max ( xmin, xmax ) )
{}
// ======================================================================
/// construct polynomial from different range
Polynomial
( const Polynomial& right ,
const double xmin ,
const double xmax ) ;
// ======================================================================
/** construct Bernstein polynomial from its roots
*
* Polinomial has a form
* \f$ B(x) = \prod_i (x-r_i) \prod_j (x-c_j)(x-c_j^*) \f$
*
* @param xmin low edge for polynomial
* @param xmax high edge for polynomial
* @param roots_real the list of real roots of the polinomial
* @param roots_complex the list of complex roots (only one root from cc-pair is needed)
*/
Polynomial
( const double xmin ,
const double xmax ,
const std::vector<double>& roots_real ,
const std::vector<std::complex<double> > & roots_complex = std::vector<std::complex<double> > () );
// ======================================================================
/** construct polynomial from its roots
*
* Polinomial has a form
* \f$ B(x) = \prod_i (x-r_i) \prod_j (x-c_j)(x-c_j^*) \f$
*
* @param xmin low edge for polynomial
* @param xmax high edge polynomial
* @param roots_complex the list of complex roots (only one root from cc-pair is needed)
* @param roots_real the list of real roots of the polinomial
*/
Polynomial
( const double xmin ,
const double xmax ,
const std::vector<std::complex<double> > & roots_complex ,
const std::vector<double>& roots_real = std::vector<double> () ) ;
// ======================================================================
/// copy
Polynomial ( const Polynomial& ) = default ;
/// move
Polynomial ( Polynomial&& ) = default ;
// ======================================================================
/// constructor from Bernstein polynomial (efficient)
explicit Polynomial ( const Bernstein& poly ) ;
/// constructor from Legendre polynomial (efficient)
explicit Polynomial ( const LegendreSum& poly ) ;
/// constructor from Chebyshev polynomial (delegation)
explicit Polynomial ( const ChebyshevSum& poly ) ;
/// constructor from Karlin-Shapley polinomial
explicit Polynomial ( const KarlinShapley& poly ) ;
/// constructor from Karlin-Studden polinomial
explicit Polynomial ( const KarlinStudden& poly ) ;
/// constructor from Even Bernstein polynomial (efficient)
explicit Polynomial ( const BernsteinEven& poly ) ;
/// constructor from positive Bernstein polynomial (efficient)
explicit Polynomial ( const Positive& poly ) ;
/// constructor from monotonic Bernstein polynomial (efficient)
explicit Polynomial ( const Monotonic& poly ) ;
/// constructor from convex Bernstein polynomial (efficient)
explicit Polynomial ( const Convex& poly ) ;
/// constructor from convex-only Bernstein polynomial (efficient)
explicit Polynomial ( const ConvexOnly& poly ) ;
// ======================================================================
public:
// ======================================================================
/// get the value
double evaluate ( const double x ) const ;
// ======================================================================
/// get the value
double operator () ( const double x ) const
{ return x < m_xmin ? 0 : x > m_xmax ? 0 : evaluate ( x ) ; }
// ======================================================================
public:
// ======================================================================
/// get lower edge
double xmin () const { return m_xmin ; }
/// get upper edge
double xmax () const { return m_xmax ; }
/// middle x
double xmid () const { return 0.5 * ( m_xmin + m_xmax ) ; }
/// delta/scale/interval length
double delta () const { return m_xmax - m_xmin ; }
// ======================================================================
public:
// ======================================================================
double x ( const double t ) const
{ return 0.5 * ( t * ( m_xmax - m_xmin ) + m_xmax + m_xmin ) ; }
double t ( const double x ) const
{ return ( 2 * x - m_xmax - m_xmin ) / ( m_xmax - m_xmin ) ; }
// ======================================================================
public:
// ======================================================================
/// get the integral between xmin and xmax
double integral () const ;
/// get the integral between low and high
double integral ( const double low , const double high ) const ;
/// get the derivative at point "x"
double derivative ( const double x ) const ;
// ======================================================================
public:
// ======================================================================
/// get indefinte integral
Polynomial indefinite_integral ( const double C = 0 ) const ;
/// get the derivative
Polynomial derivative () const ;
// ======================================================================
public:
// ======================================================================
/// simple manipulations with polynoms: shift it!
Polynomial& operator += ( const double a ) ;
/// simple manipulations with polynoms: shift it!
Polynomial& operator -= ( const double a ) ;
/// simple manipulations with polynoms: scale it
Polynomial& operator *= ( const double a ) ;
/// simple manipulations with polynoms: scale it
Polynomial& operator /= ( const double a ) ;
/// negate it!
Polynomial operator-() const ; // negate it!
// ======================================================================
public:
// ======================================================================
/// Add polynomials (with the same domain!)
Polynomial sum ( const Polynomial& other ) const ;
/// Subtract polynomials (with the same domain!)
Polynomial subtract ( const Polynomial& other ) const ;
// ======================================================================
public:
// ======================================================================
/// Add polynomials (with the same domain!)
Polynomial& isum ( const Polynomial& other ) ;
/// Subtract polynomials (with the same domain!)
Polynomial& isub ( const Polynomial& other ) ;
// ======================================================================
public:
// ======================================================================
inline Polynomial& operator+=( const Polynomial& other ) { return isum ( other ) ; }
inline Polynomial& operator-=( const Polynomial& other ) { return isub ( other ) ; }
// ======================================================================
public:
// ======================================================================
/// Add polynomials (with the same domain!)
Polynomial __add__ ( const Polynomial& other ) const ;
/// Subtract polynomials (with the same domain!)
Polynomial __sub__ ( const Polynomial& other ) const ;
// ======================================================================
public:
// ======================================================================
Polynomial& __iadd__ ( const double a ) ;
Polynomial& __isub__ ( const double a ) ;
Polynomial& __imul__ ( const double a ) ;
Polynomial& __itruediv__ ( const double a ) ;
Polynomial& __idiv__ ( const double a ) { return __itruediv__ ( a ) ; }
// ======================================================================
public:
// ======================================================================
Polynomial __add__ ( const double a ) const ;
Polynomial __sub__ ( const double a ) const ;
Polynomial __mul__ ( const double a ) const ;
Polynomial __truediv__ ( const double a ) const ;
Polynomial __div__ ( const double a ) const { return __truediv__ ( a ) ; }
// ======================================================================
public:
// ======================================================================
Polynomial __radd__ ( const double a ) const ;
Polynomial __rsub__ ( const double a ) const ;
Polynomial __rmul__ ( const double a ) const ;
// ======================================================================
public:
// ======================================================================
Polynomial& __iadd__ ( const Polynomial& a ) { return isum ( a ) ; }
Polynomial& __isub__ ( const Polynomial& a ) { return isub ( a ) ; }
// ======================================================================
public:
// ======================================================================
/// Negate it!
Polynomial __neg__ () const ; // Negate it!
// ======================================================================
public:
// ======================================================================
/// get unique tag
std::size_t tag() const ; // get unique tag
// ======================================================================
private:
// ======================================================================
/// x-min
double m_xmin ; // x-min
/// x-max
double m_xmax ; // x-max
// ======================================================================
} ;
// ========================================================================
inline Polynomial operator+( const Polynomial& a , const Polynomial& b )
{ return a.sum ( b ) ; }
inline Polynomial operator-( const Polynomial& a , const Polynomial& b )
{ return a.subtract ( b ) ; }
inline Polynomial operator+( const Polynomial& a , const double b )
{ return a.__add__ ( b ) ; }
inline Polynomial operator+( const double b , const Polynomial& a )
{ return a.__add__ ( b ) ; }
inline Polynomial operator-( const Polynomial& a , const double b )
{ return a.__sub__ ( b ) ; }
inline Polynomial operator-( const double b , const Polynomial& a )
{ return a.__rsub__ ( b ) ; }
inline Polynomial operator*( const Polynomial& a , const double b )
{ return a.__mul__ ( b ) ; }
inline Polynomial operator*( const double b , const Polynomial& a )
{ return a.__mul__ ( b ) ; }
inline Polynomial operator/( const Polynomial& a , const double b )
{ return a.__truediv__ ( b ) ; }
// ========================================================================
/** @class ChebyshevSum
* Sum of chebychev polinomials
* \f$ f(x) = \sum_i p_i T_i(x)\f$
* @author Vanya BELYAEV Ivan.Belyaev@itep.ru
* @date 2015-02-22
*/
class ChebyshevSum : public PolySum
{
public:
// =====================================================================
/// constructor from the degree
ChebyshevSum
( const unsigned short degree = 0 ,
const double xmin = -1 ,
const double xmax = 1 ) ;
// ======================================================================
/// constructor from the parameter list
ChebyshevSum
( const std::vector<double>& pars ,
const double xmin = -1 ,
const double xmax = 1 ) ;
/// template constructor from sequence of parameters
template <class ITERATOR,
typename value_type = typename std::iterator_traits<ITERATOR>::value_type,
typename = std::enable_if<std::is_convertible<value_type,long double>::value> >
ChebyshevSum
( ITERATOR first ,
ITERATOR last ,
const double xmin ,
const double xmax )
: Ostap::Math::PolySum ( first , last )
, m_xmin ( std::min ( xmin, xmax ) )
, m_xmax ( std::max ( xmin, xmax ) )
{}
// ======================================================================
/// copy
ChebyshevSum ( const ChebyshevSum& ) = default ;
/// move
ChebyshevSum ( ChebyshevSum&& ) = default ;
// ======================================================================
/// constructor from Polinomial (efficient)
explicit ChebyshevSum ( const Polynomial& poly ) ;
/// constructor from Bernstein (delegation)
explicit ChebyshevSum ( const Bernstein& poly ) ;
/// constructor from Legendre (delegation)
explicit ChebyshevSum ( const LegendreSum& poly ) ;
// ======================================================================
public:
// ======================================================================
/// get the value
double evaluate ( const double x ) const ;
/// get the value
double operator () ( const double x ) const
{ return x < m_xmin ? 0 : x > m_xmax ? 0 : evaluate ( x ) ; }
// ======================================================================
public:
// ======================================================================
/// get lower edge
double xmin () const { return m_xmin ; }
/// get upper edge
double xmax () const { return m_xmax ; }
// ======================================================================
public:
// ======================================================================
double x ( const double t ) const
{ return 0.5 * ( t * ( m_xmax - m_xmin ) + m_xmax + m_xmin ) ; }
double t ( const double x ) const
{ return ( 2 * x - m_xmax - m_xmin ) / ( m_xmax - m_xmin ) ; }
// ======================================================================
public:
// ======================================================================
/// get the integral between xmin and xmax
double integral () const ;
/// get the integral between low and high
double integral ( const double low , const double high ) const ;
/// get the derivative at point "x"
double derivative ( const double x ) const ;
// ======================================================================
public:
// ======================================================================
/// get indefinte integral
ChebyshevSum indefinite_integral ( const double C = 0 ) const ;
/// get the derivative
ChebyshevSum derivative () const ;
// ======================================================================
public:
// ======================================================================
/** update the Chebyshev expansion by addition of one "event" with
* the given weight
* @code
* chebsjevSum sum = ... ;
* for ( auto x : .... ) { sum.fill ( x ) ; }
* @endcode
* This is a useful function to make an unbinned parameterization
* of certain distribution and/or efficiency
* @parameter x the event content
* @parameter weight the weight
*/
bool fill ( const double x , const double weight = 1 ) ;
bool Fill ( const double x , const double weight = 1 ) { return fill ( x , weight ) ; }
// ======================================================================
public:
// ======================================================================
/// simple manipulations with polynoms: shift it!
ChebyshevSum& operator += ( const double a ) ;
/// simple manipulations with polynoms: shift it!
ChebyshevSum& operator -= ( const double a ) ;
/// simple manipulations with polynoms: scale it!
ChebyshevSum& operator *= ( const double a ) ;
/// simple manipulations with polynoms: scale it!
ChebyshevSum& operator /= ( const double a ) ;
// ======================================================================
public:
// ======================================================================
/// negate it!
ChebyshevSum operator-() const ; // negate it!
// ======================================================================
public:
// ======================================================================
/// add chebyshev sum (with the same domain)
ChebyshevSum sum ( const ChebyshevSum& other ) const ;
/// subtract chebyshev sum (with the same domain)
ChebyshevSum subtract ( const ChebyshevSum& other ) const ;
// ======================================================================
public:
// ======================================================================
/// add chebyshev sum (with the same domain)
ChebyshevSum& isum ( const ChebyshevSum& other ) ;
/// subtract chebyshev sum (with the same domain)
ChebyshevSum& isub ( const ChebyshevSum& other ) ;
// ======================================================================
public:
// ======================================================================
inline ChebyshevSum& operator+=( const ChebyshevSum& other ) { return isum ( other ) ; }
inline ChebyshevSum& operator-=( const ChebyshevSum& other ) { return isub ( other ) ; }
// ======================================================================
public:
// ======================================================================
ChebyshevSum& __iadd__ ( const double a ) ;
ChebyshevSum& __isub__ ( const double a ) ;
ChebyshevSum& __imul__ ( const double a ) ;
ChebyshevSum& __itruediv__ ( const double a ) ;
ChebyshevSum& __idiv__ ( const double a ) { return __itruediv__ ( a ) ; }
// ======================================================================
public:
// ======================================================================
ChebyshevSum __add__ ( const double a ) const ;
ChebyshevSum __sub__ ( const double a ) const ;
ChebyshevSum __mul__ ( const double a ) const ;
ChebyshevSum __truediv__ ( const double a ) const ;
ChebyshevSum __div__ ( const double a ) { return __truediv__ ( a ) ; }
// ======================================================================
public:
// ======================================================================
ChebyshevSum __radd__ ( const double a ) const ;
ChebyshevSum __rsub__ ( const double a ) const ;
ChebyshevSum __rmul__ ( const double a ) const ;
// ======================================================================
public:
// ======================================================================
ChebyshevSum __add__ ( const ChebyshevSum& a ) const ;
ChebyshevSum __sub__ ( const ChebyshevSum& a ) const ;
// ======================================================================
public:
// ======================================================================
ChebyshevSum& __iadd__ ( const ChebyshevSum& a ) { return isum ( a ) ; }
ChebyshevSum& __isub__ ( const ChebyshevSum& a ) { return isub ( a ) ; }
// ======================================================================
public:
// ======================================================================
// negate it!
ChebyshevSum __neg__ () const ; // negate it!
// ======================================================================
public:
// ======================================================================
/// get unique tag
std::size_t tag() const ; // get unique tag
// ======================================================================
private:
// ======================================================================
/// x-min
double m_xmin ; // x-min
/// x-max
double m_xmax ; // x-max
// ======================================================================
} ;
// ========================================================================
inline ChebyshevSum operator+( const ChebyshevSum& a , const ChebyshevSum& b )
{ return a.sum ( b ) ; }
inline ChebyshevSum operator-( const ChebyshevSum& a , const ChebyshevSum& b )
{ return a.subtract ( b ) ; }
inline ChebyshevSum operator+( const ChebyshevSum& a , const double b )
{ return a.__add__ ( b ) ; }
inline ChebyshevSum operator+( const double b , const ChebyshevSum& a )
{ return a.__add__ ( b ) ; }
inline ChebyshevSum operator-( const ChebyshevSum& a , const double b )
{ return a.__sub__ ( b ) ; }
inline ChebyshevSum operator-( const double b , const ChebyshevSum& a )
{ return a.__rsub__ ( b ) ; }
inline ChebyshevSum operator*( const ChebyshevSum& a , const double b )
{ return a.__mul__ ( b ) ; }
inline ChebyshevSum operator*( const double b , const ChebyshevSum& a )
{ return a.__mul__ ( b ) ; }
inline ChebyshevSum operator/( const ChebyshevSum& a , const double b )
{ return a.__truediv__ ( b ) ; }
// ========================================================================
/** @class LegendreSum
* Sum of Legendre polinomials
* \f$ f(x) = \sum_i p_i P_i(x)\f$
* @author Vanya BELYAEV Ivan.Belyaev@itep.ru
* @date 2015-02-22
*/
class LegendreSum : public PolySum
{
public:
// =====================================================================
/// constructor from the degree
LegendreSum
( const unsigned short degree = 0 ,
const double xmin = -1 ,
const double xmax = 1 ) ;
// ======================================================================
/// constructor from the parameter list
LegendreSum
( const std::vector<double>& pars ,
const double xmin = -1 ,
const double xmax = 1 ) ;
/// template constructor from sequence of parameters
template <class ITERATOR,
typename value_type = typename std::iterator_traits<ITERATOR>::value_type,
typename = std::enable_if<std::is_convertible<value_type,long double>::value> >
LegendreSum
( ITERATOR first ,
ITERATOR last ,
const double xmin ,
const double xmax )
: Ostap::Math::PolySum ( first , last )
, m_xmin ( std::min ( xmin, xmax ) )
, m_xmax ( std::max ( xmin, xmax ) )
{}
// ======================================================================
/// copy
LegendreSum ( const LegendreSum& ) = default ;
/// move
LegendreSum ( LegendreSum&& ) = default ;
// ======================================================================
/** constructor from Bernstein polinomial (efficient)
* @see http://www.sciencedirect.com/science/article/pii/S0377042700003769 eq.21
*/
explicit LegendreSum ( const Bernstein& poly ) ;
/// constructor from polynoimial (delegation)
explicit LegendreSum ( const Polynomial& poly ) ;
/// constructor from Chebyshev (delegation)
explicit LegendreSum ( const ChebyshevSum& poly ) ;
// ======================================================================
public:
// ======================================================================
/// get the value
double evaluate ( const double x ) const ;
/// get the value
double operator () ( const double x ) const
{ return x < m_xmin ? 0 : x > m_xmax ? 0 : evaluate ( x ) ; }
// ======================================================================
public:
// ======================================================================
/// get lower edge
double xmin () const { return m_xmin ; }
/// get upper edge
double xmax () const { return m_xmax ; }
// ======================================================================
public:
// ======================================================================
double x ( const double t ) const
{ return 0.5 * ( t * ( m_xmax - m_xmin ) + m_xmax + m_xmin ) ; }
double t ( const double x ) const
{ return ( 2 * x - m_xmax - m_xmin ) / ( m_xmax - m_xmin ) ; }
// ======================================================================
public:
// ======================================================================
/// get the integral between xmin and xmax
double integral () const ;
/// get the integral between low and high
double integral ( const double low , const double high ) const ;
/// get the derivative at point "x"
double derivative ( const double x ) const ;
// ======================================================================
public:
// ======================================================================
/// get indefinte integral
LegendreSum indefinite_integral ( const double C = 0 ) const ;
/// get the derivative
LegendreSum derivative () const ;
// ======================================================================
public:
// ======================================================================
/// simple manipulations with polynoms: shift it!
LegendreSum& operator += ( const double a ) ;
/// simple manipulations with polynoms: shift it!
LegendreSum& operator -= ( const double a ) ;
/// simple manipulations with polynoms: scale it
LegendreSum& operator *= ( const double a ) ;
/// simple manipulations with polynoms: scale it
LegendreSum& operator /= ( const double a ) ;
// ======================================================================
public:
// ======================================================================
/// negate it!
LegendreSum operator-() const ; // negate it!
// ======================================================================
public:
// ======================================================================
/// add legendre sum (with the same domain)
LegendreSum sum ( const LegendreSum& other ) const ;
/// subtract legendre sum (with the same domain)
LegendreSum subtract ( const LegendreSum& other ) const ;
// =======================================================================
public:
// =======================================================================
/// add legendre sum (with the same domain)
LegendreSum& isum ( const LegendreSum& other ) ;
/// subtract legendre sum (with the same domain)
LegendreSum& isub ( const LegendreSum& other ) ;
// ======================================================================
public:
// ======================================================================
inline LegendreSum& operator+=( const LegendreSum& other ) { return isum ( other ) ; }
inline LegendreSum& operator-=( const LegendreSum& other ) { return isub ( other ) ; }
// ======================================================================
public:
// ======================================================================
LegendreSum& __iadd__ ( const double a ) ;
LegendreSum& __isub__ ( const double a ) ;
LegendreSum& __imul__ ( const double a ) ;
LegendreSum& __itruediv__ ( const double a ) ;
LegendreSum& __idiv__ ( const double a ) { return __itruediv__ ( a ) ; }
// ======================================================================
public:
// ======================================================================
LegendreSum __add__ ( const double a ) const ;
LegendreSum __sub__ ( const double a ) const ;
LegendreSum __mul__ ( const double a ) const ;
LegendreSum __truediv__ ( const double a ) const ;
LegendreSum __div__ ( const double a ) { return __truediv__ ( a ) ; }
// ======================================================================
public:
// ======================================================================
LegendreSum __radd__ ( const double a ) const ;
LegendreSum __rsub__ ( const double a ) const ;
LegendreSum __rmul__ ( const double a ) const ;
// ======================================================================
public:
// ======================================================================
LegendreSum __add__ ( const LegendreSum& a ) const ;
LegendreSum __sub__ ( const LegendreSum& a ) const ;
// ======================================================================
LegendreSum& __iadd__ ( const LegendreSum& a ) { return isum ( a ) ; }
LegendreSum& __isub__ ( const LegendreSum& a ) { return isub ( a ) ; }
// ======================================================================
public:
// ======================================================================
// negate it!
LegendreSum __neg__ () const ; // negate it!
// ======================================================================
public:
// ======================================================================
/** update the Legendre expansion by addition of one "event" with
* the given weight
* @code
* LegendreSum sum = ... ;
* for ( auto x : .... ) { sum.fill ( x ) ; }
* @endcode
* This is a useful function to make an unbinned parameterization
* of certain distribution and/or efficiency
* @parameter x the event content
* @parameter weight the weight
*/
bool fill ( const double x , const double weight = 1 ) ;
bool Fill ( const double x , const double weight = 1 ) { return fill ( x , weight ) ; }
// ======================================================================
public:
// ======================================================================
/// get unique tag
std::size_t tag() const ; // get unique tag
// ======================================================================
private:
// ======================================================================
/// x-min
double m_xmin ; // x-min
/// x-max
double m_xmax ; // x-max
// ======================================================================
} ;
// ========================================================================
inline LegendreSum operator+( const LegendreSum& a , const LegendreSum& b )
{ return a.sum ( b ) ; }
inline LegendreSum operator-( const LegendreSum& a , const LegendreSum& b )
{ return a.subtract ( b ) ; }
inline LegendreSum operator+( const LegendreSum& a , const double b )
{ return a.__add__ ( b ) ; }
inline LegendreSum operator+( const double b , const LegendreSum& a )
{ return a.__add__ ( b ) ; }
inline LegendreSum operator-( const LegendreSum& a , const double b )
{ return a.__sub__ ( b ) ; }
inline LegendreSum operator-( const double b , const LegendreSum& a )
{ return a.__rsub__ ( b ) ; }
inline LegendreSum operator*( const LegendreSum& a , const double b )
{ return a.__mul__ ( b ) ; }
inline LegendreSum operator*( const double b , const LegendreSum& a )
{ return a.__mul__ ( b ) ; }
inline LegendreSum operator/( const LegendreSum& a , const double b )
{ return a.__truediv__ ( b ) ; }
// ========================================================================
/** @class HermiteSum
* Sum of Hermite polinomials
* \f$ f(x) = \sum_i p_i He_i(x)\f$
* @author Vanya BELYAEV Ivan.Belyaev@itep.ru
* @date 2015-08-08
*/
class HermiteSum : public PolySum
{
public:
// =====================================================================
/// constructor from the degree
HermiteSum
( const unsigned short degree = 0 ,
const double xmin = -1 ,
const double xmax = 1 ) ;
// ======================================================================
/// constructor from the parameter list
HermiteSum
( const std::vector<double>& pars ,
const double xmin = -1 ,
const double xmax = 1 ) ;
/// template constructor from sequence of parameters
template <class ITERATOR,
typename value_type = typename std::iterator_traits<ITERATOR>::value_type,
typename = std::enable_if<std::is_convertible<value_type,long double>::value> >
HermiteSum
( ITERATOR first ,
ITERATOR last ,
const double xmin ,
const double xmax )
: Ostap::Math::PolySum ( first , last )
, m_xmin ( std::min ( xmin, xmax ) )
, m_xmax ( std::max ( xmin, xmax ) )
, m_scale ( 1 )
{
m_scale /= ( m_xmax - m_xmin ) ;
}
// ======================================================================
public:
// ======================================================================
/// get the value
double evaluate ( const double x ) const ;
/// get the value
double operator () ( const double x ) const ;
// ======================================================================
public:
// ======================================================================
/// get lower edge
double xmin () const { return m_xmin ; }
/// get upper edge
double xmax () const { return m_xmax ; }
// ======================================================================
public:
// ======================================================================
double x ( const double t ) const
{ return 0.5 * ( t / m_scale + m_xmin + m_xmax ) ; }
double t ( const double x ) const
{ return m_scale * ( 2 * x - m_xmin - m_xmax ) ; }
// ======================================================================
public:
// ======================================================================
/// get the integral between low and high
double integral ( const double low , const double high ) const ;
/// get the derivative at point "x"
double derivative ( const double x ) const ;
// ======================================================================
public:
// ======================================================================
/// get indefinte integral
HermiteSum indefinite_integral ( const double C = 0 ) const ;
/// get the derivative
HermiteSum derivative () const ;
// ======================================================================
public:
// ======================================================================
/// simple manipulations with polynoms: shift it!
HermiteSum& operator += ( const double a ) ;
/// simple manipulations with polynoms: shift it!
HermiteSum& operator -= ( const double a ) ;
/// simple manipulations with polynoms: scale it!
HermiteSum& operator *= ( const double a ) ;
/// simple manipulations with polynoms: scale it!
HermiteSum& operator /= ( const double a ) ;
// ======================================================================
public:
// ======================================================================
/// negate it!
HermiteSum operator-() const ; // negate it!
// ======================================================================
public:
// ======================================================================
/// add legendre sum (with the same domain)
HermiteSum sum ( const HermiteSum& other ) const ;
/// subtract legendre sum (with the same domain)
HermiteSum subtract ( const HermiteSum& other ) const ;
// ======================================================================
public:
// =======================================================================
/// add legendre sum (with the same domain)
HermiteSum& isum ( const HermiteSum& other ) ;
/// subtract legendre sum (with the same domain)
HermiteSum& isub ( const HermiteSum& other ) ;
// ======================================================================
public:
// ======================================================================
inline HermiteSum& operator+=( const HermiteSum& other ) { return isum ( other ) ; }
inline HermiteSum& operator-=( const HermiteSum& other ) { return isub ( other ) ; }
// ======================================================================
public:
// ======================================================================
public:
// ======================================================================
HermiteSum& __iadd__ ( const double a ) ;
HermiteSum& __isub__ ( const double a ) ;
HermiteSum& __imul__ ( const double a ) ;
HermiteSum& __itruediv__ ( const double a ) ;
HermiteSum& __idiv__ ( const double a ) { return __itruediv__ ( a ) ; }
// ======================================================================
public:
// ======================================================================
HermiteSum __add__ ( const double a ) const ;
HermiteSum __sub__ ( const double a ) const ;
HermiteSum __mul__ ( const double a ) const ;
HermiteSum __truediv__ ( const double a ) const ;
HermiteSum __div__ ( const double a ) { return __truediv__ ( a ) ; }
// ======================================================================
public:
// ======================================================================
HermiteSum __radd__ ( const double a ) const ;
HermiteSum __rsub__ ( const double a ) const ;
HermiteSum __rmul__ ( const double a ) const ;
// ======================================================================
public:
// ======================================================================
HermiteSum __add__ ( const HermiteSum& a ) const ;
HermiteSum __sub__ ( const HermiteSum& a ) const ;
// ======================================================================
HermiteSum& __iadd__ ( const HermiteSum& a ) { return isum ( a ) ; }
HermiteSum& __isub__ ( const HermiteSum& a ) { return isub ( a ) ; }
// ======================================================================
public:
// ======================================================================
// negate it!
HermiteSum __neg__ () const ; // negate it!
// ======================================================================
public:
// ======================================================================
/// get unique tag
std::size_t tag() const ; // get unique tag
// ======================================================================
private:
// ======================================================================
/// low edge
double m_xmin ; // low edge
/// high edge
double m_xmax ; // high edge
/// scale
double m_scale ; // scale
// ======================================================================
} ;
// ========================================================================
inline HermiteSum operator+( const HermiteSum& a , const HermiteSum& b )
{ return a.sum ( b ) ; }
inline HermiteSum operator-( const HermiteSum& a , const HermiteSum& b )
{ return a.subtract ( b ) ; }
inline HermiteSum operator+( const HermiteSum& a , const double b )
{ return a.__add__ ( b ) ; }
inline HermiteSum operator+( const double b , const HermiteSum& a )
{ return a.__add__ ( b ) ; }
inline HermiteSum operator-( const HermiteSum& a , const double b )
{ return a.__sub__ ( b ) ; }
inline HermiteSum operator-( const double b , const HermiteSum& a )
{ return a.__rsub__ ( b ) ; }
inline HermiteSum operator*( const HermiteSum& a , const double b )
{ return a.__mul__ ( b ) ; }
inline HermiteSum operator*( const double b , const HermiteSum& a )
{ return a.__mul__ ( b ) ; }
inline HermiteSum operator/( const HermiteSum& a , const double b )
{ return a.__truediv__ ( b ) ; }
// ========================================================================
} // end of namespace Ostap::Math
// ==========================================================================
} // end of namespace Ostap
// ============================================================================
namespace Ostap
{
// ==========================================================================
namespace Math
{
// ========================================================================
// helper utilities for integration of product of polynomial and an exponent
// ========================================================================
/** get the integral between low and high for a product of Bernstein
* polynom and the exponential function with the exponent tau
* \f[ \int_{a}^{b} \mathcal{B} e^{\tau x } \mathrm{d}x \f]
* @param poly bernstein polynomial
* @param tau slope parameter for exponential
* @param a low integration range
* @param b high integration range
*/
double integrate
( const Ostap::Math::Bernstein& poly ,
const double tau ,
const double a ,
const double b ) ;
// ========================================================================
/** get the integral between low and high for a product of
* polynom and the exponential function with the exponent tau
* \f[ r = \int_{a}^{b} \mathcal{P} e^{\tau x } \mathrm{d}x \f]
* @param poly polynomial
* @param tau slope parameter for exponential
* @param a low integration range
* @param b high integration range
*/
double integrate
( const Ostap::Math::Polynomial& poly ,
const double tau ,
const double a ,
const double b ) ;
// ========================================================================
/** get the integral between low and high for a product of
* Chebyshev polynom and the exponential function with the exponent tau
* \f[ r = \int_{a}^{b} \mathcal{T} e^{\tau x } \mathrm{d}x \f]
* @param poly chebyshev polynomial
* @param tau slope parameter for exponential
* @param a low integration range
* @param b high integration range
*/
double integrate
( const Ostap::Math::ChebyshevSum& poly ,
const double tau ,
const double a ,
const double b ) ;
// ========================================================================
/** get the integral between low and high for a product of
* Legendre polynom and the exponential function with the exponent tau
* \f[ r = \int_{a}^{b} \mathcal{L} e^{\tau x } \mathrm{d}x \f]
* @param poly Legendre polynomial
* @param tau slope parameter for exponential
* @param a low integration range
* @param b high integration range
*/
double integrate
( const Ostap::Math::LegendreSum& poly ,
const double tau ,
const double a ,
const double b ) ;
// ========================================================================
// ========================================================================
// special cases:
// ========================================================================
// ========================================================================
/** get the integral between low and high for a product of
* polynom and the exponential function with the exponent tau
* \f[ r = \int_{a}^{b} \mathcal{P} e^{\tau x } \mathrm{d}x \f]
* @param poly polynomial
* @param tau slope parameter for exponential
*/
double integrate
( const Ostap::Math::Polynomial& poly ,
const double tau ) ;
// ========================================================================
// ========================================================================
/** construct chebyshev approximation for arbitrary function
* @param func the function
* @param x_min low edge
* @param x_max high edge
* @return Chebyshev approximation
* @see ChebyshevSum
* @code
* FUNC func = ...
* ChebyshevSum a = chebyshev_sum<6> ( func , x_min , x_max ) ;
* @endcode
*/
template <unsigned short N, class FUNCTION>
inline ChebyshevSum
chebyshev_sum
( FUNCTION func ,
const double x_min ,
const double x_max )
{
// array of precomputed function values
std::array<double,N> fv ;
//
const double xmin = std::min ( x_min , x_max ) ;
const double xmax = std::max ( x_min , x_max ) ;
//
const double xhs = 0.5 * ( xmin + xmax ) ;
const double xhd = 0.5 * ( xmax - xmin ) ;
const long double pi_N = M_PIl / N ;
auto _xi_ = [xhs,xhd,pi_N] ( const unsigned short k )
{ return std::cos ( pi_N * ( k + 0.5 ) ) * xhd + xhs ; } ;
for ( unsigned short i = 0 ; i < N ; ++i ) { fv[i] = func ( _xi_ ( i ) ) ; }
//
ChebyshevSum cs ( N , xmin , xmax ) ;
for ( unsigned short i = 0 ; i < N + 1 ; ++i )
{
double c_i = 0 ;
if ( 0 == i )
{ for ( unsigned short k = 0 ; k < N ; ++k ) { c_i += fv[k] ; } }
else
{
for ( unsigned short k = 0 ; k < N ; ++k )
{ c_i += fv[k] * std::cos ( pi_N * i * ( k + 0.5 ) ) ; }
}
c_i *= 2.0 / N ;
if ( 0 == i ) { c_i *= 0.5 ;}
cs.setPar ( i, c_i ) ;
}
return cs ;
}
// ========================================================================
/* construct chebyshev approximation for arbitrary function
* @param func the function
* @param N degree of polynomial
* @param x_min low edge
* @param x_max high edge
* @return Chebyshev approximation
* @see ChebyshevSum
* @code
* FUNC func = ...
* ChebyshevSum a = chebyshev_sum ( func , 10 , xmin , xmax ) ;
* @endcode
*/
ChebyshevSum
chebyshev_sum
( std::function<double(double)> func ,
const unsigned short N ,
const double x_min ,
const double x_max ) ;
// ========================================================================
} // end of namespace Ostap::Math
// ==========================================================================
} // end of namespace Ostap
// ============================================================================
// The END
// ============================================================================
#endif // OSTAP_POLYNOMIALS_H
// ============================================================================
| true |
a72098a79de626f902550dea519e953292d401da
|
C++
|
senshishiro/Mentoring
|
/linkedList/linkedList/list.cpp
|
UTF-8
| 9,277 | 3.6875 | 4 |
[] |
no_license
|
#include "stdafx.h"
#include "list.h"
using namespace std;
//==========================================================================
//Singly Linked List
//==========================================================================
//--------------------------------------------------------
//Constructor
SinglyList::SinglyList()
{
head = NULL;
size = 0;
}
//--------------------------------------------------------
//addNode
//BigO Analysis: O(N) - Goes through the list looking for the last node. Appends node at the end
void SinglyList::addNode(int data)
{
//create node
Node* n = new Node;
Node* current = head;
n->x = data;
n->next = NULL;
//if a list already exists
if (head != NULL)
{
//current = head;
//search for the last node of the list
while (current->next != NULL)
{
current = current->next;
}
current->next = n;
size++;
}
//set to head if a node doesn't exist
else
{
head = n;
size++;
}
}
//--------------------------------------------------------
//deleteNode
//BigO Analysis: O(N) - loops through the linked list once looking for matching value
void SinglyList::deleteNode(int data)
{
Node* current = head;
Node* previous = head;
//find node
while (current != NULL && current->x != data)
{
previous = current;
current = current->next;
}
//print error if there are no matches
if (current == NULL)
{
cerr << "error: " << data << " does not exist in the list.\n";
}
else
{
//update head if the first node is deleted
if (current == head)
{
head = head->next;
}
previous->next = current->next;
delete current;
size--;
cout << data << " was deleted from the list.\n";
}
}
//--------------------------------------------------------
//deleteAll - Goes through each node and deletes it
//BigO Analysis: O(N) - Only loops through once deleting each node.
void SinglyList::deleteAll()
{
Node* current = head;
while (current != NULL)
{
head = current->next;
delete current;
current = head;
}
//cout << "List has been emptied\n";
head = NULL;
size = 0;
}
//--------------------------------------------------------
// reverse list
//BigO Analysis: O(N) - Loops through the list rebuilding it in reverse
void SinglyList::reverseList()
{
Node* temp = NULL;
Node* current = head;
Node* previous = NULL;
while (current != NULL)
{
temp = current;
current = current->next;
temp->next = previous;
previous = temp;
}
//makes the last node in the loop the head
head = previous;
}
//--------------------------------------------------------
//printList
//BigO Analysis: O(N) - loops throught the list, and prints out data
void SinglyList::printList()
{
Node* current = head;
if (isEmpty())
{
cout << "The list is empty\n";
}
else
{
cout << "------------------\n";
while (current != NULL)
{
cout << current->x << endl;
current = current->next;
}
cout << "------------------\n";
}
}
//--------------------------------------------------------
//size
//BigO Analysis: O(N) - Loops through linked list counting all the nodes
int SinglyList::getSize()
{
return size;
}
//--------------------------------------------------------
//isEmpty
//BigO Analysis: O(1) - Checks if there is a head node
bool SinglyList::isEmpty()
{
if (head == NULL)
{
return true;
}
else
{
return false;
}
}
//==========================================================================
//Doubly Linked List
//==========================================================================
//--------------------------------------------------------
//Constructor
DoublyList::DoublyList()
{
first = NULL;
last = NULL;
size = 0;
}
//--------------------------------------------------------
//addNode - adds node to the end of the list
//BigO: O(1) - No loops. appends node to last.
void DoublyList::addNode(int data)
{
//create node
DoubleNode* n = new DoubleNode;
n->x = data;
n->next = NULL;
n->prev = NULL;
if (first != NULL)
{
//Add nodes to the end of the list
last->next = n;
n->prev = last;
last = n;
}
else
{
//first node in the list. set first and last.
first = n;
last = n;
}
size++;
}
//--------------------------------------------------------
//deleteNode
//BigO: O(N) - one loop that searches for the matching data to delete
void DoublyList::deleteNode(int data)
{
DoubleNode* endCurrent = last;
DoubleNode* current = first;
//search for node wioth matching data in the list - one pointer at the beginning and end, moving towards the middle.
while (current != NULL && current->x != data )
{
if (endCurrent->x == data)
{
//stop search when they reach the middle
current = endCurrent;
break;
}
else if (current == endCurrent)
{
current = NULL;
break;
}
current = current->next;
endCurrent = endCurrent->prev;
}
// No match value - value does not exist in the list
if (current == NULL)
{
cerr << "error: " << data << " does not exist in the list.\n";
//delete delNode;
}
else
{
//delNode = current;
//reaasign first node when it is about to be deleted
if (current == first)
{
first = first->next;
first->prev = NULL;
}
//reaasign last node when it is about to be deleted
else if (current == last)
{
last = last->prev;
last->next = NULL;
}
else
{
//Connect the two nodes adjacent to the deleted node
(current->next)->prev = current->prev;
(current->prev)->next = current->next;
}
delete current;
size--;
cout << data << " was deleted from the list.\n";
}
}
//--------------------------------------------------------
//deleteAll
//BigO: O(N) - One loop that goes through each node in the list and delete it
void DoublyList::deleteAll()
{
DoubleNode* current = first;
while (current != NULL)
{
first = first->next;
delete current;
current = first;
}
//reset nodes
first = NULL;
last = NULL;
size = 0;
}
//--------------------------------------------------------
// reverseList
//BigO Analysis: O(N) - Loops through the list swapping the prev and next pointers
void DoublyList::reverseList()
{
DoubleNode* previous = NULL;
DoubleNode* current = first;
while (current != NULL)
{
//swap previous and next pointers
previous = current->prev;
current->prev = current->next;
current->next = previous;
//update the first node to last
if (current->next == NULL)
{
last = current;
//cout << "set last: "<< current->x << "\n";
}
//update the last node to first
else if (current->prev == NULL)
{
first = current;
//cout << "set first: " << current->x << "\n";
}
//advanced pointer by going "backwards", since they were flipped
current = current->prev;
}
}
//--------------------------------------------------------
//printList - prints from first node to last.
//BigO: O(N) - one loop goes through each loop, and prints out the data.
void DoublyList::printList()
{
DoubleNode* current = first;
if (isEmpty())
{
cout << "The list is empty\n";
}
else
{
cout << "------------------\n";
while (current != NULL)
{
cout << current->x << endl;
current = current->next;
}
cout << "------------------\n";
}
}
//--------------------------------------------------------
//printListReverse - print from last node to first.
//BigO: O(N) - one loop goes through each loop, and prints out the data.
void DoublyList::printListReverse()
{
DoubleNode* current = last;
if (isEmpty())
{
cout << "The list is empty\n";
}
else
{
cout << "------------------\n";
while (current != NULL)
{
cout << current->x << endl;
current = current->prev;
}
cout << "------------------\n";
}
}
//--------------------------------------------------------
//size
//BigO Analysis: O(1) - calls size from class
int DoublyList::getSize()
{
return size;
}
//--------------------------------------------------------
//isEmpty
//BigO: O(1) - one comparison that checks if the first node exists.
bool DoublyList::isEmpty()
{
if (first == NULL)
{
return true;
}
else
{
return false;
}
}
/*
//--------------------------------------------------------
//swap
//BigO:
void DoublyList::swap(DoubleNode* a, DoubleNode* b)
{
DoubleNode* temp = new DoubleNode;
cout << "first " << a->x << " second "<< b->x <<endl;
cout << "first " << a->next << " second " << b->next << endl;
//temp = a;
temp->prev = a->prev;
temp->next = a->next;
//a->x = b->x;
a->prev = b->prev;
a->next = b->next;
//b = temp;
b->prev = temp->prev;
b->next = temp->next;
//delete temp;
cout << "first " << a->x << " second " << b->x << endl;
cout << "first " << a->next << " second " << b->next << endl;
}
//--------------------------------------------------------
//sort
//BigO:
void DoublyList::sort()
{
DoubleNode* current = first;
DoubleNode* inner = first;
DoubleNode* min = first;
DoubleNode* temp = new DoubleNode;
//DoubleNode* temp->prev = NULL;
//int min = first->x;
while (current != NULL)
{
min = current;
inner = current->next;
while (inner != NULL)
{
if (min->x > inner->x)
{
min = inner;
}
inner = inner->next;
}
if (min->x < current->x)
{
swap(min, current);
}
if (min->x < first->x)
{
first = min;
}
//current = current->next;
}
}
*/
| true |
edfbb8d896dd6e1cf7983f305e8de01b991e39d1
|
C++
|
ThomasCol/MathLibrary
|
/MathLib/MathLib/Src/Geometry/Cylinder.cpp
|
UTF-8
| 1,028 | 2.96875 | 3 |
[] |
no_license
|
#include "Cylinder.h"
namespace Math::Geometry
{
#pragma region Constructors
QXcylinder::QXcylinder(const QXsegment& segment, const QXfloat& radius) noexcept:
_segment(segment),
_radius{radius}
{}
QXcylinder::QXcylinder(const QXcylinder& cylinder) noexcept:
_segment(cylinder._segment),
_radius{cylinder._radius}
{}
QXcylinder::QXcylinder(QXcylinder&& cylinder) noexcept:
_segment(std::move(cylinder._segment)),
_radius{std::move(cylinder._radius)}
{}
#pragma endregion Constructors
#pragma region Functions
#pragma region Operators
QXcylinder& QXcylinder::operator=(const QXcylinder& cylinder) noexcept
{
_segment = cylinder._segment;
_radius = cylinder._radius;
return *this;
}
QXcylinder& QXcylinder::operator=(QXcylinder&& cylinder) noexcept
{
_segment = std::move(cylinder._segment);
_radius = std::move(cylinder._radius);
return *this;
}
#pragma endregion Operators
#pragma region Statics Functions
#pragma endregion Statics Functions
#pragma endregion Functions
}
| true |
3752ffe94580e125ee4b563ab0ef14fe3c669d43
|
C++
|
tupieurods/SportProgramming
|
/CR251/CR251_B/main.cpp
|
UTF-8
| 704 | 2.578125 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#pragma warning(disable: 4996)
using namespace std;
int n, x;
__int64 c[100009];
void ReadData()
{
scanf("%d %d", &n, &x);
for(int i = 0; i < n; i++)
{
scanf("%I64d", &c[i]);
}
}
__int64 answer;
void Solve()
{
answer = 0;
sort(c, c + n);
for(int i = 0; i < n; i++)
{
answer += c[i] * x;
if(x != 1)
{
x--;
}
}
}
void WriteData()
{
printf("%I64d\n", answer);
}
int main()
{
int QWE = 1;
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
scanf("%d", &QWE);
#endif
for(int T = 0; T < QWE; T++)
{
ReadData();
Solve();
WriteData();
}
return 0;
}
| true |
3d3609c21d5ec559f3fe8b30aee7e2f1f3d2ab9a
|
C++
|
xunzhang/lcode
|
/lintcode/binary-tree-serialization.cc
|
UTF-8
| 1,686 | 3.5625 | 4 |
[] |
no_license
|
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* This method will be invoked first, you should design your own
* algorithm
* to serialize a binary tree which denote by a root node to a
* string which
* can be easily deserialized by your own "deserialize"
* method later.
*/
string serialize(TreeNode *root) {
// write your code here
if(root == NULL) return "";
string str;
dump_vlr(root, str);
return str;
}
/**
* This method will be invoked second, the argument data is what
* exactly
* you serialized at method "serialize", that means the
* data is not given by
* system, it's given by your own serialize method. So
* the format of data is
* designed by yourself, and deserialize it here
* as you serialize it in
* "serialize" method.
*/
TreeNode *deserialize(string data) {
// write your code here
if(data.size() == 0) return NULL;
TreeNode *p;
load_vlr(p, data);
return p;
}
private:
void dump_vlr(TreeNode *p, string & str) {
if(p == NULL) { str.push_back('#'); return; }
str.push_back(p->val + 'a');
dump_vlr(p->left, str);
dump_vlr(p->right, str);
}
void load_vlr(TreeNode *&p, string & str) {
if(str.size() == 0) return;
if(str[0] == '#') { str = str.substr(1, str.size() - 1); return; }
p = new TreeNode(str[0] - 'a');
str = str.substr(1, str.size() - 1);
load_vlr(p->left, str);
load_vlr(p->right, str);
}
};
| true |
9f293cc153076ccaef1bd2e88e5857c127db0ee8
|
C++
|
NewYaroslav/xtechnical_analysis
|
/include/xtechnical_streaming_min_max.hpp
|
UTF-8
| 5,511 | 2.9375 | 3 |
[
"MIT"
] |
permissive
|
#ifndef XTECHNICAL_STREAMING_MIN_MAX_HPP_INCLUDED
#define XTECHNICAL_STREAMING_MIN_MAX_HPP_INCLUDED
#include <deque>
namespace xtechnical {
/** \brief Streaming Maximum-Minimum Filter Using No More than Three Comparsions per Element.
* URL: https://zelych.livejournal.com/2692.html
* URL: https://arxiv.org/abs/cs/0610046v5
* URL: https://arxiv.org/pdf/cs/0610046v5.pdf
* \param a Input array
* \param minval Output array
* \param maxval Output array
* \param w Window length
*/
template<class T>
void streaming_maximum_minimum_filter(T &a, T &minval, T &maxval, const size_t w) {
std::deque<int> U, L;
for (size_t i = 1; i < a.size(); ++i) {
if (i >= w) {
maxval[i - w] = a[U.size() > 0 ? U.front() : i - 1];
minval[i - w] = a[L.size() > 0 ? L.front() : i - 1];
} // end if
if (a[i] > a[i - 1]) {
L.push_back(i - 1);
if (i == w + L.front()) L.pop_front();
while (U.size() > 0) {
if (a[i] <= a[U.back()]) {
if (i == w + U.front()) U.pop_front();
break;
} // end if
U.pop_back();
} // end while
} else {
U.push_back(i - 1) ;
if (i == w + U.front()) U.pop_front();
while (L.size() > 0) {
if (a[i] >= a[L.back()]) {
if (i == w + L.front()) L.pop_front();
break;
} // end if
L.pop_back();
} // end while
} // end if else
} // end for
maxval[a.size() - w] = a[U.size() > 0 ? U.front() : a.size() - 1];
minval[a.size() - w] = a[L.size() > 0 ? L.front() : a.size() - 1];
}
/** \brief Streaming Maximum-Minimum Filter Using No More than Three Comparsions per Element.
* URL: https://zelych.livejournal.com/2692.html
* URL: https://arxiv.org/abs/cs/0610046v5
* URL: https://arxiv.org/pdf/cs/0610046v5.pdf
* \param window Input array
* \param minval Output value
* \param maxval Output value
*/
template<class T, class T2>
void streaming_maximum_minimum_filter(T &window, T2 &minval, T2 &maxval) {
std::deque<int> U, L;
const size_t w = window.size();
for (size_t i = 1; i < w; ++i) {
if (window[i] > window[i - 1]) {
L.push_back(i - 1) ;
if (i == w + L.front()) L.pop_front();
while (U.size() > 0) {
if (window[i] <= window[U.back()]) {
if (i == w + U.front()) U.pop_front();
break;
} // end if
U.pop_back();
} // end while
} else {
U.push_back(i - 1);
if (i == w + U.front()) U.pop_front();
while (L.size() > 0) {
if (window[i] >= window[L.back()]) {
if (i == w + L.front()) L.pop_front();
break;
} // end if
L.pop_back();
} // end while
} // end if else
} // end for
maxval = window[U.size() > 0 ? U.front() : w - 1];
minval = window[L.size() > 0 ? L.front() : w - 1];
}
template<class T>
class StreamingMaximumMinimumFilter {
private:
T maxval = std::numeric_limits<T>::quiet_NaN(), minval = std::numeric_limits<T>::quiet_NaN();
T last_input = 0;
int64_t period = 0;
int64_t offset = 0;
std::deque<std::pair<int64_t, T>> U, L;
public:
StreamingMaximumMinimumFilter(const int64_t p) : period(p) {}
void update(const T input) noexcept {
if (offset == 0) {
++offset;
last_input = input;
return;
}
if (input > last_input) {
L.push_back(std::make_pair(offset - 1, last_input));
if (offset == period + L.front().first) L.pop_front() ;
while (U.size() > 0) {
if (input <= U.back().second) {
if (offset == period + U.front().first) U.pop_front();
break ;
} // end if
U.pop_back() ;
} // end while
} else {
U.push_back(std::make_pair(offset - 1, last_input)) ;
if (offset == period + U.front().first) U.pop_front() ;
while (L.size() > 0) {
if (input >= L.back().second) {
if (offset == period + L.front().first) L.pop_front();
break ;
} // end if
L.pop_back();
} // end while
} // end if else
++offset;
if (offset >= period) {
maxval = U.size() > 0 ? U.front().second : input;
minval = L.size() > 0 ? L.front().second : input;
}
last_input = input;
}
inline T get_min() noexcept {
return minval;
}
inline T get_max() noexcept {
return maxval;
}
};
};
#endif // XTECHNICAL_STREAMING_MIN_MAX_HPP_INCLUDED
| true |
6b8b3b19af318add71dd74e4bedd5ec81a65755e
|
C++
|
Rajanarender/Hanuman
|
/Study/StandardTemplateLibrary_STL/setmultisetunorderedsetDiff.cpp
|
UTF-8
| 2,132 | 3.59375 | 4 |
[] |
no_license
|
#include<iostream>
using namespace std;
#include<set> //set,multiset
#include<unordered_set> //unordered_set,supported only in C++11
#include<algorithm> //find(),count() are not members of set
/***********************************************************************
Example:
1
4
1
6
set:
unique sorted elements
Header:#include<set>
Implementation: BST
If the element is repeated once or more,then it takes the very first element data only and rejects the older data.
It displays the elements in sorted order
O/p of above Example:
1
4
6
multiset:
duplicate sorted elements
Header:#include<set>
Implementation: BST
If the element is repeated once or more,then it takes the very latest element data only and rejects the older data.
It displays the elements in sorted order
O/p of above Example:
1
1
4
6
unordered_set:
unique unsorted elements
Header:#include<unordered_set> //C++11
Implementation: BST
If the element is repeated once or more,then it takes the very latest element data only and rejects the older data.
It displays the elements in UNsorted order
O/p of above Example:
6
4
1
************************************************************************/
int main()
{
#if 0
set<int>s;
set<int>::iterator it;
s.insert(1);
s.insert(4);
s.insert(1);//This is not taken into set,since it is repeated
s.insert(6);
#endif
#if 1
multiset<int>s;
multiset<int>::iterator it;
s.insert(1);
s.insert(4);
s.insert(1);
s.insert(6);
for(int i=1;i<7;i++)
{
if(count(s.begin(),s.end(),i)>1)
{
cout<<"multiset is having duplicate element: "<<i<<endl;
cout<<"Element is repeated:"<<count(s.begin(),s.end(),i)<<"times"<<endl;
}
if(count(s.begin(),s.end(),i) == 0)
{
cout<<"multiset is not having element: "<<i<<endl;
}
}
#endif
#if 0
unordered_set<int>s; //C++11 only
unordered_set<int>::iterator it;
s.insert(1);
s.insert(4);
s.insert(1);
s.insert(6);
#endif
s.erase(4); //deletes only 4
//s.erase(s.find(4),s.find(6)); //Deleting elements from value 4 to 6[excluding 6],V.V.Imp step
for(it=s.begin();it !=s.end();it++)
{
cout<<*it<<endl; //dereference iterator
}
}
| true |
d0025d2db75bd18178aea3cd6384929b859ea274
|
C++
|
acmol/toft
|
/net/uri/uri.h
|
UTF-8
| 8,564 | 2.6875 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
// Copyright (c) 2011, The Toft Authors.
// All rights reserved.
//
// Author: CHEN Feng <chen3feng@gmail.com>
// Created: 05/11/11
// Description: URI class, based on RFC 3986
#ifndef TOFT_NET_URI_URI_H
#define TOFT_NET_URI_URI_H
#include <cassert>
#include <string>
#include <utility>
#include "toft/base/string/string_piece.h"
namespace toft {
class UriAuthority
{
friend class URI;
public:
UriAuthority():
m_has_user_info(false),
m_has_port(false)
{
}
public: // Attributes
bool HasUserInfo() const { return m_has_user_info; }
const std::string& UserInfo() const {
assert(m_has_user_info);
return m_user_info;
}
void SetUserInfo(const std::string& value) {
m_user_info = value;
m_has_user_info = true;
}
void SetUserInfo(const char* value) {
m_user_info = value;
m_has_user_info = true;
}
void SetUserInfo(const char* value, size_t length)
{
m_user_info.assign(value, length);
m_has_user_info = true;
}
void ClearUserInfo() {
m_user_info.clear();
m_has_user_info = false;
}
const std::string& Host() const { return m_host; }
void SetHost(const std::string& value) { m_host = value; }
void SetHost(const char* value) { m_host = value; }
void SetHost(const char* value, size_t length)
{
m_host.assign(value, length);
}
bool HasPort() const { return m_has_port; }
const std::string& Port() const {
assert(m_has_port);
return m_port;
}
void SetPort(const std::string& value) {
m_port = value;
m_has_port = true;
}
void SetPort(const char* value) {
m_port = value;
m_has_port = true;
}
void SetPort(const char* value, size_t length)
{
m_port.assign(value, length);
m_has_port = true;
}
void ClearPort() {
m_port.clear();
m_has_port = false;
}
void Clear()
{
ClearUserInfo();
m_host.clear();
ClearPort();
}
void Swap(UriAuthority* other) throw();
private:
bool m_has_user_info;
bool m_has_port;
std::string m_user_info;
std::string m_host;
std::string m_port;
};
// RFC 3986 URI class
class URI
{
public:
URI() :
m_has_authority(false),
m_has_query(false),
m_has_fragment(false)
{
}
public: // Attributes
// Scheme
const std::string& Scheme() const { return m_scheme; }
void SetScheme(const std::string& value) { m_scheme = value; }
void SetScheme(const char* value) { m_scheme = value; }
void SetScheme(const char* value, size_t length) { m_scheme.assign(value, length); }
// Authority
bool HasAuthority() const { return m_has_authority; }
UriAuthority& Authority() {
assert(m_has_authority);
return m_authority;
}
const UriAuthority& Authority() const {
assert(m_has_authority);
return m_authority;
}
void SetAuthority(const UriAuthority& value) {
m_has_authority = true;
m_authority = value;
}
void ClearAuthority() {
m_authority.Clear();
m_has_authority = false;
}
// UserInfo
bool HasUserInfo() const { return m_has_authority && m_authority.HasUserInfo(); }
const std::string& UserInfo() const {
assert(m_has_authority);
return Authority().UserInfo();
}
void SetUserInfo(const std::string& value)
{
m_has_authority = true;
m_authority.SetUserInfo(value);
}
void SetUserInfo(const char* value)
{
m_has_authority = true;
m_authority.SetUserInfo(value);
}
void SetUserInfo(const char* value, size_t length)
{
m_has_authority = true;
m_authority.SetUserInfo(value, length);
}
void ClearUserInfo() {
assert(m_has_authority);
m_authority.ClearUserInfo();
}
// Host
bool HasHost() const { return m_has_authority; }
const std::string& Host() const {
assert(m_has_authority);
return m_authority.Host();
}
void SetHost(const std::string& value)
{
m_has_authority = true;
m_authority.SetHost(value);
}
void SetHost(const char* value, size_t length)
{
m_has_authority = true;
m_authority.SetHost(value, length);
}
// Port
bool HasPort() const { return m_has_authority && m_authority.HasPort(); }
const std::string& Port() const {
assert(m_has_authority);
return m_authority.Port();
}
void SetPort(const std::string& value)
{
m_has_authority = true;
m_authority.SetPort(value);
}
void SetPort(const char* value, size_t length)
{
m_has_authority = true;
m_authority.SetPort(value, length);
}
void ClearPort() {
assert(m_has_authority);
m_authority.ClearPort();
}
// Path
const std::string& Path() const { return m_path; }
void SetPath(const std::string& value) { m_path = value; }
void SetPath(const char* value) { m_path = value; }
void SetPath(const char* value, size_t length)
{
m_path.assign(value, length);
}
// Query
bool HasQuery() const { return m_has_query; }
const std::string& Query() const { return m_query; }
void SetQuery(const std::string& value)
{
m_query = value;
m_has_query = true;
}
void SetQuery(const char* value)
{
m_query = value;
m_has_query = true;
}
void SetQuery(const char* value, size_t length)
{
m_query.assign(value, length);
m_has_query = true;
}
void ClearQuery() {
m_query.clear();
m_has_query = false;
}
std::string PathAndQuery() const { return HasQuery() ? Path() + "?" + Query() : Path(); }
// Fragment
bool HasFragment() const { return m_has_fragment; }
const std::string& Fragment() const { return m_fragment; }
void SetFragment(const std::string& value) {
m_fragment = value;
m_has_fragment = true;
}
void SetFragment(const char* value) {
m_fragment = value;
m_has_fragment = true;
}
void SetFragment(const char* value, size_t length)
{
m_fragment.assign(value, length);
m_has_fragment = true;
}
void ClearFragment() {
m_fragment.clear();
m_has_fragment = false;
}
public: // operations
std::string& ToString(std::string* result) const;
std::string ToString() const;
bool WriteToBuffer(char* buffer, size_t buffer_size, size_t* result_size) const;
bool WriteToBuffer(char* buffer, size_t buffer_size) const
{
size_t result_size; // ignore length
return WriteToBuffer(buffer, buffer_size, &result_size);
}
// clear to empty
void Clear();
// swap with other URI object
void Swap(URI* other) throw();
bool Normalize();
bool ToAbsolute(const URI& base);
// parse a length specified buffer
// return parsed length
size_t ParseBuffer(const char* uri, size_t uri_length);
bool Parse(const char* uri);
bool Parse(const std::string& uri)
{
return ParseBuffer(uri.data(), uri.length()) == uri.length();
}
bool Merge(const URI& base, bool strict = false);
// Same as encodeURI in javascript
static void Encode(const StringPiece& src, std::string* dest);
static std::string Encode(const StringPiece& src);
static void Encode(std::string* uri);
// Same as encodeURIComponent in javascript
static void EncodeComponent(const StringPiece& src, std::string* dest);
static std::string EncodeComponent(const StringPiece& src);
static void EncodeComponent(std::string* uri);
// Decode % encoding string
static bool Decode(const StringPiece& src, std::string* result);
private:
static void StringLower(std::string* str)
{
for (size_t i = 0; i < str->length(); ++i)
(*str)[i] = tolower((*str)[i]);
}
private:
bool m_has_authority;
bool m_has_query;
bool m_has_fragment;
std::string m_scheme;
UriAuthority m_authority;
std::string m_path;
std::string m_query;
std::string m_fragment;
};
} // namespace toft
// fit to STL
namespace std
{
template <>
inline void swap(toft::UriAuthority& x, toft::UriAuthority& y) throw()
{
x.Swap(&y);
}
template <>
inline void swap(toft::URI& x, toft::URI& y) throw()
{
x.Swap(&y);
}
} // namespace std
#endif // TOFT_NET_URI_URI_H
| true |
452b65d4507067654e1b16eb875e2dca38f1d8bc
|
C++
|
marcob90/CPP-Projects
|
/H/DeckOfCards.h
|
UTF-8
| 398 | 2.9375 | 3 |
[] |
no_license
|
#ifndef DECK
#define DECK
#include "Card.h"
#include <vector>
#include <algorithm>
class DeckOfCards
{
public:
static const int SIZE = 52;
DeckOfCards();
void shuffle();
Card &dealCard();
bool moreCards() const;
private:
typedef std::vector< Card > deck_t;
deck_t deck;
deck_t::iterator it;
int currentCard; //next card to deal
};
#endif
| true |
5befe813e8a93060ce69d418f6053c6051ec853a
|
C++
|
realfirst/ffcpp
|
/Matrix.cpp
|
UTF-8
| 3,524 | 3.84375 | 4 |
[] |
no_license
|
#include <iostream>
#include <cstdlib>
class Matrix {
int width, height;
double *data;
public:
Matrix();
Matrix(int w, int h);
Matrix(const Matrix &m);
~Matrix();
bool operator == (const Matrix &m) const;
Matrix &operator = (const Matrix &m);
Matrix operator + (const Matrix &m) const;
Matrix operator * (const Matrix &m) const;
double &operator () (int i, int j);
void print() const;
};
Matrix::Matrix() {
width = 0;
height = 0;
data = 0;
}
Matrix::Matrix(int w, int h) {
std::cout << " Matrix::Matrix(int w, int h)" << std::endl;
width = w;
height = h;
data = new double[width * height];
}
Matrix::Matrix(const Matrix &m) {
std::cout << " Matrix::Matrix(cosnt Matrix &m)" << std::endl;
width = m.width;
height = m.height;
data = new double[width * height];
for (int k = 0; k < width*height; k++) {
data[k] = m.data[k];
}
}
Matrix::~Matrix() {
std::cout << " Matrix::~Matrix()" << std::endl;
delete[] data;
}
Matrix &Matrix::operator = (const Matrix &m) {
std::cout << " Matrix &Matrix::operator = (const Matrix &m)" << std::endl;
if (&m != this) {
delete[] data;
width = m.width;
height = m.height;
data = new double[width * height];
for (int k = 0; k < width * height; k++) {
data[k] = m.data[k];
}
return *this;
}
}
bool Matrix::operator == (const Matrix &m) const {
std::cout << " bool Matrix::operator == (const Matrix &m) const" << std::endl;
if (width != m.width || height != m.height) {
return false;
}
for (int k = 0; k < width*height; k++) {
if (data[k] != m.data[k]) {
return false;
}
}
return true;
}
Matrix Matrix::operator + (const Matrix &m) const {
std::cout << " Matrix Matrix::operator + (const Matrix &m) const" << std::endl;
if (width != m.width || height != m.height) {
std::cerr << "Size error" << std::endl;
abort();
}
Matrix result(width, height);
for (int k = 0; k < width * height; k++) {
result.data[k] = data[k] + m.data[k];
}
return result;
}
Matrix Matrix::operator * (const Matrix &m) const {
std::cout << " Matrix Matrix::operator * (const Matrix &m) const" << std::endl;
if (width != m.height) {
std::cerr << "Size error!" << std::endl;
abort();
}
Matrix result(m.width, height);
for (int i = 0; i < m.width; i++) {
for (int j = 0; j < height; j++) {
double s = 0;
for (int k = 0; k < width; k++) {
s += data[k + j*width] * m.data[i + m.width*k];
}
result.data[i + m.width*j] = s;
}
}
return result;
}
double &Matrix::operator () (int i, int j) {
std::cout << " double &Matrix::operator () (int i, int j)" << std::endl;
if (i < 0 || i >= width || j < 0 || j >= height) {
std::cerr << "Out of bounds!" << std::endl;
abort();
}
return data[i + width*j];
}
void Matrix::print() const {
std::cout << " void print() const" << std::endl;
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
std::cout << " " << data[i + width*j];
}
std::cout << std::endl;
}
}
int main(int argc, char **argv) {
std::cout << "DOING Matirx m(3, 2), n(5, 3);" << std::endl;
Matrix m(3, 2), n(5, 3);
std::cout << "DOING Matirx x = m*n;" << std::endl;
Matrix x = m*n;
std::cout << "DOING m.print();" << std::endl;
m.print();
std::cout << "DOING m = n;" << std::endl;
n = m;
std::cout << "DOING n.print();" << std::endl;
n.print();
std::cout << "DOING x.print();" << std::endl;
x.print();
return 0;
}
| true |
94e158b47e1622daf77c5522b82b80fc3630b1d3
|
C++
|
ishsum/cpp-oops
|
/q7.cpp
|
UTF-8
| 914 | 3.34375 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
class emp
{
protected:
int eno;
char name[20],des[20];
public:
void get();
};
void emp::get()
{
cout<<"enter eno,name and des"<<endl;
cin>>eno;
cin.ignore();
cin.getline(name,20);
cin.getline(des,20);
}
class salary:protected emp
{
protected:
float gross,salary,HRA,DA;
public:
void get1()
{
get();
cout<<"enter salary hra percent and da percent"<<endl;
cin>>salary>>HRA>>DA;
}
void calculate()
{
HRA=(HRA*salary)/100;
DA=(DA*salary)/100;
gross=salary+HRA+DA;
}
void display()
{
cout<<eno<<endl;
cout<<name<<endl;
cout<<gross<<endl;
}
};
//STUDENT CODE HERE
int main()
{
int i,n;
char ch;
salary s[10];
cin>>n;//maximum 10 employees
for(i=0;i<n;i++)
{ s[i].get1();
s[i].calculate();
}
for(i=0;i<n;i++)
{ s[i].display();}
return 0;
}
| true |
d144d3aab2e9c24d3d5e300384652d35bddeb653
|
C++
|
caohong/practice
|
/leetcode/c++/lintcode-064-merge-sorted-array/merge-sorted-array.cpp
|
UTF-8
| 728 | 3.515625 | 4 |
[
"Apache-2.0"
] |
permissive
|
/*
* http://www.lintcode.com/en/problem/merge-sorted-array/
*/
class Solution {
public:
/*
* @param A: sorted integer array A which has m elements, but size of A is m+n
* @param m: An integer
* @param B: sorted integer array B which has n elements
* @param n: An integer
* @return: nothing
*/
void mergeSortedArray(int A[], int m, int B[], int n) {
int ia = m - 1, ib = n - 1, i = m + n - 1;
while (ia >= 0 && ib >= 0) {
if (A[ia] > B[ib]) {
A[i] = A[ia--];
} else {
A[i] = B[ib--];
}
i--;
}
while (ib >= 0) {
A[i--] = B[ib--];
}
return;
}
};
| true |
05d5569a1c956967b44941b50ef1b0d34f96448a
|
C++
|
lsa-src/ArduinoBible
|
/본문소스/CH_68_03/CH_68_03.ino
|
UTF-8
| 1,773 | 2.859375 | 3 |
[] |
no_license
|
#include <WiFiEsp.h>
#include <SoftwareSerial.h>
SoftwareSerial ESPSerial(2, 3); // ESP-01 모듈 연결 포트
char AP[] = "your_AP_name_here";
char PW[] = "your_AP_password_here";
int status = WL_IDLE_STATUS;
void setup() {
Serial.begin(9600); // 컴퓨터와의 UART 시리얼 연결
ESPSerial.begin(9600); // ESP-01 모듈과의 UART 시리얼 연결
WiFi.init(&ESPSerial); // ESP-01 모듈 초기화
String fv = WiFi.firmwareVersion(); // SDK 버전
Serial.println("* SDK 버전 : v." + fv);
Serial.println();
Serial.println(String("* \'") + AP + "\'에 연결을 시도합니다.");
status = WiFi.begin(AP, PW);
if (status != WL_CONNECTED) {
Serial.println("** AP에 연결할 수 없습니다.");
while (1);
}
else {
Serial.println("* AP에 연결되었습니다.");
Serial.println();
printCurrentNet(); // 연결된 네트워크 정보
Serial.println();
printWifiData(); // 무선 인터페이스 정보
}
}
void printCurrentNet() {
Serial.print(" >> SSID (AP 이름)\t\t: ");
Serial.println(WiFi.SSID());
byte bssid[6];
WiFi.BSSID(bssid);
Serial.print(" >> BSSID (네트워크 MAC 주소)\t: ");
printMAC(bssid);
long rssi = WiFi.RSSI();
Serial.print(" >> RSSI (신호 세기)\t\t: ");
Serial.println(rssi);
}
void printWifiData() {
IPAddress ip = WiFi.localIP();
Serial.print(" >> IP 주소\t\t\t: ");
Serial.println(ip);
byte mac[6];
WiFi.macAddress(mac);
Serial.print(" >> 인터페이스 MAC 주소\t\t: ");
printMAC(mac);
}
void printMAC(byte *mac) { // 6바이트 MAC 주소 출력
for (int i = 5; i >= 0; i--) {
Serial.print(mac[i], HEX);
if (i != 0) Serial.print(":");
}
Serial.println();
}
void loop() {
}
| true |
91262410131c458a622f58a61689d937dda3ffcc
|
C++
|
kotmasha/kodlab-uma-encapsulated
|
/slhc/src/logging.cpp
|
UTF-8
| 626 | 2.953125 | 3 |
[
"MIT"
] |
permissive
|
#include "logging.h"
logging::logging(){}
logging::logging(const logging &l){}
logging::logging(string filename, string classname){
_filename = filename;
_classname = parse_class_name(classname);
_output = new ofstream(filename);
}
string logging::parse_class_name(string classname){
classname = classname.substr(classname.find("class") + 6, classname.size() - 6);
return classname;
}
void logging::operator<<(string info){
if(!_active) return;
string output_info = "[" + _classname + "]:" + _level + " " + info + "\n";
_output->write(output_info.c_str(), output_info.size() * sizeof(char));
_output->flush();
}
| true |
433b03ea8f4702a6cd515abe4b78eecc4db623be
|
C++
|
kyang35/x07-KhangYang
|
/TicTacToeBoardTest.cpp
|
UTF-8
| 1,327 | 3.484375 | 3 |
[
"MIT"
] |
permissive
|
/**
* Unit Tests for TicTacToeBoard
**/
#include <gtest/gtest.h>
#include "TicTacToeBoard.h"
class TicTacToeBoardTest : public ::testing::Test
{
protected:
TicTacToeBoardTest(){} //constructor runs before each test
virtual ~TicTacToeBoardTest(){} //destructor cleans up after tests
virtual void SetUp(){} //sets up before each test (after constructor)
virtual void TearDown(){} //clean up after each test, (before destructor)
};
TEST(TicTacToeBoardTest, sanityCheck)
{
ASSERT_TRUE(true);
}
/*
TEST(TicTacToeBoardTest, toggleTurn)
{
TicTacToeBoard board;
Turn = X;
ASSERT_EQ(board.toggleTurn(), O);
}
*/
TEST(TicTacToeBoardTest, placePiece)
{
TicTacToeBoard board;
int row = 1;
int column = 2;
board.placePiece(row, column);
ASSERT_EQ(row, 1);
ASSERT_EQ(column, 2);
}
TEST(TicTacToeBoardTest, checkplacePiece)
{
TicTacToeBoard board;
ASSERT_TRUE(board.placePiece(1, 1) == X);
}
TEST(TicTacToeBoardTest, getPiece)
{
int row = 1;
int column = 1;
TicTacToeBoard board;
board.placePiece(row, column);
int result = board.getPiece(row, column);
ASSERT_EQ(X,result);
}
TEST(TicTacToeBoardTest, getWinner_Invalid)
{
TicTacToeBoard board;
ASSERT_EQ(Invalid, board.getWinner());
}
TEST(TicTacToeBoardTest, getWinner_Blank)
{
TicTacToeBoard board;
ASSERT_EQ(Blank, board.getWinner());
}
| true |
ca0fdcffed54aadd40ae467543798bf14888631d
|
C++
|
ShaneCoates/OpenGL
|
/OpenGL/inc/GameStateManager.h
|
UTF-8
| 850 | 3.15625 | 3 |
[] |
no_license
|
#ifndef GAMESTATE_MANAGER_H
#define GAMESTATE_MANAGER_H
#include <map>
#include <list>
#include <string>
class IGameState;
class GameStateManager
{
public:
GameStateManager();
~GameStateManager();
void Update(double dt);
void Draw();
void RegisterState(std::string _name, IGameState* _state);
void Push(std::string _name);
void Pop();
protected:
private:
std::map<std::string, IGameState*> m_gameStates;
std::list<IGameState*> m_stack;
};
class IGameState
{
public:
virtual void Update(double dt) {};
virtual void Draw() {};
bool isUpdateBlocking() {return m_updateBlocking;}
bool isDrawBlocking() {return m_drawBlocking;}
void SetUpdateBlocking(bool _block) {m_updateBlocking = _block;}
void SetDrawBlocking(bool _block) { m_drawBlocking = _block;}
protected:
private:
bool m_updateBlocking;
bool m_drawBlocking;
};
#endif
| true |
3ed2d20fe16de82f36c0c47cd01b4692fe356f46
|
C++
|
Neconspictor/Euclid
|
/projects/engine_opengl/nex/opengl/buffer/GpuBufferGL.cpp
|
UTF-8
| 4,493 | 2.75 | 3 |
[] |
no_license
|
#include <nex/buffer/GpuBuffer.hpp>
#include <nex/opengl/buffer/GpuBufferGL.hpp>
#include <nex/opengl/opengl.hpp>
nex::UsageHintGL nex::translate(nex::GpuBuffer::UsageHint hint)
{
static UsageHintGL const table[] =
{
DYNAMIC_COPY,
DYNAMIC_DRAW,
DYNAMIC_READ,
STATIC_COPY,
STATIC_READ,
STATIC_DRAW,
STREAM_COPY,
STREAM_DRAW,
STREAM_READ,
};
static const unsigned size = static_cast<unsigned>(GpuBuffer::UsageHint::LAST) + 1;
static_assert(sizeof(table) / sizeof(table[0]) == size, "NeX error: UsageHint and UsageHintGL doesn't match");
return table[static_cast<unsigned>(hint)];
}
nex::AccessGL nex::translate(nex::GpuBuffer::Access access)
{
static AccessGL const table[] =
{
READ_ONLY,
WRITE_ONLY,
READ_WRITE,
};
static const unsigned size = static_cast<unsigned>(GpuBuffer::Access::LAST) + 1;
static_assert(sizeof(table) / sizeof(table[0]) == size, "NeX error: Access and AccessGL doesn't match");
return table[static_cast<unsigned>(access)];
}
nex::GpuBuffer::Impl::Impl(GLenum target) : mTarget(target), mRendererID(GL_FALSE)
{
ASSERT(sizeof(unsigned int) == sizeof(GLuint));
ASSERT(sizeof(unsigned short) == sizeof(GLshort));
GLCall(glGenBuffers(1, &mRendererID));
GLCall(glBindBuffer(mTarget, mRendererID));
}
nex::GpuBuffer::Impl::Impl(nex::GpuBuffer::Impl&& other) noexcept :
mRendererID(other.mRendererID),
mTarget(other.mTarget)
{
other.mRendererID = GL_FALSE;
}
nex::GpuBuffer::Impl& nex::GpuBuffer::Impl::operator=(nex::GpuBuffer::Impl&& o) noexcept
{
if (this == &o) return *this;
this->mRendererID = o.mRendererID;
o.mRendererID = GL_FALSE;
this->mTarget = o.mTarget;
return *this;
}
nex::GpuBuffer::Impl::~Impl()
{
if (mRendererID != GL_FALSE) {
GLCall(glDeleteBuffers(1, &mRendererID));
mRendererID = GL_FALSE;
}
}
nex::GpuBuffer::GpuBuffer(void* internalBufferType, size_t size, const void* data, UsageHint usage) :
mSize(size),
mUsageHint(usage),
#pragma warning( push )
#pragma warning( disable : 4311) // warning for pointer truncation from void* to GLenum
#pragma warning( disable : 4302) // warning for truncation from void* to GLenum
mImpl(new Impl(reinterpret_cast<GLenum>(internalBufferType)))
#pragma warning( pop )
{
resize(mSize, data, mUsageHint);
}
nex::GpuBuffer::GpuBuffer(GpuBuffer&& other) :
mSize(other.mSize),
mUsageHint(other.mUsageHint),
mImpl(other.mImpl)
{
other.mImpl = nullptr;
}
nex::GpuBuffer& nex::GpuBuffer::operator=(GpuBuffer&& o) {
if (this == &o) return *this;
this->mSize = o.mSize;
mUsageHint = o.mUsageHint;
std::swap(mImpl, o.mImpl);
return *this;
}
nex::GpuBuffer::~GpuBuffer() {
if (mImpl) delete mImpl;
mImpl = nullptr;
};
void nex::GpuBuffer::bind() const
{
GLCall(glBindBuffer(mImpl->mTarget, mImpl->mRendererID));
}
nex::GpuBuffer::Impl* nex::GpuBuffer::getImpl()
{
return mImpl;
}
const nex::GpuBuffer::Impl* nex::GpuBuffer::getImpl() const
{
return mImpl;
}
size_t nex::GpuBuffer::getSize() const
{
return mSize;
}
nex::GpuBuffer::UsageHint nex::GpuBuffer::getUsageHint() const
{
return mUsageHint;
}
void* nex::GpuBuffer::map(GpuBuffer::Access usage) const
{
GLCall(void* ptr = glMapNamedBuffer(mImpl->mRendererID, translate(usage)));
return ptr;
}
void nex::GpuBuffer::unbind() const
{
GLCall(glBindBuffer(mImpl->mTarget, GL_FALSE));
}
void nex::GpuBuffer::unmap() const
{
GLCall(glUnmapNamedBuffer(mImpl->mRendererID));
}
void nex::GpuBuffer::update(size_t size, const void* data, size_t offset)
{
GLCall(glNamedBufferSubData(mImpl->mRendererID, offset, size, data));
}
void nex::GpuBuffer::syncWithGPU()
{
//GLCall(glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT));
GLCall(glFinish());
}
void nex::GpuBuffer::resize(size_t size, const void* data, GpuBuffer::UsageHint hint, bool allowOrphaning)
{
//bind();
mUsageHint = hint;
mSize = size;
GLCall(glNamedBufferData(mImpl->mRendererID, size, data, translate(hint)));
}
void nex::ShaderBuffer::bindToTarget() const
{
bindToTarget(mBinding);
}
void nex::ShaderBuffer::bindToTarget(unsigned binding) const
{
//bind();
GLCall(glBindBufferBase(GpuBuffer::mImpl->mTarget, binding, GpuBuffer::mImpl->mRendererID));
}
unsigned nex::ShaderBuffer::getDefaultBinding() const
{
return mBinding;
}
nex::ShaderBuffer::ShaderBuffer(unsigned int binding, void* internalBufferType, size_t size, const void* data, UsageHint usage) :
GpuBuffer(internalBufferType, size, data, usage), mBinding(binding)
{
}
nex::ShaderBuffer::~ShaderBuffer() = default;
| true |
b387902657bee657ee5c5f44ccd72c3c308f6dc5
|
C++
|
JDNdeveloper/2048-Smart-Players
|
/src/ExpectiMaxPlayer.cpp
|
UTF-8
| 17,027 | 3.234375 | 3 |
[
"MIT"
] |
permissive
|
#include <cmath>
#include <sstream>
#include <iostream>
#include <memory.h>
#include <bits/stdc++.h>
#include "ExpectiMaxPlayer.h"
/* ExpectiMaxPlayer interface */
extern "C" {
ExpectiMaxPlayer* ExpectiMaxPlayer_new(bool debug, int depth,
double probCutoff) {
return new ExpectiMaxPlayer(debug, depth, probCutoff);
}
void ExpectiMaxPlayer_delete(ExpectiMaxPlayer* player) {
delete player;
}
int ExpectiMaxPlayer_getMove(ExpectiMaxPlayer* player, Board* board) {
return player->getMove(board);
}
}
/* Board interface */
extern "C" {
Board* Board_new(int size) {
return new Board(size);
}
void Board_delete(Board* board) {
delete board;
}
void Board_setPos(Board* board, int row, int col, int val) {
board->setPos(row, col, val);
}
void Board_setScore(Board* board, int score) {
board->setScore(score);
}
}
/* Board */
Board::Board(int sizeArg) {
// set the board size
size = sizeArg;
length = size * size;
// setup the board
boardByteArray = (char*) calloc(length, sizeof(char));
}
Board::Board(const Board& oldBoard) {
// set the board size and score
size = oldBoard.size;
length = size * size;
score = oldBoard.score;
// copy the board contents
boardByteArray = (char*) malloc(length * sizeof(char));
char* oldBoardByteArray = oldBoard.boardByteArray;
memmove(boardByteArray, oldBoardByteArray, length*sizeof(char));
}
Board::~Board() {
free(boardByteArray);
}
inline void Board::setRawPos(int row, int col, char val) {
boardByteArray[getIndex(row, col)] = val;
}
inline char Board::getRawPos(int row, int col) {
return boardByteArray[getIndex(row, col)];
}
char* Board::getSortedBoardValues() {
char* boardValueArray = (char*) malloc(length * sizeof(char));
memmove(boardValueArray, boardByteArray, length * sizeof(char));
std::sort(boardValueArray, boardValueArray + length, std::greater<char>());
return boardValueArray;
}
inline void Board::setPos(int row, int col, int val) {
if (val == 0) {
setRawPos(row, col, 0);
} else {
setRawPos(row, col, (char) std::log2(val));
}
}
inline int Board::getPos(int row, int col) {
int val = getRawPos(row, col);
if (val == 0) {
return 0;
} else {
return std::pow(2.0, float(val));
}
}
std::string Board::getString() {
std::ostringstream os;
for (int i = 0; i < length; i++) {
os << boardByteArray[i];
}
return os.str();
}
void Board::printBoard() {
for (int row = 0; row < getSize(); row++) {
for (int col = 0; col < getSize(); col++) {
std::cout << getPos(row, col) << "\t";
}
std::cout << std::endl;
}
}
int Board::getAdjacentTiles(){
int numAdj = 0;
int start = 0;
for( int i=0; i<getSize(); i++){
for( int j=0; j<getSize(); j++){
if((j+1 < getSize()) && getPos(i, j) == getPos(i, j+1)) numAdj++;
if((i+1 < getSize()) && getPos(i, j) == getPos(i+1, j)) numAdj++;
if((j-1 >= start) && getPos(i, j) == getPos(i, j-1)) numAdj++;
if((i-1 >= start) && getPos(i, j) == getPos(i-1, j)) numAdj++;
}
}
return numAdj;
}
bool Board::maxTilePenalty(){
int maxTileCount = 1;
int maxTile = getMaxTile();
for (int i=0; i<getSize(); i++){
for (int j=0; j<getSize(); j++){
if (getPos(i, j) == maxTile) maxTileCount++;
}
}
return maxTileCount > 1;
}
bool Board::isMonotonicIncreasingCol(int i){
for (int j = 0; j < getSize()-1; j++){
if (getPos(j, i) > getPos(j+1, i)) return false;
}
return true;
}
bool Board::isMonotonicDecreasingCol(int i){
for (int j = 0; j < getSize()-1; j++){
if (getPos(j, i) < getPos(j+1, i)) return false;
}
return true;
}
bool Board::isMonotonicIncreasingRow(int i){
for (int j = 0; j < getSize()-1; j++){
if (getPos(i, j) < getPos(i, j+1)) return false;
}
return true;
}
bool Board::isMonotonicDecreasingRow(int i){
for (int j = 0; j < getSize()-1; j++){
if (getPos(i, j) > getPos(i, j+1)) return false;
}
return true;
}
int Board::isMonotonicRows(){
int monCntr = 0;
for (int i = 0; i < getSize(); i++){
monCntr += isMonotonicIncreasingRow(i) ? 0: 2;
}
return monCntr;
}
int Board::getTopLeftMonotonicity() {
int monCntr = 0;
int boardSize = getSize();
int start = 0;
int end = boardSize - 1;
for (int j = 0; j < boardSize; j++){
for (int i = 0; i<boardSize-1; i++){
if (getPos(start+j, start+i) < getPos(start+j, start+i+1)){
monCntr += boardSize - i;
}
}
}
for (int i = 0; i<boardSize-1; i++){
if (getPos(start+i, start) < getPos(start+i+1, start)){
monCntr += boardSize - i;
}
}
return monCntr;
}
int Board::getTopRightMonotonicity(){
int monCntr = 0;
int boardSize = getSize();
int start = 0;
int end = boardSize - 1;
for (int j = 0; j<boardSize-1; j++){
for (int i = 0; i<boardSize-1; i++){
if (getPos(start+j, end-i) < getPos(start+j, end-i-1)){
monCntr += boardSize - i;
}
}
}
for (int i = 0; i<boardSize-1; i++){
if (getPos(start+i, end) < getPos(end+i+1, start)){
monCntr += boardSize - i;
}
}
return monCntr;
}
int Board::getBotLeftMonotonicity(){
int monCntr = 0;
int boardSize = getSize();
int start = 0;
int end = boardSize - 1;
for (int j = 0; j<boardSize-1; j++){
for (int i = 0; i<boardSize-1; i++){
if (getPos(end-j, start+i) < getPos(end-j, start+i+1)){
monCntr += boardSize - i;
}
}
}
for (int i = 0; i<boardSize-1; i++){
if (getPos(end-i, start) < getPos(end-i-1, start)){
monCntr += boardSize - i;
}
}
return monCntr;
}
int Board::getBotRightMonotonicity(){
int monCntr = 0;
int boardSize = getSize();
int start = 0;
int end = boardSize - 1;
for (int j = 0; j<boardSize-1; j++){
for (int i = 0; i<boardSize-1; i++){
if (getPos(end-j, end-i) < getPos(end-j, end-i-1)){
monCntr += boardSize - i;
}
}
}
for (int i = 0; i<boardSize-1; i++){
if (getPos(end-i, end) < getPos(end-i-1, end)){
monCntr += boardSize - i;
}
}
return monCntr;
}
int Board::getSnakeBonus(char* sortedBoardValues){
int start=0;
int snakeBonus = 0;
if (getPos(start, start) > getPos(start, start+1)){
for (int i=0; i<getSize()-1; i++){
if(i%2==0 && getPos(start, start+i) > getPos(start, start+i+1))
snakeBonus++;
else if(i%2==1 && getPos(start, start+i) < getPos(start, start+i+1))
snakeBonus++;
}
} else {
for (int i=0; i<getSize()-1; i++){
if(i%2==0 && getPos(start, start+i) < getPos(start, start+i+1))
snakeBonus++;
else if(i%2==1 && getPos(start, start+i) > getPos(start, start+i+1))
snakeBonus++;
}
}
}
int Board::getTileSum() {
int score = 0;
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
score += getPos(row, col);
}
}
return score;
}
int Board::getMaxTile() {
int maxTile = 0;
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
int val = getRawPos(row, col);
maxTile = val > maxTile ? val : maxTile;
}
}
return std::pow(2.0, maxTile);
}
int Board::getNumOpenSpaces() {
int numOpenSpaces = 0;
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
if (getRawPos(row, col) == 0) {
numOpenSpaces++;
}
}
}
return numOpenSpaces;
}
int Board::makeMove(Move move) {
bool boardChanged = false;
int moveScore = 0;
int rowIdx = 0;
int colIdx = 0;
switch (move) {
case UP:
rowIdx = 0;
colIdx = 0;
break;
case DOWN:
rowIdx = size - 1;
colIdx = 0;
break;
case LEFT:
rowIdx = 0;
colIdx = 0;
break;
case RIGHT:
rowIdx = 0;
colIdx = size - 1;
break;
}
for (int i = 0; i < size; i++) {
int rowBackIdx = rowIdx;
int colBackIdx = colIdx;
int setCount = 0;
int prevVal = -1;
int rowPrevIdx = -1;
int colPrevIdx = -1;
for (int j = 0; j < size; j++) {
int val = getRawPos(rowIdx, colIdx);
if (val > 0) {
if (val == prevVal) {
int newVal = val + 1;
setRawPos(rowPrevIdx, colPrevIdx, newVal);
moveScore += newVal;
prevVal = -1;
boardChanged = true;
} else {
setRawPos(rowBackIdx, colBackIdx, val);
setCount++;
if (rowBackIdx != rowIdx || colBackIdx != colIdx)
boardChanged = true;
prevVal = val;
switch (move) {
case UP:
rowBackIdx++;
break;
case DOWN:
rowBackIdx--;
break;
case LEFT:
colBackIdx++;
break;
case RIGHT:
colBackIdx--;
break;
}
}
}
rowPrevIdx = rowIdx;
colPrevIdx = colIdx;
switch (move) {
case UP:
rowIdx++;
break;
case DOWN:
rowIdx--;
break;
case LEFT:
colIdx++;
break;
case RIGHT:
colIdx--;
break;
}
}
for (; setCount < size; setCount++) {
setRawPos(rowBackIdx, colBackIdx, 0);
switch (move) {
case UP:
rowBackIdx++;
break;
case DOWN:
rowBackIdx--;
break;
case LEFT:
colBackIdx++;
break;
case RIGHT:
colBackIdx--;
break;
}
}
switch (move) {
case UP:
rowIdx = 0;
colIdx++;
break;
case DOWN:
rowIdx = size - 1;
colIdx++;
break;
case LEFT:
rowIdx++;
colIdx = 0;
break;
case RIGHT:
rowIdx++;
colIdx = size - 1;
break;
}
}
score += moveScore;
/* return value:
* -1 = board did not change
* 0 = no tiles merged
* >0 = tiles merged
*/
return boardChanged ? moveScore : -1;
}
/* ExpectiMaxPlayer */
ExpectiMaxPlayer::ExpectiMaxPlayer(bool debugArg, int depthArg,
double probCutoffArg)
: debug(debugArg),
depth(depthArg),
probCutoff(probCutoffArg),
stateCache() {
}
int tryMove(Board* board, Move move) {
Board* newBoard = new Board(*board);
int moveScore = newBoard->makeMove(move);
delete newBoard;
return moveScore;
}
float getHeuristicScore(Board* board) {
int boardSize = board->getSize();
int start = 0;
int end = boardSize - 1;
int score = board->getScore();
int maxTile = board->getMaxTile();
int openSpaces = board->getNumOpenSpaces();
bool topLeft = (maxTile == board->getPos(start, start));
bool topRight = (maxTile == board->getPos(start, end));
bool botLeft = (maxTile == board->getPos(end, start));
bool botRight = (maxTile == board->getPos(end, end));
bool maxTileInCorner = topLeft || topRight || botLeft || botRight;
int numAdjacent = board->getAdjacentTiles();
int monCntr = 0; //proxy for monotonicity of row and col with Max Val
if (topLeft) monCntr = board->getTopLeftMonotonicity();
if (topRight) monCntr = board->getTopRightMonotonicity();
if (botLeft) monCntr = board->getBotLeftMonotonicity();
if (botRight) monCntr = board->getBotRightMonotonicity();
return (-10.0 * monCntr +
10.0 * openSpaces +
20.0 * maxTileInCorner*maxTile +
10.0*numAdjacent);
}
Result ExpectiMaxPlayer::getMoveRecursive(Board* board, Player player,
int depth, double prob) {
State state(board->getString(), player, depth);
StateCache::iterator stateIt = stateCache.find(state);
if (stateIt != stateCache.end()) {
return Result(stateIt->second, NO_MOVE);
}
if (depth == 0 || prob < probCutoff) {
int heuristicScore = getHeuristicScore(board);
stateCache.insert({state, heuristicScore});
return Result(heuristicScore, NO_MOVE);
}
switch (player) {
case USER:
{
Board* newBoard;
Move move;
int moveScore;
Move maxMove = NO_MOVE;
// this serves as the penalty for reaching
// game over
float maxScore = -100;
// move up
move = UP;
newBoard = new Board(*board);
moveScore = newBoard->makeMove(move);
if (moveScore != -1) {
Result result = getMoveRecursive(newBoard, TILE_SPAWN,
depth, prob / 4.0);
float score = result.score;
if (score >= maxScore) {
maxScore = score;
maxMove = move;
}
}
delete newBoard;
// move down
move = DOWN;
newBoard = new Board(*board);
moveScore = newBoard->makeMove(move);
if (moveScore != -1) {
Result result = getMoveRecursive(newBoard, TILE_SPAWN,
depth, prob / 4.0);
float score = result.score;
if (score >= maxScore) {
maxScore = score;
maxMove = move;
}
}
delete newBoard;
// move left
move = LEFT;
newBoard = new Board(*board);
moveScore = newBoard->makeMove(move);
if (moveScore != -1) {
Result result = getMoveRecursive(newBoard, TILE_SPAWN,
depth, prob / 4.0);
float score = result.score;
if (score >= maxScore) {
maxScore = score;
maxMove = move;
}
}
delete newBoard;
// move right
move = RIGHT;
newBoard = new Board(*board);
moveScore = newBoard->makeMove(move);
if (moveScore != -1) {
Result result = getMoveRecursive(newBoard, TILE_SPAWN,
depth, prob / 4.0);
float score = result.score;
if (score >= maxScore) {
maxScore = score;
maxMove = move;
}
}
delete newBoard;
stateCache.insert({state, maxScore});
return Result(maxScore, maxMove);
}
break;
case TILE_SPAWN:
{
float expectedScore = 0;
float twoTileScores = 0;
float fourTileScores = 0;
int size = board->getSize();
int emptySlots = board->getNumOpenSpaces();
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
if (board->getRawPos(row, col) == 0) {
Board* newBoard;
int tile;
double newProb;
// spawn a 2^1 = 2 tile in the empty position
tile = 1;
newBoard = new Board(*board);
newBoard->setRawPos(row, col, tile);
newProb = prob * (1.0 / emptySlots) * 0.9;
{
Result result = getMoveRecursive(newBoard, USER,
depth - 1, newProb);
twoTileScores += result.score;
}
delete newBoard;
// spawn a 2^2 = 4 tile in the empty position
tile = 2;
newBoard = new Board(*board);
newBoard->setRawPos(row, col, tile);
newProb = prob * (1.0 / emptySlots) * 0.1;
{
Result result = getMoveRecursive(newBoard, USER,
depth - 1, newProb);
fourTileScores += result.score;
}
delete newBoard;
}
}
}
if (emptySlots == 0) {
expectedScore = 0;
} else {
expectedScore = (0.9 * (twoTileScores / emptySlots) +
0.1 * (fourTileScores / emptySlots));
}
stateCache.insert({state, expectedScore});
return Result(expectedScore, NO_MOVE);
}
break;
}
}
int ExpectiMaxPlayer::getMove(Board* board) {
stateCache.clear();
Result result = getMoveRecursive(board, USER, depth, 1.0);
return result.move;
}
| true |
008a615130c64e4607fa5902a3aa4b99da5eb13b
|
C++
|
aazucena/Portfolio
|
/University/Introduction To Sofware Engineering/Lectures/playlist/src/main.cpp
|
UTF-8
| 476 | 3 | 3 |
[] |
no_license
|
#include "Playlist.h"
#include <iostream>
void list(Playlist* pl) {
for(int i = 0; i < 10; i++) {
const Song* s = pl->getSong();
std::cout << s->name << std::endl;
}
}
int main(int argc, char const *argv[]) {
Playlist* pl = Playlist::greatest();
std::cout << " ===== Default Ordering =====" << std::endl;
list(pl);
std::cout << std::endl << " ===== Random Order =====" << std::endl;
//pl->setNumberGenerator(new Random());
list(pl);
return 0;
}
| true |
d54083b1ff6b859e939b2159460ae482cdb66c27
|
C++
|
hpurba/CS236
|
/HP_Project4/main.cpp
|
UTF-8
| 4,460 | 2.515625 | 3 |
[] |
no_license
|
// HP_Project1.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "parser.h"
#include "scanner.h"
#include "interpreter.h"
#include "database.h"
using namespace std;
int main(int argc, char *argv[]) {
string fileName = argv[1];
// ORIGINAL CODE
vector<Tokenizer> vectorOfTokens;
Scanner scan;
// Scan to create vector of token objects
vectorOfTokens = scan.scan_Identify(fileName);
Parser parse; // Checks the grammar
parse.parse(vectorOfTokens);
DataBase database;
database.setup(parse.getSchemes()); // sets up the database from all the vectors from the parser
database.addFacts(parse.getFacts());
// database.printRelations();
Interpreter interpreter;
// Evaluate rules
// database.addRules(parse.getRules()); // what I originally had
interpreter.addDatabase(database.returnDatabaseRelations());
interpreter.addRules(parse.getRules());
// Process queries
cout << "Query Evaluation\n";
// Interpreter interpreter;
interpreter.setupQuery(parse.getQueries());
interpreter.processQuery(); // database.returnDatabaseRelations());
//// FOR TESTING PUPOSES
//DataBase database;
//vector<Schemes> vectorOfSchemes;
//vector<Facts> vectorOfFacts;
//// Set up Relation Name and Schemes
//
//// alpha
//vector<string> columnNames0 = { "cat", "dog", "fish"}; // "fish", "bird", "bunny"
//Schemes scheme1("alpha", columnNames0);
//// fill scheme with tuples
//// Row 1
//string factID1 = "alpha"; // name of table it belongs to
//vector<string> stringListVector1 = { "1", "2", "5" };
//Facts fact1(factID1, stringListVector1);
//vectorOfFacts.push_back(fact1);
//// Row 2
//stringListVector1 = { "1", "4", "1" };
//Facts fact2(factID1, stringListVector1);
//vectorOfFacts.push_back(fact2);
//// Row 3
//stringListVector1 = { "6", "7", "4" };
//Facts fact3(factID1, stringListVector1);
//vectorOfFacts.push_back(fact3);
//vectorOfSchemes.push_back(scheme1); // Add Scheme
//
//// beta
//vector<string> columnNames1 = { "cat", "fish", "bird", "bunny" };
//Schemes scheme2("beta", columnNames1);
//// fill scheme with tuples
//// Row 1
//factID1 = "beta"; // name of table it belongs to
//stringListVector1 = { "1", "5", "2", "4" };
//Facts fact4(factID1, stringListVector1);
//vectorOfFacts.push_back(fact4);
//// Row 2
//stringListVector1 = { "4", "3", "2", "7" };
//Facts fact5(factID1, stringListVector1);
//vectorOfFacts.push_back(fact5);
//// Row 3
//stringListVector1 = { "1", "5", "8", "3" };
//Facts fact6(factID1, stringListVector1);
//vectorOfFacts.push_back(fact6);
//// Row 4
//stringListVector1 = { "6", "4", "9", "2" };
//Facts fact7(factID1, stringListVector1);
//vectorOfFacts.push_back(fact7);
//vectorOfSchemes.push_back(scheme2); // Add Scheme
//// add facts to database
//
//// EMPTY
//vector<string> columnNames = { "cat", "dog", "fish", "bird", "bunny" };
//Schemes scheme3("gamma", columnNames);
//// no tuples
//vectorOfSchemes.push_back(scheme3);
//// Add all the schemes into database.
//database.setup(vectorOfSchemes);
//database.addFacts(vectorOfFacts);
//
//// BUILDING RULES
//vector<Rules> vectorOfRules;
//// individual object specific variables
//vector<HeadPredicate> headPredicateObj;
//vector<Predicates> vectorOfPredicates; // holds vector of Predicate
//string headPredicateID = "gamma";
//vector<string> idList = { "cat", "dog", "fish", "bird", "bunny" };
//HeadPredicate headPredicate( headPredicateID, idList);
//headPredicateObj.push_back(headPredicate);
//// alpha
//string predicateID = "alpha";
//vector<string> parametersVector0 = { "cat", "dog", "fish" };
//Predicates firstPredicate(predicateID, parametersVector0);
//vectorOfPredicates.push_back(firstPredicate);
//// beta
//predicateID = "beta";
//vector<string> parametersVector1 = { "cat", "fish", "bird", "bunny" };
//Predicates secondPredicate(predicateID, parametersVector1);
//vectorOfPredicates.push_back(secondPredicate);
//
//Rules rule1( headPredicateObj, vectorOfPredicates);
//vectorOfRules.push_back(rule1);
//Interpreter interpreter;
//interpreter.addDatabase(database.returnDatabaseRelations());
//interpreter.addRules(vectorOfRules);
return 0;
}
| true |
c223c0a05a4189a61088a83bfecf1a6dbeb6b4fb
|
C++
|
dwrrehman/sput
|
/testing/finished/opticnerve_test(failed)/source/r.cpp
|
UTF-8
| 2,116 | 2.78125 | 3 |
[] |
no_license
|
/// ----------- sput -------------
/*
* project : opticnerve_test
* file : r.cpp
*
* creator : dwrr
* created : 1705033.102142
*
* version : 0.1
* touched : 1707123.172242
*
*/
/// -------------------------------
// description:
// the retina of sput. this is a set of functions used to retreive image data from the camera sensor.
#ifndef r_dot_cpp
#define r_dot_cpp
// system includes:
#include <unistd.h>
#include <stdio.h>
#include <raspicam/raspicam.h>
// my includes:
#include "r.on.cpp"
/*
example of the retinas use:
retina_set_size(small);// optional //
//retina_visualencoder_set_n_and_w(50, 5);//opt // init
retina_initialize(); //
while(true){
data = retina(); // bit array. // get
}
retina_clean(); // end
*/
// ---------- retina functions and variables: --------------
// ---------- constants -------------
#define small 1
#define medium 2
#define large 3
// ---------- vairables ---------
raspicam::RaspiCam Camera;
unsigned char* retina_data;
int camera_size = small;
// -------------- computed values -------------
#define retina_length (Camera.getImageTypeSize(raspicam::RASPICAM_FORMAT_RGB))
#define retina_height (Camera.getHeight())
#define retina_width (Camera.getWidth())
// -------- functions -----------
void retina_set_size(int size) {
camera_size = size;
}
void retina_initialize() {
Camera.setFormat(raspicam::RASPICAM_FORMAT_RGB);
// initialize the size of the camera:
if (camera_size == small) {
Camera.setHeight(240);
Camera.setWidth(320);
}
else if (camera_size == medium) {
Camera.setHeight(480);
Camera.setWidth(640);
}
else if (camera_size == large) {
Camera.setHeight(960);
Camera.setWidth(1280);
}
Camera.open();
sleep(3); // let the camera settle,
retina_data = new unsigned char[retina_length]; // allocate for image.
}
void retina_clean() {
delete retina_data;
}
unsigned char* retina() {
Camera.grab();
Camera.retrieve(retina_data);
return retina_data;
}
#endif
| true |
bfedcbaa862826e67d3d70120aa545c9a2d9893f
|
C++
|
jacek143/kata
|
/sources/range_extraction/range_extraction.cpp
|
UTF-8
| 1,008 | 3.03125 | 3 |
[
"MIT"
] |
permissive
|
#include "range_extraction.h"
#include <sstream>
void range_extraction::remove_last_comma(std::string &str) {
if (not str.empty()) {
str.pop_back();
}
}
void range_extraction::format_ranges(std::string &str) {
for (auto pos = str.find(",_"); pos != std::string::npos;
pos = str.find(",_")) {
str.replace(pos, 2, "-");
}
for (auto pos = str.find('_'); pos != std::string::npos;
pos = str.find('_')) {
str.erase(pos, 1);
}
}
std::string range_extraction::range_extraction(std::vector<int> args) {
std::stringstream stream;
auto N = args.size();
for (decltype(N) i = 0; i < N; i++) {
bool in_range = false;
if (i > 0 and i < N - 1) {
if (args.at(i - 1) + 1 == args.at(i) and
args.at(i) + 1 == args.at(i + 1)) {
in_range = true;
}
}
if (in_range) {
stream << "_";
} else {
stream << args.at(i) << ",";
}
}
auto str = stream.str();
remove_last_comma(str);
format_ranges(str);
return str;
}
| true |
c473e0eff7b26e5d483528939c3c4f527dfd78c6
|
C++
|
theunknowner/WebDerm
|
/WebDerm/src/Shape/shapecolor.cpp
|
UTF-8
| 8,350 | 2.609375 | 3 |
[] |
no_license
|
/*
* shapecolor.cpp
*
* Created on: Mar 16, 2015
* Author: jason
*/
#include "shapecolor.h"
#include "../functions.h"
#include "../KneeCurve/kneecurve.h"
#include "../Shades/shades.h"
void ShapeColor::setDebugLevel(int level) {
this->debugLevel = level;
}
//use in conjunction with setDebugLevel;
void ShapeColor::setDebugColRow(int col, int row) {
this->dbgCol = col;
this->dbgRow = row;
}
//removes lines that run across the image
Mat ShapeColor::removeRunningLines(Mat input, Size size) {
Mat dst = input.clone();
const int thresh=11; // length of line
const int thickness = 5; // thickness of line
Size winSize = size;
int countStreak=0;
Mat window;
Size prevSize;
Point startPt(0,0), endPt(0,0);
int rowDecr=0, rowIncr=0;
if(this->debugLevel==2)
namedWindow("img",CV_WINDOW_FREERATIO | CV_GUI_EXPANDED);
for(int row=0; row<=(dst.rows-winSize.height); row++) {
startPt.y = row;
for(int col=0; col<=(dst.cols-winSize.width); col++) {
window = dst(Rect(col,startPt.y,winSize.width,winSize.height));
if(countNonZero(window)==window.total()) {
/****DEBUG OUTPUT INFO ****/
if(this->debugLevel==2) {
Mat test = input.clone();
rectangle(test,Rect(col,startPt.y,winSize.width,winSize.height),Scalar(150));
printf("****BEFORE0****\n");
printf("Point(%d,%d)\n",col,row);
printf("winSize: %dx%d\n",winSize.width, winSize.height);
printf("Begin:(%d,%d)\n",col,row-rowDecr);
printf("Streak: %d\n",countStreak);
imshow("img",test);
waitKey(0);
} //end debug print
//expand upwards
if(row>0) {
while(1) {
try {
rowDecr++;
winSize.height = size.height+rowDecr+rowIncr;
if(row-rowDecr>=0) {
window = dst(Rect(col,row-rowDecr,winSize.width,winSize.height));
/****DEBUG OUTPUT INFO ****/
if(this->debugLevel==2) {
Mat test = input.clone();
rectangle(test,Rect(col,row-rowDecr,winSize.width,winSize.height),Scalar(150));
printf("****BEFORE1****\n");
printf("Point(%d,%d)\n",col,row);
printf("winSize: %dx%d\n",winSize.width, winSize.height);
printf("Begin:(%d,%d)\n",col,row-rowDecr);
printf("Streak: %d\n",countStreak);
imshow("img",test);
waitKey(0);
} //end debug output
}
if(countNonZero(window)!=window.total() || (row-rowDecr)<0) {
rowDecr--;
winSize.height = size.height+rowDecr+rowIncr;
window = dst(Rect(col,row-rowDecr,winSize.width,winSize.height));
if(prevSize!=window.size()) {
if(countStreak>thresh && window.rows<=thickness) {
for(int i=startPt.y; i<startPt.y+window.rows; i++) {
for(int j=startPt.x; j<col+window.cols; j++) {
if(dst.type()==CV_8U)
dst.at<uchar>(i,j) = 0;
/****DEBUG OUTPUT INFO ****/
if(this->debugLevel==2) {
imshow("dst",dst);
waitKey(0);
} // end debug output
}
}
}
countStreak=0;
}
if(countStreak==0)
startPt = Point(col,row-rowDecr);
/****DEBUG OUTPUT INFO ****/
if(this->debugLevel==2) {
Mat test = input.clone();
rectangle(test,Rect(col,row-rowDecr,winSize.width,winSize.height),Scalar(150));
printf("****AFTER1****\n");
printf("Point(%d,%d)\n",col,row);
printf("winSize: %dx%d\n",winSize.width, winSize.height);
printf("Begin:(%d,%d)\n",col,row-rowDecr);
printf("Streak: %d\n",countStreak);
imshow("img",test);
waitKey(0);
} //end debug output
break;
}
} catch (cv::Exception &e) {
printf("Catch #1\n");
printf("%d,%d\n",col,row);
printf("Row+RowIncr: %d\n",row+rowIncr);
exit(1);
}
} // end while
} // end if(row>0)
//expand downwards
if(row<input.rows-1) {
while(1) {
try {
rowIncr++;
winSize.height = size.height+rowDecr+rowIncr;
if(row+rowIncr<dst.rows) {
window = dst(Rect(col,startPt.y,winSize.width,winSize.height));
/****DEBUG OUTPUT INFO ****/
if(this->debugLevel==2) {
Mat test = input.clone();
rectangle(test,Rect(col,startPt.y,winSize.width,winSize.height),Scalar(150));
printf("****BEFORE2****\n");
printf("Point(%d,%d)\n",col,row);
printf("winSize: %dx%d\n",winSize.width, winSize.height);
printf("Begin:(%d,%d)\n",col,row-rowDecr);
printf("End:(%d,%d)\n",col,row+rowIncr);
printf("Streak: %d\n",countStreak);
imshow("img",test);
waitKey(0);
} //end debug output
}
if(countNonZero(window)!=window.total() || row+rowIncr>=dst.rows) {
rowIncr--;
winSize.height = size.height+rowDecr+rowIncr;
endPt = Point(col,row+rowIncr);
window = dst(Rect(col,startPt.y,winSize.width,winSize.height));
/****DEBUG OUTPUT INFO ****/
if(this->debugLevel==2) {
Mat test = input.clone();
rectangle(test,Rect(col,startPt.y,winSize.width,winSize.height),Scalar(150));
printf("****AFTER2****\n");
printf("Point(%d,%d)\n",col,row);
printf("winSize: %dx%d\n",winSize.width, winSize.height);
printf("Begin:(%d,%d)\n",col,row-rowDecr);
printf("End:(%d,%d)\n",col,row+rowIncr);
printf("Streak: %d\n",countStreak);
imshow("img",test);
waitKey(0);
} // end debug output
break;
}
} catch (cv::Exception &e) {
printf("Catch #2\n");
printf("%d,%d\n",col,row);
printf("Row+RowIncr: %d\n",row+rowIncr);
printf("StartPt:(%d,%d)\n",col,startPt.y);
printf("EndPt(%d,%d)\n",endPt.x,endPt.y);
printf("WinSize(%d,%d)\n",winSize.width,winSize.height);
exit(1);
}
} // end while
} // end if
if(prevSize==window.size()) countStreak++;
if(prevSize!=window.size() || col==(dst.cols-winSize.width)) {
if(countStreak>=thresh && window.rows<=thickness) {
for(int i=startPt.y; i<startPt.y+window.rows; i++) {
for(int j=startPt.x; j<col+window.cols; j++) {
if(dst.type()==CV_8U)
dst.at<uchar>(i,j) = 0;
/****DEBUG OUTPUT INFO ****/
if(this->debugLevel==2) {
imshow("dst",dst);
waitKey(0);
} // end debug output
}
}
}
if(countStreak>0) {
winSize = size;
rowDecr=0;
rowIncr=0;
startPt = Point(col,row);
}
countStreak=0;
}
} // end if
else {
if(countStreak>=thresh && window.rows<=thickness) {
for(int i=startPt.y; i<startPt.y+window.rows; i++) {
for(int j=startPt.x; j<col+window.cols; j++) {
if(dst.type()==CV_8U)
dst.at<uchar>(i,j) = 0;
if(dst.type()==CV_8UC3)
dst.at<Vec3b>(i,j) = Vec3b(0,0,0);
/****DEBUG OUTPUT INFO ****/
if(this->debugLevel==2) {
imshow("dst",dst);
waitKey(0);
} // end debug output
}
}
}
winSize=size;
rowDecr=0;
rowIncr=0;
startPt = Point(col,row);
countStreak=0;
}
/****DEBUG OUTPUT INFO ****/
if(this->debugLevel==2) {
printf("****FINAL****\n");
printf("Point(%d,%d)\n",col,row);
printf("PrevSize: %dx%d, WindowSize: %dx%d\n",prevSize.width,prevSize.height,window.cols,window.rows);
printf("Streak: %d\n",countStreak);
} // end debug output
prevSize = window.size();
} // end col
} // end row
return dst;
}
//filter LC using knee of curve
Mat ShapeColor::filterKneePt(Mat src, double thresh, double shift) {
KneeCurve kc;
vector<double> yVec1;
for(int i=0; i<src.rows; i++) {
for(int j=0; j<src.cols; j++) {
double lum = src.at<uchar>(i,j);
if(lum>thresh)
yVec1.push_back(lum);
}
}
int bestIdx = kc.kneeCurvePoint(yVec1);
float percent = ip::roundDecimal((float)bestIdx/yVec1.size(),2);
if(percent<=0.05000001)
bestIdx = 0.25 * yVec1.size();
if(percent>=0.8999999)
bestIdx = 0.75 * yVec1.size();
double threshFilter = yVec1.at(bestIdx);
Mat dst =src.clone();
for(int i=0; i<src.rows; i++) {
for(int j=0; j<src.cols; j++) {
double lum = src.at<uchar>(i,j);
if(lum<threshFilter)
dst.at<uchar>(i,j) = 0;
}
}
return dst;
}
| true |
d3df741279740340ff519a15b5609940dd08a303
|
C++
|
AlexAUT/SFML-Gamejam2
|
/include/game/misc/introMessage.hpp
|
UTF-8
| 443 | 2.703125 | 3 |
[] |
no_license
|
#ifndef INTROMESSAGE_HPP
#define INTORMESSAGE_HPP
#include <vector>
#include <SFML/Graphics/Text.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
namespace aw
{
class IntroMessage
{
public:
IntroMessage();
void setMessage(std::vector<std::string> &message, const std::string &instruction);
void render(sf::RenderTarget &target);
private:
sf::Font mFont;
std::vector<sf::Text> mMessages;
sf::Text mInstruction;
};
}
#endif
| true |
2448e0a7fb86ae668671fc08dcbe43e743e10288
|
C++
|
zaman-projectxix/C-plus-plus
|
/All About C++/chap3drill/main.cpp
|
UTF-8
| 1,510 | 3.25 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <algorithm>
using namespace std;
int main () {
string first_name = "";
cout << "Enter the name of the person you want to write to\n";
cin >> first_name;
string another_name;
cout << "Enter the name of another friend\n";
cin >> another_name;
char friend_sex = 0;
cout << "Enter the sex of the friend\n";
cin >> friend_sex;
int age;
cout << "Enter the age of the recipient\n";
cin >> age;
cout << "Dear " << first_name << ',' << endl;
cout << " How are you? I am fine. I miss you. Are you continuing your coding yet?\n";
cout << "\nHave you seen " << another_name << " recently?\n";
if (friend_sex == 'm')
cout << "If you see " << another_name
<< " please ask him to call me.\n";
if (friend_sex == 'f')
cout << "If you see " << another_name
<< " please ask her to call me.\n";
cout << "\nI hear you just had a birthday recently and are "
<< age << " years old\n";
if (age <= 0)
cout << "You're kidding!\n";
if (age >= 110)
cout << "You're kidding!\n";
if (age <= 12)
cout << "Next year you will be " << age+1 << endl;
if (age == 17)
cout << "Next year you will be able to vote.\n";
if (age >= 70)
cout << "I hope you are enjoying your retirement.\n";
cout << "Yours sincerely, Shawkat.\n";
// keep_window_open();
return 0;
}
| true |
89f7190580c5ac1a6e3e0398ae3756e551502a51
|
C++
|
lxj434368832/Framework
|
/projects/Test/LogTest.h
|
GB18030
| 2,535 | 2.578125 | 3 |
[] |
no_license
|
#pragma once
#include <windows.h>
#include <atlconv.h>
/*#include "..\..\include\LogFile.h"
int TestAppLog()
{
char szFullPath[MAX_PATH];
::GetModuleFileNameA(nullptr, szFullPath, MAX_PATH);
DWORD dwCount = GetTickCount();
for (int i = 0; i < 1000; i++)
{
LOGM("ǰ·Ϊ:%s", szFullPath);
}
DWORD dwCount1 = GetTickCount();
logw() << "һʱ" << dwCount1 - dwCount << "ms";
dwCount = GetTickCount();
for (int i = 0; i < 1000; i++)
{
logd() << "ǰ·Ϊ:" << szFullPath;
}
dwCount1 = GetTickCount();
loge() << "ڶιʱ:" << dwCount1 - dwCount << "ms";
logd() << "˳";
return 0;
}*/
/*
#include "..\..\include\LibLog.h"
#define LIB_NAME "LogTest"
int TestLibLog()
{
char szFullPath[MAX_PATH];
::GetModuleFileNameA(nullptr, szFullPath, MAX_PATH);
DWORD dwCount = GetTickCount();
for (int i = 0; i < 1000; i++)
{
LOGM("ǰ·Ϊ:%s", szFullPath);
LOGM("%s", "ζţҹĿǰѾ͵ٴ顣\
ϴȾЧİ취ж֣ʵȻĵֿ\
¹ڷײSARS͵Ĺ״ڵϵͳʶ\
ˡϵΪѡãҪϵͳʶʲôӣ\
Ȼϵͳ");
}
DWORD dwCount1 = GetTickCount();
std::cout << "ܹʱ" << dwCount1 - dwCount << std::endl;
return 0;
}
*/
#include "..\..\include\DebugLog.h"
int TestDebugLog()
{
char szFullPath[MAX_PATH];
::GetModuleFileNameA(nullptr, szFullPath, MAX_PATH);
DWORD dwCount = GetTickCount();
for (int i = 0; i < 1000; i++)
{
LOGM("ǰ·Ϊ:%s", szFullPath);
LOGM("%s", "ζţҹĿǰѾ͵ٴ顣"\
"ϴȾЧİ취ж֣ʵȻĵֿ"\
"¹ڷײSARS͵Ĺ״ڵϵͳʶ"\
"ˡϵΪѡãҪϵͳʶʲôӣ"\
"Ȼϵͳ");
}
DWORD dwCount1 = GetTickCount();
std::cout << "ܹʱ" << dwCount1 - dwCount << std::endl;
return 0;
}
| true |
82143c73d5897977f4900ef50d07055132edd418
|
C++
|
tac2155/rgb
|
/firmware/Effects.h
|
UTF-8
| 1,648 | 2.9375 | 3 |
[
"MIT"
] |
permissive
|
// rgb
// daisy-chainable lighting module
// http://github.com/mcous/rgb
//
// copyright 2013 michael cousins and authors listed in http://github.com/mcous/rgb/AUTHORS.md
// shared under the terms of the mit licence
// header file for light effects class using a tlc5940
#ifndef EFFECTS_H
#define EFFECTS_H
// includes necessary for this header
#include "TLC5940.h"
// effect defines
#define SUPERDOME 1
#define CYLON 2
#define PINGPONG 3
#define ALLFADE 4
#define WATERFALL 5
#define DOUBLEWF 6
class Effects {
public:
// constructor
Effects();
// set the current effect
void setEffect(uint8_t eff);
// refresh the display
void refresh();
private:
// TLC5940 led driver
TLC5940 driver;
// overflow counter
uint16_t count;
// 5x3 array for led values (5x RGB led, where each RGB is 3 leds)
uint8_t leds[5][3];
//3 int array to set LED colors
uint8_t val[3];
// counter step for effects (bigger step = faster effects)
uint8_t step;
// custom parameters for effects
uint8_t param[6];
// current effect function handle
void (Effects::*cF)(void);
// superdome show
void superDome(void);
// cylon
void cylon(void);
//bouncing color
void pingPong(void);
//unison fade
void allFade(void);
//one direction on, off
void waterfall(void);
//on to off right and left
void doubleWF(void);
// effect helper functions
// sets all leds to the same color
void rgb(uint16_t r, uint16_t g, uint16_t b);
// saves to v the rgb values for a cosine-wave based rainbow given a time t (T = 384)
void cosineVal(uint8_t* v, uint16_t t);
};
#endif
| true |
621d46a36a894861f228b7f14ab0a5694ad89b19
|
C++
|
timofteciprian/uni
|
/oop/finalExam/finalExam/Ui.cpp
|
UTF-8
| 1,885 | 2.84375 | 3 |
[] |
no_license
|
//
// Ui.cpp
// finalExam
//
// Created by Timofte Ciprian Andrei on 08/06/2018.
// Copyright © 2018 Timofte Ciprian Andrei. All rights reserved.
//
#include "Ui.hpp"
Ui::Ui(Controller &ctrl): ctrl(ctrl) {
//ctor
}
void Ui::mainSupport(){
cout<<endl;
cout<<" --------------------------------------- Main ------------------------------------------"<<endl;
cout<<" 0. Exit."<<endl;
cout<<" 1. Adauga animal."<<endl;
cout<<" 2. Afiseaza toate custile. "<<endl;
cout<<" 3. Afisare animale hranite(4/ora) si custi ingrijite(2/ora)."<<endl;
cout<<" --------------------------------------------------------------------------------------------"<<endl;
}
void Ui::add(){
string nume, zona, tip;
cout<<"Dati numele: ";
cin>>nume;
cout<<"Dati zona: ";
cin>>zona;
cout<<"Dati tipul ";
cin>>tip;
ctrl.addCusca(true, true, nume, zona, tip);
}
void Ui::get(){
vector<Cusca> custii = ctrl.getCusti();
for(int i=0; i<custii.size(); i++)
cout<<custii[i];
cout<<endl;
}
void Ui::program(){
int a=0,b=0;
vector<Cusca> custii = ctrl.programLucru(a,b);
for(int i=0; i<custii.size(); i++)
cout<<custii[i];
cout<<endl;
cout<<"Animale hranite: "<<a<<endl<<"Custi curatate: "<<b<<endl;
}
void Ui::run(){
int com;
bool quit = true;
while(quit){
mainSupport();
cout<<"Dati comanda: ";
cin>>com;
ctrl.readFile();
switch(com){
case 0:
cout<<endl;
cout<<"bye bye";
quit = false;
break;
case 1:
add();
break;
case 2:
get();
break;
case 3:
program();
break;
}
}
}
| true |
341d28cfedbecdd8ba1c02dffe1eee7dc736af71
|
C++
|
FOOZBY/2ndlaba
|
/2ndlaba.cpp
|
UTF-8
| 407 | 2.640625 | 3 |
[] |
no_license
|
#include <iostream>
#include <cmath>
using namespace std;
#define PI 3.14159265
int main()
{
setlocale(0, "");
double x,y,g;
cout << "Введите x, y: " << endl;
cout << "x: "; cin >> x;
cout << "y: "; cin >> y;
g = 5 * atan(x) - atan(y) / 4;
cout << "g = " << g << " rad" << endl;
system("pause");
return 0;
}
| true |
255f3cd4924fc1360939f9d6a0bdb77484476d6e
|
C++
|
gabkk/Gbemulator
|
/srcs/main.cpp
|
UTF-8
| 669 | 2.609375 | 3 |
[] |
no_license
|
# include "../includes/Gbmu.class.hpp"
# include "../includes/Registers.class.hpp"
# include <iostream>
//int main()
int main(int argc, char *argv[])
{
//Registers reg;
//uint8_t t = 8;
//t = reg.getA();
//std::cout << reg;
//reg.setAF(0x1234);
//reg.setBC(0x1234);
//reg.setDE(0x1234);
//reg.setHL(0x1234);
//std::cout << reg;
Gbmu::Gb gb;
std::string path;
if (argc != 2)
{
std::cout << "Gbmu Should take a cartridge as parameter and can't take more than 1 cartridge" << std::endl;
return(0);
}
path = argv[1];
try
{
gb.load(path);
}
catch (std::exception& e)
{
std::perror("File opening failed");
}
return(0);
}
| true |
e46ea29f66599f786f55ef5592c38ab8a1422b79
|
C++
|
aeremenok/a-team-777
|
/09/oot/eav_labs/lab3/src/Sketcher/Elements.cpp
|
UTF-8
| 4,044 | 2.734375 | 3 |
[] |
no_license
|
// Implementations of the element classes
#include "stdafx.h"
//////////////////////////////////////////////////////////////////////////
#include "OurConstants.h"
#include "Elements.h"
#include <math.h>
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_SERIAL(CElement, CObject, VERSION_NUMBER)
//////////////////////////////////////////////////////////////////////////
// Add definitions for member functions here
// CLine class constructor
//##ModelId=4770E2080334
CLine::CLine(CPoint Start, CPoint End, COLORREF aColor)
{
m_Color = aColor; // Set line color
m_Pen = 1; // Set pen width
resize(Start, End);
}
// Draw a CLine object
//##ModelId=4770E2080328
void CLine::Draw(CDC* pDC, CElement* pElement, bool isIdVisible)
{
// Create a pen for this object and
// initialize it to the object color and line width of 1 pixel
CPen aPen;
if(!aPen.CreatePen(PS_SOLID, m_Pen, m_Color))
{
// Pen creation failed. Abort the program.
AfxMessageBox("Pen creation failed drawing a line", MB_OK);
AfxAbort();
}
CPen* pOldPen = pDC->SelectObject(&aPen); // Select the pen
// Now draw the line
pDC->MoveTo(m_StartPoint);
pDC->LineTo(m_EndPoint);
pDC->SelectObject(pOldPen); // Restore the old pen
}
//##ModelId=4770E208032D
void CLine::Move( CSize& aSize )
{
m_StartPoint += aSize; // Move the start point
m_EndPoint += aSize; // and the end point
CElement::Move(aSize);
}
// Get the bounding rectangle for an element
//##ModelId=4770E20802FE
CRect CElement::GetBoundRect()
{
CRect BoundingRect; // Object to store bounding rectangle
BoundingRect = m_EnclosingRect; // Store the enclosing rectangle
// Increase the rectangle by the pen width
BoundingRect.InflateRect(m_Pen, m_Pen);
return BoundingRect; // Return the bounding rectangle
}
// CRectangle class constructor
//##ModelId=4770E2080363
CRectangle::CRectangle(CPoint Start, CPoint End, COLORREF aColor)
{
m_Color = aColor; // Set rectangle color
m_Pen = 1; // Set pen width
CElement::resize(Start, End);
}
// Draw a CRectangle object
//##ModelId=4770E2080353
void CRectangle::Draw(CDC* pDC, CElement* pElement)
{
// Create a pen for this object and
// initialize it to the object color and line width of 1 pixel
CPen aPen;
if(!aPen.CreatePen(PS_SOLID, m_Pen, m_Color))
{ // Pen creation failed
AfxMessageBox("Pen creation failed drawing a rectangle", MB_OK);
AfxAbort();
}
// Select the pen
CPen* pOldPen = pDC->SelectObject(&aPen);
// Select the brush
CBrush* pOldBrush = (CBrush*)pDC->SelectStockObject(NULL_BRUSH);
// Now draw the rectangle
pDC->Rectangle(m_EnclosingRect);
pDC->SelectObject(pOldBrush); // Restore the old brush
pDC->SelectObject(pOldPen); // Restore the old pen
}
//##ModelId=4770E2080357
void CRectangle::Move( CSize& aSize )
{
CElement::Move( aSize );
}
//##ModelId=4770E20802EA
bool CElement::operator==(const CElement& rhs) const
{
return
this->m_Color == rhs.m_Color &&
this->m_EnclosingRect == rhs.m_EnclosingRect &&
this->m_Pen == rhs.m_Pen;
}
//##ModelId=4770E2080304
void CElement::Move( CSize& aSize )
{
m_EnclosingRect += aSize;
}
//##ModelId=4770E20802E6
void CElement::resize( CPoint Start, CPoint End )
{
m_EnclosingRect = CRect(Start, End);
m_EnclosingRect.NormalizeRect();
}
//##ModelId=4770E2080324
void CLine::resize(CPoint Start, CPoint End)
{
m_StartPoint = Start;
m_EndPoint = End;
CElement::resize(Start, End);
}
//##ModelId=4770E2080308
void CElement::Serialize(CArchive& ar)
{
if (ar.IsStoring())
{ // storing code
ar << m_Color
<< m_EnclosingRect
<< m_Pen;
}
else
{ // loading code
ar >> m_Color
>> m_EnclosingRect
>> m_Pen;
}
}
| true |
b754ef14670e8d30bc7ae75a0845f9f5303b8851
|
C++
|
PasserByJia/algorithm-train
|
/EC/PAT1033/src/PAT1033.cpp
|
UTF-8
| 1,155 | 2.765625 | 3 |
[] |
no_license
|
//============================================================================
// Name : PAT1033.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <bits/stdc++.h>
using namespace std;
/*
* TIE.
7_This_is_a_test.
*/
int main() {
string a ,b;
getline(cin,a);
getline(cin,b);
int flag =a.find('+');
for(int i=0;i<b.length();i++){
if(flag==-1){
if('0'<=b[i]&&b[i]<='9'&&a.find(b[i])!=-1){
continue;
}else if('A'<=b[i]&&b[i]<='Z'&&a.find(b[i])!=-1){
continue;
}else if('a'<=b[i]&&b[i]<='z'&&a.find(b[i]-32)!=-1){
continue;
}else if((b[i]=='_'||b[i]=='.'||b[i]=='-'||b[i]==',')&&a.find(b[i])!=-1){
continue;
}
cout << b[i];
}else{
if('A'<=b[i]&&b[i]<='Z'){
continue;
}else if('0'<=b[i]&&b[i]<='9'&&a.find(b[i])!=-1){
continue;
}else if('a'<=b[i]&&b[i]<='z'&&a.find(b[i]-32)!=-1){
continue;
}else if((b[i]=='_'||b[i]=='.'||b[i]=='-'||b[i]==',')&&a.find(b[i])!=-1){
continue;
}
cout << b[i];
}
}
return 0;
}
| true |
b981f19632da84c5fa2e8b218d6795cfc53b4565
|
C++
|
Jawshouamoua/AdvPgm
|
/ds/midterm/fallMidterm.cpp
|
UTF-8
| 1,113 | 3.6875 | 4 |
[] |
no_license
|
#include <iostream>
#include "List.h"
using namespace std;
/*
* Question 1
*
* The big-O of:
* non-member function = 18*N + 3
* There are 3 initial steps for setting up variables and 18 steps
* for each iteration of the while loop which iterates N times.
*
* member function = 10*(N/2) + 8
* There are 8 initial steps for setting up variables and 10 steps
* for each iteration of the for loop which iterates N/2 times.
*
*
*/
void reverseList(List<int> &l) ;
int main() {
List<int> list ;
List<int>::iterator itr = list.begin() ;
for(int i=0; i < 10; i++)
list.insert(itr, i ) ;
//cout << list.size() << endl ;
//cout << list.front() << endl ;
/*
itr = list.begin() ;
for(int i=0; i< 10; i++) {
list.insert(itr, list.back()) ;
list.pop_back() ;
}
*/
reverseList(list) ;
list.reverse() ;
itr = list.begin() ;
while(itr != list.end()) {
cout << *itr++ << endl ;
list.pop_front() ;
}
}
void reverseList(List<int> & l) {
List<int>::iterator itr = l.begin() ;
int i = 0 ;
while(i < l.size()) {
l.insert(itr, l.back()) ;
l.pop_back() ;
i++;
}
}
| true |
0bdccddd12d846c7e62779f0122182417c72decf
|
C++
|
blockspacer/Kaboom
|
/KaboomServer/src/messaging/MessageHandlerChain.cpp
|
UTF-8
| 377 | 2.6875 | 3 |
[] |
no_license
|
#include "MessageHandlerChain.h"
#include "MessageHandler.h"
void MessageHandlerChain::addHandler(MessageHandler *handler) {
handlers.push_back(handler);
}
bool MessageHandlerChain::handle(const Message &message) const {
for (MessageHandler *handler : handlers) {
if (handler->handle(message)) {
return true;
}
}
return false;
}
| true |
41a72b97cba3c90e3dca59e80716e8c1cf6cd640
|
C++
|
syedfairozpasha/refresh_CplusPlus
|
/FifthFile.cpp
|
UTF-8
| 382 | 2.875 | 3 |
[] |
no_license
|
#include<iostream>
using namespace std;
int main()
{
int *intptr;
float *fltptr;
int p[3] = {1,2,3};
float f[3] = {11.11,22.22,33.33};
cout<<sizeof(intptr)<<endl;
cout<<sizeof(fltptr)<<endl;
intptr = (int*)f;
fltptr = (float*)p;
//cout<<intptr[1]<<endl<<fltptr[1];
cout<<sizeof(intptr)<<endl;
cout<<sizeof(fltptr)<<endl;
return 0;
}
| true |
795bf3d4c0860d434d0bcef65188c50f17ab7f01
|
C++
|
BullynckVictor/VulkanRave
|
/VulkanRave/Engine/Utilities/source/Timer.cpp
|
UTF-8
| 434 | 2.5625 | 3 |
[] |
no_license
|
#include "Engine/Utilities/Timer.h"
rv::Timer::Timer()
:
last(now())
{
}
float rv::Timer::Peek() const
{
return std::chrono::duration<float>(now() - last).count();
}
float rv::Timer::Mark()
{
auto temp = last;
return std::chrono::duration<float>((last = now()) - temp).count();
}
void rv::Timer::Reset()
{
last = now();
}
std::chrono::steady_clock::time_point rv::Timer::now()
{
return std::chrono::steady_clock::now();
}
| true |
874c448cfb243acc8460f8dc30f422449dc1c991
|
C++
|
etienne-p/MecanicTree
|
/src/RingBuffer.cpp
|
UTF-8
| 2,898 | 3.453125 | 3 |
[] |
no_license
|
//
// RingBuffer.cpp
// ofForest
//
// Created by Etienne on 2014-12-15.
//
//
#include "RingBuffer.h"
template <typename T>
RingBuffer<T>::RingBuffer(int size) {
_data = new T[size];
memset( _data, 0, size * sizeof(T));
_size = size;
_readPtr = 0;
_writePtr = 0;
_writeSamplesAvail = size;
}
template <typename T>
RingBuffer<T>::~RingBuffer() {
delete[] _data;
}
// Set all data to 0 and flag buffer as empty.
template <typename T>
bool RingBuffer<T>::Empty() {
memset( _data, 0, _size * sizeof(T));
_readPtr = 0;
_writePtr = 0;
_writeSamplesAvail = _size;
return true;
}
template <typename T>
int RingBuffer<T>::Read(T * dataPtr, int numSamples) {
// If there's nothing to read or no data available, then we can't read anything.
if( dataPtr == 0 || numSamples <= 0 || _writeSamplesAvail == _size ){
return 0;
}
int readBytesAvail = _size - _writeSamplesAvail;
// Cap our read at the number of bytes available to be read.
if( numSamples > readBytesAvail ){
numSamples = readBytesAvail;
}
// Simultaneously keep track of how many bytes we've read and our position in the outgoing buffer
if(numSamples > _size - _readPtr){
int len = _size-_readPtr;
memcpy(dataPtr, _data+_readPtr, len * sizeof(T));
memcpy(dataPtr+len, _data, (numSamples-len) * sizeof(T));
} else {
memcpy(dataPtr, _data+_readPtr, numSamples * sizeof(T));
}
_readPtr = (_readPtr + numSamples) % _size;
_writeSamplesAvail += numSamples;
return numSamples;
}
// Write to the ring buffer. Do not overwrite data that has not yet
// been read.
template <typename T>
int RingBuffer<T>::Write(T * dataPtr, int numSamples) {
// If there's nothing to write or no room available, we can't write anything.
if( dataPtr == 0 || numSamples <= 0 || _writeSamplesAvail == 0 ){
return 0;
}
// Cap our write at the number of bytes available to be written.
if( numSamples > _writeSamplesAvail ){
numSamples = _writeSamplesAvail;
}
// Simultaneously keep track of how many bytes we've written and our position in the incoming buffer
if(numSamples > _size - _writePtr){
int len = _size-_writePtr;
memcpy(_data+_writePtr, dataPtr, len * sizeof(T));
memcpy(_data, dataPtr+len, (numSamples-len) * sizeof(T));
} else {
memcpy(_data+_writePtr, dataPtr, numSamples * sizeof(T));
}
_writePtr = (_writePtr + numSamples) % _size;
_writeSamplesAvail -= numSamples;
return numSamples;
}
template <typename T>
int RingBuffer<T>::GetSize() {
return _size;
}
template <typename T>
int RingBuffer<T>::GetWriteAvail() {
return _writeSamplesAvail;
}
template <typename T>
int RingBuffer<T>::GetReadAvail() {
return _size - _writeSamplesAvail;
}
| true |
0770018bbe391781cc475b869b0f9e262e178e36
|
C++
|
ideechaniz/repasoQt
|
/SignalSlots/persona.h
|
UTF-8
| 528 | 2.75 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
#ifndef PERSONA_H
#define PERSONA_H
#include <QObject>
class Persona : public QObject
{
Q_OBJECT
public:
explicit Persona(QObject *parent = nullptr);
void setNombre(const QString &nombre)
{
m_nombre=nombre;
}
void habla(const QString &palabras);
signals:
void hablo(QString);// todas las señales son void y no se pone la variable solo el tipo.
public slots:
void escucha(const QString &palabras); // estos son metodos normales.
private:
QString m_nombre;
};
#endif // PERSONA_H
| true |
c7d15742c1ff9b677294c07aca4936f1b13596ed
|
C++
|
ardasdasdas/youtube-cpp
|
/Ders-12/04.cpp
|
UTF-8
| 233 | 2.546875 | 3 |
[] |
no_license
|
#include<iostream>
using namespace std;
int main() {
char sehir[] = "ESKISEHIR";
cout << sehir << endl;
cout << "*******************" << endl;
for (int i = 0; i < 10; i++)
{
cout << sehir[i] << endl;
}
system("pause");
}
| true |
77b6ede095e6a0940d08e3f29c0cf560290b397b
|
C++
|
SJ0000/PS
|
/BOJ/BOJ_2583.cpp
|
UTF-8
| 1,155 | 2.53125 | 3 |
[] |
no_license
|
#include cstdio
#include iostream
#include algorithm
#include string
#include vector
#include queue
#include map
#include string.h
using namespace std;
int a[101][101];
bool check[101][101];
int dx[4] = { 0,0,1,-1 };
int dy[4] = { 1,-1,0,0 };
int m, n;
int sz = 0;
void set(int x1, int y1, int x2, int y2) {
for (int i = y1; i y2; i++) {
for (int j = x1; j x2; j++) {
a[i][j] = 1;
check[i][j] = true;
}
}
}
void dfs(int x, int y) {
sz++;
check[x][y] = true;
int ax, ay;
for (int i = 0; i 4; i++) {
ax = x + dx[i]; ay = y + dy[i];
if (0 = ax && ax m && 0 = ay && ay n && !check[ax][ay]) {
dfs(ax, ay);
}
}
}
int main()
{
memset(a, 0, sizeof(a));
memset(check, false, sizeof(check));
int t;
scanf(%d %d %d, &m, &n, &t);
int x1, x2, y1, y2;
while (t-- 0) {
scanf(%d %d %d %d, &x1, &y1, &x2, &y2);
set(x1, y1, x2, y2);
}
vectorint ret;
for (int i = 0; i m; i++) {
for (int j = 0; j n; j++) {
if (check[i][j] == true) {
continue;
}
dfs(i, j);
ret.push_back(sz);
sz = 0;
}
}
sort(ret.begin(), ret.end());
printf(%dn, ret.size());
for (int i ret) {
printf(%d , i);
}
return 0;
}
| true |
0c36326f6a10c45a200cbadcfc9bcb53766e91d4
|
C++
|
ldtg/tallerSIU
|
/src/server_SIUGuaramini.h
|
UTF-8
| 1,110 | 2.84375 | 3 |
[] |
no_license
|
#ifndef TP3_APP_SIUGUARAMINI_H
#define TP3_APP_SIUGUARAMINI_H
#include <string>
#include "server_IdUsuario.h"
#include "server_IdMateria.h"
class SIUGuaramini { //Interfaz compartida entre monitorSIU y realSIU
public:
// El usuario inscribidor, inscribe al alumno idALumno en la materia idMateria
// retorna la respuesta del sistema como string
virtual std::string inscribir(const IdUsuario &idInscribidor, const IdUsuario
&idAlumno, const IdMateria &idMateria) = 0;
// El usuario desinscribidor, desinscribe al alumno idALumno
// de la materia idMateria retorna la respuesta del sistema como string
virtual std::string desinscribir(const IdUsuario &idDesinscribidor, const
IdUsuario &idAlumno, const IdMateria &idMateria) = 0;
// Lista las materias en el sistema
virtual std::string listarMaterias() const = 0;
// Lista las inscripciones para el usuario.
virtual std::string listarInscripciones(const IdUsuario &usuario) const = 0;
// Retorna true si el usuario existe en el sistema
virtual bool existeElUsuario(const IdUsuario &id) const = 0;
};
#endif //TP3_APP_SIUGUARAMINI_H
| true |
602ec113bb1008f673566485b38a6547b0b7e8e9
|
C++
|
root-a/LTU-labs
|
/qt_ai_network/ai1_statemachine/code/StateMachine.h
|
WINDOWS-1258
| 2,867 | 3.515625 | 4 |
[
"Apache-2.0"
] |
permissive
|
#pragma once
#include <cassert>
#include <string>
#include "State.h"
#include "Telegram.h"
template <class entity_type>
class StateMachine
{
public:
StateMachine(entity_type* owner) :owner(owner),
currentState(NULL),
previousState(NULL),
globalState(NULL)
{}
virtual ~StateMachine(){}
//use these methods to initialize the FSM
void SetCurrentState(State<entity_type>* s){ currentState = s; }
void SetGlobalState(State<entity_type>* s) { globalState = s; }
void SetPreviousState(State<entity_type>* s){ previousState = s; }
//call this to update the FSM
void Update()const
{
//if a global state exists, call its execute method, else do nothing
if (globalState) globalState->Execute(owner);
//same for the current state
if (currentState) currentState->Execute(owner);
}
bool HandleMessage(const Telegram& msg)const
{
//first see if the current state is valid and that it can handle
//the message
if (currentState && currentState->OnMessage(owner, msg))
{
return true;
}
//if not, and if a global state has been implemented, send
//the message to the global state
if (globalState && globalState->OnMessage(owner, msg))
{
return true;
}
return false;
}
//change to a new state
void ChangeState(State<entity_type>* pNewState)
{
assert(pNewState && "<StateMachine::ChangeState>:trying to assign null state to current");
//std::cout << GetNameOfCurrentState();
//keep a record of the previous state
previousState = currentState;
//call the exit method of the existing state
currentState->Exit(owner);
//change state to the new state
currentState = pNewState;
//call the entry method of the new state
currentState->Enter(owner);
}
//change state back to the previous state
void RevertToPreviousState()
{
ChangeState(previousState);
}
//accessors
State<entity_type>* CurrentState() const{ return currentState; }
State<entity_type>* GlobalState() const{ return globalState; }
State<entity_type>* PreviousState() const{ return previousState; }
//returns true if the current states type is equal to the type of the
//class passed as a parameter.
bool isInState(const State<entity_type>& st) const
{
if (typeid(*currentState) == typeid(st)) return true;
return false;
}
//only ever used during debugging to grab the name of the current state
std::string GetNameOfCurrentState() const
{
std::string s(typeid(*currentState).name());
//remove the 'class ' part from the front of the string
if (s.size() > 5)
{
s.erase(0, 6);
}
return s;
}
private:
//a pointer to the agent that owns this instance
entity_type* owner;
State<entity_type>* currentState;
//a record of the last state the agent was in
State<entity_type>* previousState;
//this state logic is called every time the FSM is updated
State<entity_type>* globalState;
};
| true |
5dfba7918aca6614f2f5734f41c75ccc517fca0f
|
C++
|
GuoHuanyu/Introduction-of-algorithm
|
/Introdution to algorithm/Graphl.h
|
UTF-8
| 2,269 | 3.515625 | 4 |
[] |
no_license
|
#pragma once
#include"Graph.h"
#include<list>
#include<limits>
class Graphl : public Graph {
private:
std::list<Edge>** vertex; // List headers
int numVertex, numEdge; // Number of vertices, edges
int *mark; // Pointer to mark array
std::list<Edge>::iterator it;
public:
Graphl(int numVert)
{
Init(numVert);
}
~Graphl() { // Destructor
delete[] mark; // Return dynamically allocated memory
for (int i = 0; i<numVertex; i++)
delete vertex[i];
delete[] vertex;
}
void Init(int n)
{
int i;
numVertex = n;
numEdge = 0;
mark = new int[n]; // Initialize mark array
for (i = 0; i<numVertex; i++) mark[i] = std::numeric_limits<int>::max();
// Create and initialize adjacency lists
vertex = (std::list<Edge>**) new std::list<Edge>*[numVertex];
for (i = 0; i<numVertex; i++)
vertex[i] = new std::list<Edge>();
}
int n() { return numVertex; } // Number of vertices
int e() { return numEdge; } // Number of edges
int first(int v) { // Return first neighbor of "v"
if (vertex[v]->empty())
return n(); // No neighbor
it=vertex[v]->begin();
Edge eit = *it;
return eit.vertex();
}
// Get v’s next neighbor after w
int next(int v, int w) {
Edge eit;
if (isEdge(v, w)) {
if (++it!= vertex[v]->end())
{
eit = *it;
return eit.vertex();
}
}
return n(); // No neighbor
}
// Set edge (i, j) to "weight"
void setEdge(int i, int j, int weight) {
Edge currEdge(j, weight);
if (isEdge(i, j))
{ // Edge already exists in graph
vertex[i]->remove(*it);
vertex[i]->push_back(currEdge);
}
else
{ // Keep neighbors sorted by vertex index
numEdge++;
vertex[i]->push_back(currEdge);
}
}
void delEdge(int i, int j) { // Delete edge (i, j)
if (isEdge(i, j)) {
vertex[i]->remove(*it);
numEdge--;
}
}
bool isEdge(int i, int j) { // Is (i,j) an edge?
Edge eit;
for (it=vertex[i]->begin();it!=vertex[i]->end();++it)
{ // Check whole list
Edge temp = *it;
if (temp.vertex() == j) return true;
}
return false;
}
int weight(int i, int j) { // Return weight of (i, j)
Edge curr;
if (isEdge(i, j)) {
curr = *it;
return curr.weight();
}
else return 0;
}
int getMark(int v) { return mark[v]; }
void setMark(int v, int val) { mark[v] = val; }
};
| true |
f017a6aed413e9a67334d780584baf66896181b6
|
C++
|
notwatermango/Kattis-Problem-Archive
|
/below2.1/dicegame.cc
|
UTF-8
| 289 | 2.984375 | 3 |
[
"Apache-2.0"
] |
permissive
|
#include <iostream>
using namespace std;
int main(){
int a,b,c,d,e,f,g,h;
cin>>a>>b>>c>>d>>e>>f>>g>>h;
if(a+b+c+d>e+f+g+h){
cout<<"Gunnar";
}
else if (a+b+c+d==e+f+g+h)
{
cout<<"Tie";
}
else{
cout<<"Emma";
}
return 0;
}
| true |
eb3fbc4359b519f3d0f22464f52675e4a587d381
|
C++
|
MSC-CQU/AnEngine
|
/AEngine/DTimer.h
|
UTF-8
| 1,563 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#ifndef __DTIMER_H__
#define __DTIMER_H__
#include"onwind.h"
using namespace std;
class DTimer : public NonCopyable
{
LARGE_INTEGER qpcFrequency;
LARGE_INTEGER qpcLastTime;
UINT64 qpcMaxDelta;
// 时间数据源使用QPC单元
UINT64 elapsedTicks;
UINT64 totalTicks;
UINT64 leftOverTicks; // ???
UINT64 qpcSecondCounter;
UINT32 FrameCount;
UINT32 framesPerSecond;
UINT32 framesThisSecond;
bool isFixedTimeStep;
UINT64 targetElapsedTicks;
// 用于配置固定帧率模式
public:
DTimer();
~DTimer();
const UINT64 GetElapsedTicks();
const double GetElapsedSeconds();
// 获取自上次调用以来所经过的时间
const UINT64 GetTotalTicks();
const double GetTotalSeconds();
// 获取程序启动后的时间
UINT32 GetFrameCount();
// 获取程序启动以来更新的帧数
UINT32 GetFramePerSecond();
// 获取帧率
void SetFixedFramerate(bool _isFixedTimeStep);
// 设置是否使用固定帧率
void SetTargetElapsedTicks(UINT64 _targetElapsed);
void SetTargetElapsedSeconds(double _targetElapsed);
// 设置更新频率
static const UINT64 TicksPerSecond = 1000000;
// 设置每秒使用1000000个时钟周期
static double TicksToSeconds(UINT64 _ticks);
static UINT64 SecondsToTicks(double _seconds);
void ResetElapsedTime();
// 在长时间中断(如阻塞IO、线程中断)后调用以追赶更新进度
typedef void(*LpUpdateFunc) (void);
void Tick(LpUpdateFunc _update);
// 更新计时器状态,调用指定次数的update函数(OnUpdate)
};
#endif // !__DTIMER_H__
| true |
78b5e7d903379006b2fa5115561b018b3726221a
|
C++
|
matt-hoiland/CS360
|
/labs/3_Threaded_Web_Server/Server.h
|
UTF-8
| 2,062 | 2.765625 | 3 |
[] |
no_license
|
/*
* Server.h
*
* Created on: Jan 26, 2016
* Author: matt
*/
#ifndef SERVER_H_
#define SERVER_H_
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include "ClientHandler.h"
#include "ClientQueue.h"
using namespace std;
class Server {
private:
bool debug;
unsigned int port;
const char* dir;
ClientQueue* queue;
int server;
bool serving;
void create() {
struct sockaddr_in serverAddress;
memset(&serverAddress, 0, sizeof(serverAddress));
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(port);
serverAddress.sin_addr.s_addr = INADDR_ANY;
server = socket(PF_INET, SOCK_STREAM, 0);
if (!server) {
perror("socket");
exit(-1);
}
int reuse = 1;
if (setsockopt(server, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0) {
perror("setsockopt");
exit(-1);
}
if (bind(server, (const struct sockaddr*) &serverAddress, sizeof(serverAddress)) < 0) {
perror("bind");
exit(-1);
}
if (listen(server, SOMAXCONN) < 0) {
perror("listen");
exit(-1);
}
if (debug) cout << "Socket successfully created! Ready to server!" << endl;
}
void serve() {
while (serving) {
struct sockaddr_in clientAddress;
socklen_t clientLength = sizeof(clientAddress);
int client = accept(server, (struct sockaddr*) &clientAddress, &clientLength);
if (!client) {
perror("accept");
//exit(-1);
}
if (debug) cout << "Client accepted!" << endl;
ClientHandler* handler = new ClientHandler(client, dir, debug);
queue->enqueue(handler);
}
closeServer();
}
void closeServer() {
}
public:
Server(bool debug, unsigned int port, unsigned int connections, const char* dir) :
debug(debug), port(port), dir(dir), server(0), serving(true) {
queue = new ClientQueue(debug, connections);
}
~Server() {
delete queue;
}
ClientQueue* getQueue() { return queue; }
void run() {
create();
serve();
}
void stop() {
}
};
#endif /* SERVER_H_ */
| true |
d4102673250c6db1ad316f880af8db9fa218cf48
|
C++
|
sdimosik/spbspu-labs-2020-904-4
|
/vasilevskaya.katya/A1/triangle.hpp
|
UTF-8
| 531 | 2.875 | 3 |
[] |
no_license
|
#ifndef A1_TRIANGLE_H
#define A1_TRIANGLE_H
#include "shape.hpp"
#include "base-types.hpp"
class Triangle : public Shape
{
public:
Triangle(const point_t & vertex_1, const point_t & vertex_2, const point_t & vertex_3);
double getArea() const override;
rectangle_t getFrameRect() const override;
point_t getPosition() const;
void move(const point_t & point) override;
void move(const double dx, const double dy) override;
void printFigure() const override;
private:
point_t a_, b_, c_;
point_t pos_;
};
#endif
| true |
cd6258cc1e7d3090e6318ea39437ec7772ad87d0
|
C++
|
mevoroth/meet-minecraft-bots
|
/_minecraft/src/actors/GroupActor.cpp
|
UTF-8
| 674 | 2.828125 | 3 |
[] |
no_license
|
#include "GroupActor.hpp"
using namespace DatNS;
bool GroupActor::add(GroupElement* actor)
{
if (full())
{
return false;
}
_actors.push_back(actor);
return true;
}
bool GroupActor::remove(GroupElement* actor)
{
if (one())
{
return false;
}
_actors.remove(actor);
return true;
}
inline bool GroupActor::full() const
{
return _actors.size() >= MAX;
}
inline bool GroupActor::one() const
{
return _actors.size() <= MIN;
}
NYVert3Df GroupActor::getPosition()
{
NYVert3Df distance;
for (list<GroupElement*>::const_iterator it = _actors.begin();
it != _actors.end();
++it)
{
distance += (*it)->getPosition();
}
return distance / _actors.size();
}
| true |
c548f3dd19491d986d6c481d5f549a3a0c8858ec
|
C++
|
nathanrw/ld-shared
|
/include/filesystem/Path.hpp
|
UTF-8
| 247 | 3.015625 | 3 |
[] |
no_license
|
#pragma once
#include <string>
namespace filesystem {
/**
* Type safe representation of a path.
*/
class Path {
public:
explicit Path(std::string path);
std::string path() const;
private:
std::string m_path;
};
}
| true |
0994913b685a26f80253406ffa834e03d5086d22
|
C++
|
syordya/lab_ADA
|
/practica_09/fibonnaci_recursivo.cpp
|
UTF-8
| 207 | 2.859375 | 3 |
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
int fibonnacci(int n)
{
if (n == 0) return 0;
if (n == 1) return 1;
return (fibonnacci(n-1)+ fibonnacci(n-2));
}
int main()
{
cout<<fibonnacci(50)<<endl;
}
| true |
e1b8d83f8ae094eb08eaa14fd4a98679f54cb7fc
|
C++
|
joe-stifler/uHunt
|
/Problem Solving Paradigm/Complete Search/Iterative (Three or more Loops, Easier)/154.cpp
|
UTF-8
| 1,972 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
/*------------------------------------------------*/
// Uva Problem No: 154
// Problem Name: Recycling
// Type: Iterative (Three or More Nested Loops, Easier) (Complete Search)
// Autor: Joe Stifler
// Data: 2017-12-10 01:12:34
// Runtime: 0.020s
// Universidade: Unicamp
/*------------------------------------------------*/
#include <bits/stdc++.h>
using namespace std;
int main() {
char c, d;
char vec[101][5];
int cont = 0, pos = 0;
while(true) {
while(c != 'e') {
scanf("%c", &c);
if (c == 'e') break;
else if (c == '#') return 0;
scanf("/%c", &d);
if (d == 'P') pos = 0;
else if (d == 'G') pos = 1;
else if (d == 'A') pos = 2;
else if (d == 'S') pos = 3;
else if (d == 'N') pos = 4;
vec[cont][pos] = c;
for (int i = 1; i <= 4; i++) {
scanf(",%c/%c", &c, &d);
if (d == 'P') pos = 0;
else if (d == 'G') pos = 1;
else if (d == 'A') pos = 2;
else if (d == 'S') pos = 3;
else if (d == 'N') pos = 4;
vec[cont][pos] = c;
}
do scanf("%c", &c);
while(c != '\n');
cont++;
}
int total, tot[cont];
for (int i = 0; i < cont; i++) {
total = 0;
for (int j = 0; j < cont; j++) {
if (i == j) continue;
for (int k = 0; k < 5; k++) {
if (vec[i][k] != vec[j][k]) total++;
}
}
tot[i] = total;
}
int menor = tot[0], indice = 0;
for (int i = 0; i < cont; i++) {
if (menor > tot[i]) {
menor = tot[i];
indice = i;
}
}
printf("%d\n", indice + 1);
do scanf("%c", &c);
while(c != '\n');
cont = 0;
}
}
| true |
3ad677acb0af6c27fd14b79c48f77b1592b0fc07
|
C++
|
Andrewpqc/pat_basic
|
/1035.cpp
|
UTF-8
| 2,444 | 3.734375 | 4 |
[
"MIT"
] |
permissive
|
/**
* 归并还是插入 暂时没有搞定
**/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
void print(int *a, size_t size){
for (int i = 0; i < size; i++)
cout << a[i] << " ";
}
bool is_eq(int *a, int *b, size_t size){
int flag = true;
for (int i = 0; i < size; i++)
if (a[i] != b[i])
flag = false;
if (flag)
return true;
else
return false;
}
bool is_insert_sort(int *a, int *mid, size_t size){
int flag = 0;
//查看初始状态是否相同
if (is_eq(a, mid, size))
flag = 1;
for (int i = 1; i < size; i++){
if (a[i - 1] > a[i]){
int temp = a[i];
int j = i;
do{
a[j] = a[j - 1];
--j;
} while (j > 0 && a[j - 1] > temp);
a[j] = temp;
}
if (flag == i){
cout << "Insertion Sort" << endl;
print(a, size);
return true;
}
//这是迭代之后的情况
if (is_eq(a, mid, size))
flag = i + 1;
}
return false;
}
void merge_sort(int *list, int length){
int i, left_min, left_max, right_min, right_max, next;
int *tmp = (int *)malloc(sizeof(int) * length);
// i为步长,1,2,4,8……
for (i = 1; i < length; i *= 2) {
for (left_min = 0; left_min < length - i; left_min = right_max){
right_min = left_max = left_min + i;
right_max = left_max + i;
if (right_max > length)
right_max = length;
next = 0;
while (left_min < left_max && right_min < right_max)
tmp[next++] = list[left_min] > list[right_min] ? list[right_min++] : list[left_min++];
while (left_min < left_max)
list[--right_min] = list[--left_max];
while (next > 0)
list[--right_min] = tmp[--next];
}
}
free(tmp);
}
int main(void)
{
// int count;
// cin>>count;
// int origin[count];//接收原始序列
// int middle[count];//接收中间序列
// for(int i=0;i<count;i++)
// cin>>origin[i];
// for(int i=0;i<count;i++)
// cin>>middle[i];
int a[5] = {2, 5, 3, 4, 2};
int mid[5] = {2, 3, 5, 4, 2};
is_insert_sort(a, mid, 5);
// for(int i=0;i<5;i++)
// cout<<a[i]<<" ";
return 0;
}
| true |