blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
0ea0e7d1872b63f6fd2845d41b8557370a798987
3058de21ed33db262d3cf611fc1281457b601528
/include/gaia_ctn_avltree.h
9ecc726e166053c50a7a67f83c9fdd2305f67214
[]
no_license
Armterla/GAIA
6a24f1f421d5cdb84c7c9f3938bc70240bf92f02
7e2e78b0f33f3e209a7a1019bb2d810ca491ebbc
refs/heads/master
2021-01-19T11:39:56.389573
2017-09-27T12:08:52
2017-09-27T12:08:52
82,270,136
2
5
null
2017-09-27T12:08:53
2017-02-17T07:33:26
C
UTF-8
C++
false
false
24,118
h
gaia_ctn_avltree.h
#ifndef __GAIA_CTN_AVLTREE_H__ #define __GAIA_CTN_AVLTREE_H__ #include "gaia_type.h" #include "gaia_assert.h" #include "gaia_iterator.h" #include "gaia_algo_extend.h" #include "gaia_ctn_pool.h" namespace GAIA { namespace CTN { template<typename _DataType, typename _SizeType, typename _HeightType, typename _ExtendType> class BasicAVLTree : public GAIA::Base { private: friend class it; friend class const_it; private: class Node : public GAIA::Base { public: GCLASS_COMPARE(t, Node) _DataType t; _HeightType h; Node* pPrev; Node* pNext; Node* pParent; }; public: typedef _DataType _datatype; typedef _SizeType _sizetype; typedef _HeightType _heighttype; typedef _ExtendType _extendtype; public: typedef BasicAVLTree<_DataType, _SizeType, _HeightType, _ExtendType> __MyType; typedef BasicPool<Node, _SizeType, _ExtendType> __PoolType; public: class it : public GAIA::ITERATOR::Iterator<_DataType> { private: friend class BasicAVLTree; public: GINL it(){this->init();} GINL virtual GAIA::BL empty() const{return m_pNode == GNIL;} GINL virtual GAIA::GVOID clear(){this->init();} GINL virtual GAIA::BL erase() { if(this->empty()) return GAIA::False; return m_pContainer->erase(*this); } GINL virtual _DataType& operator * (){return m_pNode->t;} GINL virtual const _DataType& operator * () const{return m_pNode->t;} GINL virtual GAIA::ITERATOR::Iterator<_DataType>& operator ++ () { if(m_pNode == GNIL) return *this; m_pNode = this->select_next(m_pNode); return *this; } GINL virtual GAIA::ITERATOR::Iterator<_DataType>& operator -- () { if(m_pNode == GNIL) return *this; m_pNode = this->select_prev(m_pNode); return *this; } GINL virtual GAIA::ITERATOR::Iterator<_DataType>& operator = (const GAIA::ITERATOR::Iterator<_DataType>& src){GAST(&src != this); return this->operator = (*GSCAST(const it*)(&src));} GINL virtual GAIA::BL operator == (const GAIA::ITERATOR::Iterator<_DataType>& src) const{return this->operator == (*GSCAST(const it*)(&src));} GINL virtual GAIA::BL operator != (const GAIA::ITERATOR::Iterator<_DataType>& src) const{return this->operator != (*GSCAST(const it*)(&src));} GINL it& operator = (const it& src){GAST(&src != this); m_pNode = src.m_pNode; m_pContainer = src.m_pContainer; return *this;} GINL it& operator += (_SizeType c) { GAST(!this->empty()); if(this->empty()) return *this; while(c > 0) { ++(*this); if(this->empty()) return *this; --c; } while(c < 0) { --(*this); if(this->empty()) return *this; ++c; } return *this; } GINL it& operator -= (_SizeType c) { GAST(!this->empty()); if(this->empty()) return *this; if(this->empty()) return *this; while(c > 0) { --(*this); if(this->empty()) return *this; --c; } while(c < 0) { ++(*this); if(this->empty()) return *this; ++c; } return *this; } GINL it operator + (const _SizeType& c) const { it ret = *this; ret += c; return ret; } GINL it operator - (const _SizeType& c) const { it ret = *this; ret -= c; return ret; } GINL _SizeType operator - (const it& src) const { it iter = *this; _SizeType ret = 0; for(; iter > src; --iter) ++ret; for(; iter < src; ++iter) --ret; return ret; } GINL GAIA::BL operator == (const it& src) const{return GAIA::ALGO::cmpp(m_pNode, src.m_pNode) == 0;} GINL GAIA::BL operator != (const it& src) const{return !(*this == src);} GINL GAIA::BL operator >= (const it& src) const{return GAIA::ALGO::cmpp(m_pNode, src.m_pNode) >= 0;} GINL GAIA::BL operator <= (const it& src) const{return GAIA::ALGO::cmpp(m_pNode, src.m_pNode) <= 0;} GINL GAIA::BL operator > (const it& src) const{return !(*this <= src);} GINL GAIA::BL operator < (const it& src) const{return !(*this >= src);} private: GINL virtual GAIA::ITERATOR::Iterator<_DataType>& operator ++ (GAIA::N32){++(*this); return *this;} GINL virtual GAIA::ITERATOR::Iterator<_DataType>& operator -- (GAIA::N32){--(*this); return *this;} GINL Node* select_next(Node* pNode) { if(pNode->pNext != GNIL) pNode = m_pContainer->front_node(pNode->pNext); else { for(;;) { if(pNode->pParent == GNIL) { pNode = GNIL; break; } else { if(pNode == pNode->pParent->pPrev) { pNode = pNode->pParent; break; } else pNode = pNode->pParent; } } } return pNode; } GINL Node* select_prev(Node* pNode) { if(pNode->pPrev != GNIL) pNode = m_pContainer->back_node(pNode->pPrev); else { for(;;) { if(pNode->pParent == GNIL) { pNode = GNIL; break; } else { if(pNode == pNode->pParent->pNext) { pNode = pNode->pParent; break; } else pNode = pNode->pParent; } } } return pNode; } private: GINL GAIA::GVOID init(){m_pNode = GNIL; m_pContainer = GNIL;} private: Node* m_pNode; __MyType* m_pContainer; }; class const_it : public GAIA::ITERATOR::ConstIterator<_DataType> { private: friend class BasicAVLTree; public: GINL const_it(){this->init();} GINL virtual GAIA::BL empty() const{return m_pNode == GNIL;} GINL virtual GAIA::GVOID clear(){this->init();} GINL virtual const _DataType& operator * () const{return m_pNode->t;} GINL virtual GAIA::ITERATOR::ConstIterator<_DataType>& operator ++ () { if(m_pNode == GNIL) return *this; m_pNode = this->select_next(m_pNode); return *this; } GINL virtual GAIA::ITERATOR::ConstIterator<_DataType>& operator -- () { if(m_pNode == GNIL) return *this; m_pNode = this->select_prev(m_pNode); return *this; } GINL virtual GAIA::ITERATOR::ConstIterator<_DataType>& operator = (const GAIA::ITERATOR::ConstIterator<_DataType>& src){GAST(&src != this); return this->operator = (*GSCAST(const const_it*)(&src));} GINL virtual GAIA::BL operator == (const GAIA::ITERATOR::ConstIterator<_DataType>& src) const{return this->operator == (*GSCAST(const const_it*)(&src));} GINL virtual GAIA::BL operator != (const GAIA::ITERATOR::ConstIterator<_DataType>& src) const{return this->operator != (*GSCAST(const const_it*)(&src));} GINL const_it& operator = (const const_it& src){GAST(&src != this); m_pNode = src.m_pNode; m_pContainer = src.m_pContainer; return *this;} GINL const_it& operator += (_SizeType c) { GAST(!this->empty()); if(this->empty()) return *this; while(c > 0) { ++(*this); if(this->empty()) return *this; --c; } while(c < 0) { --(*this); if(this->empty()) return *this; ++c; } return *this; } GINL const_it& operator -= (_SizeType c) { GAST(!this->empty()); if(this->empty()) return *this; while(c > 0) { --(*this); if(this->empty()) return *this; --c; } while(c < 0) { ++(*this); if(this->empty()) return *this; ++c; } return *this; } GINL const_it operator + (const _SizeType& c) const { const_it ret = *this; ret += c; return ret; } GINL const_it operator - (const _SizeType& c) const { const_it ret = *this; ret -= c; return ret; } GINL _SizeType operator - (const const_it& src) const { const_it iter = *this; _SizeType ret = 0; for(; iter > src; --iter) ++ret; for(; iter < src; ++iter) --ret; return ret; } GINL GAIA::BL operator == (const const_it& src) const{return GAIA::ALGO::cmpp(m_pNode, src.m_pNode) == 0;} GINL GAIA::BL operator != (const const_it& src) const{return !(*this == src);} GINL GAIA::BL operator >= (const const_it& src) const{return GAIA::ALGO::cmpp(m_pNode, src.m_pNode) >= 0;} GINL GAIA::BL operator <= (const const_it& src) const{return GAIA::ALGO::cmpp(m_pNode, src.m_pNode) <= 0;} GINL GAIA::BL operator > (const const_it& src) const{return !(*this <= src);} GINL GAIA::BL operator < (const const_it& src) const{return !(*this >= src);} private: GINL virtual GAIA::ITERATOR::ConstIterator<_DataType>& operator ++ (GAIA::N32){++(*this); return *this;} GINL virtual GAIA::ITERATOR::ConstIterator<_DataType>& operator -- (GAIA::N32){--(*this); return *this;} GINL const Node* select_next(const Node* pNode) { if(pNode->pNext != GNIL) pNode = m_pContainer->front_node(pNode->pNext); else { for(;;) { if(pNode->pParent == GNIL) { pNode = GNIL; break; } else { if(pNode == pNode->pParent->pPrev) { pNode = pNode->pParent; break; } else pNode = pNode->pParent; } } } return pNode; } GINL const Node* select_prev(const Node* pNode) { if(pNode->pPrev != GNIL) pNode = m_pContainer->back_node(pNode->pPrev); else { for(;;) { if(pNode->pParent == GNIL) { pNode = GNIL; break; } else { if(pNode == pNode->pParent->pNext) { pNode = pNode->pParent; break; } else pNode = pNode->pParent; } } } return pNode; } private: GINL GAIA::GVOID init(){m_pNode = GNIL; m_pContainer = GNIL;} private: const Node* m_pNode; const __MyType* m_pContainer; }; public: GINL BasicAVLTree(){this->init();} GINL BasicAVLTree(const __MyType& src){this->init(); this->operator = (src);} GINL GAIA::BL empty() const{return m_pool.empty();} GINL _SizeType size() const{return m_pool.size();} GINL const _SizeType& capacity() const{return m_pool.capacity();} GINL GAIA::GVOID clear(){m_pRoot = GNIL; m_pool.clear();} GINL GAIA::GVOID destroy(){m_pRoot = GNIL; m_pool.destroy();} GINL GAIA::BL insert(const _DataType& t, typename __MyType::it* pIter = GNIL) { if(m_pRoot == GNIL) { m_pRoot = m_pool.alloc(); m_pRoot->t = t; m_pRoot->h = 1; m_pRoot->pPrev = GNIL; m_pRoot->pNext = GNIL; m_pRoot->pParent = GNIL; if(pIter != GNIL) { pIter->m_pNode = m_pRoot; pIter->m_pContainer = this; } return GAIA::True; } else { GAIA::BL bResult = GAIA::False; Node* pResultNode; m_pRoot = this->insert_node(m_pRoot, &pResultNode, t, bResult); m_pRoot->pParent = GNIL; if(pIter != GNIL) { pIter->m_pNode = pResultNode; pIter->m_pContainer = this; } return bResult; } } GINL GAIA::BL erase(const _DataType& t) { if(m_pRoot == GNIL) return GAIA::False; GAIA::BL bResult = GAIA::False; m_pRoot = this->erase_node(m_pRoot, t, bResult); if(m_pRoot != GNIL) m_pRoot->pParent = GNIL; return bResult; } GINL GAIA::BL erase(it& iter) { if(iter.empty()) return GAIA::False; _DataType t = *iter; if(!this->erase(t)) return GAIA::False; iter = this->upper_equal(t); return GAIA::True; } GINL _DataType* find(const _DataType& t) { if(m_pRoot == GNIL) return GNIL; Node* pFinded = this->find_node(m_pRoot, t); if(pFinded == GNIL) return GNIL; return &pFinded->t; } GINL const _DataType* find(const _DataType& t) const { if(m_pRoot == GNIL) return GNIL; const Node* pFinded = this->find_node(m_pRoot, t); if(pFinded == GNIL) return GNIL; return &pFinded->t; } GINL GAIA::BL exist(const _DataType& t) const { return this->find(t) != GNIL; } GINL it findit(const _DataType& t) { it iter; if(m_pRoot == GNIL) return iter; Node* pFinded = this->find_node(m_pRoot, t); if(pFinded == GNIL) return iter; iter.m_pNode = pFinded; iter.m_pContainer = this; return iter; } GINL const_it const_findit(const _DataType& t) const { const_it iter; if(m_pRoot == GNIL) return iter; const Node* pFinded = this->find_node(m_pRoot, t); if(pFinded == GNIL) return iter; iter.m_pNode = pFinded; iter.m_pContainer = this; return iter; } GINL it upper_equal(const _DataType& t) { it iter; if(m_pRoot == GNIL) return iter; iter.m_pNode = this->lower_bound_node(m_pRoot, t); if(iter.m_pNode != GNIL) iter.m_pContainer = this; return iter; } GINL it lower_equal(const _DataType& t) { it iter; if(m_pRoot == GNIL) return iter; iter.m_pNode = this->upper_bound_node(m_pRoot, t); if(iter.m_pNode != GNIL) iter.m_pContainer = this; return iter; } GINL const_it upper_equal(const _DataType& t) const { const_it iter; if(m_pRoot == GNIL) return iter; iter.m_pNode = this->lower_bound_node(m_pRoot, t); if(iter.m_pNode != GNIL) iter.m_pContainer = this; return iter; } GINL const_it lower_equal(const _DataType& t) const { const_it iter; if(m_pRoot == GNIL) return iter; iter.m_pNode = this->upper_bound_node(m_pRoot, t); if(iter.m_pNode != GNIL) iter.m_pContainer = this; return iter; } GINL const _DataType* minimize() const{if(m_pRoot == GNIL) return GNIL; return &this->findmin(m_pRoot);} GINL _DataType* minimize(){if(m_pRoot == GNIL) return GNIL; return &this->findmin(m_pRoot);} GINL const _DataType* maximize() const{if(m_pRoot == GNIL) return GNIL; return &this->findmax(m_pRoot);} GINL _DataType* maximize(){if(m_pRoot == GNIL) return GNIL; return &this->findmax(m_pRoot);} GINL _DataType& front(){return *this->frontit();} GINL const _DataType& front() const{return *this->const_frontit();} GINL _DataType& back(){return *this->backit();} GINL const _DataType& back() const{return *this->const_backit();} GINL it frontit() { it iter; if(m_pRoot == GNIL) return iter; iter.m_pNode = this->front_node(m_pRoot); iter.m_pContainer = this; return iter; } GINL it backit() { it iter; if(m_pRoot == GNIL) return iter; iter.m_pNode = this->back_node(m_pRoot); iter.m_pContainer = this; return iter; } GINL const_it const_frontit() const { const_it iter; if(m_pRoot == GNIL) return iter; iter.m_pNode = this->front_node(m_pRoot); iter.m_pContainer = this; return iter; } GINL const_it const_backit() const { const_it iter; if(m_pRoot == GNIL) return iter; iter.m_pNode = this->back_node(m_pRoot); iter.m_pContainer = this; return iter; } GINL __MyType& operator = (const __MyType& src) { GAST(&src != this); this->clear(); if(!src.empty()) { const_it it = src.const_frontit(); for(; !it.empty(); ++it) this->insert(*it); } return *this; } GINL __MyType& operator += (const __MyType& src) { if(this == &src) GTHROW_RET(InvalidParam, *this); for(__MyType::const_it it = src.const_frontit(); !it.empty(); ++it) this->insert(*it); return *this; } GINL GAIA::N32 compare(const __MyType& src) const { if(this->size() < src.size()) return -1; else if(this->size() > src.size()) return +1; const_it srcit = this->const_frontit(); const_it dstit = src.const_frontit(); for(;;) { if(srcit.empty() || dstit.empty()) return 0; if(*srcit < *dstit) return -1; else if(*srcit > *dstit) return +1; ++srcit; ++dstit; } } GCLASS_COMPARE_BYCOMPARE(__MyType) private: GINL GAIA::GVOID init(){m_pRoot = GNIL;} GINL GAIA::GVOID rotate_prev(Node*& pNode) { Node* pTemp = pNode->pNext; pNode->pNext = pTemp->pPrev; if(pNode->pNext != GNIL) pNode->pNext->pParent = pNode; pTemp->pPrev = pNode; if(pTemp->pPrev != GNIL) pTemp->pPrev->pParent = pTemp; pNode->h = this->height(pNode); pTemp->h = this->height(pTemp); pNode = pTemp; } GINL GAIA::GVOID rotate_next(Node*& pNode) { Node* pTemp = pNode->pPrev; pNode->pPrev = pTemp->pNext; if(pNode->pPrev != GNIL) pNode->pPrev->pParent = pNode; pTemp->pNext = pNode; if(pTemp->pNext != GNIL) pTemp->pNext->pParent = pTemp; pNode->h = this->height(pNode); pTemp->h = this->height(pTemp); pNode = pTemp; } GINL _HeightType height(Node* pNode) { _HeightType prevh = pNode->pPrev == GNIL ? 0 : pNode->pPrev->h; _HeightType nexth = pNode->pNext == GNIL ? 0 : pNode->pNext->h; return GAIA::ALGO::gmax(prevh, nexth) + 1; } GINL GAIA::GVOID balance(Node*& pNode) { _HeightType prevh = pNode->pPrev == GNIL ? 0 : pNode->pPrev->h; _HeightType nexth = pNode->pNext == GNIL ? 0 : pNode->pNext->h; if(prevh > nexth + 1) { _HeightType prevnexth = pNode->pPrev->pNext == GNIL ? 0 : pNode->pPrev->pNext->h; _HeightType prevprevh = pNode->pPrev->pPrev == GNIL ? 0 : pNode->pPrev->pPrev->h; if(prevnexth > prevprevh) this->rotate_prev(pNode->pPrev); this->rotate_next(pNode); } else if(nexth > prevh + 1) { _HeightType nextprevh = pNode->pNext->pPrev == GNIL ? 0 : pNode->pNext->pPrev->h; _HeightType nextnexth = pNode->pNext->pNext == GNIL ? 0 : pNode->pNext->pNext->h; if(nextprevh > nextnexth) this->rotate_next(pNode->pNext); this->rotate_prev(pNode); } } GINL Node* front_node(Node* pNode) { if(pNode->pPrev != GNIL) return this->front_node(pNode->pPrev); else return pNode; } GINL Node* back_node(Node* pNode) { if(pNode->pNext != GNIL) return this->back_node(pNode->pNext); else return pNode; } GINL const Node* front_node(const Node* pNode) const { if(pNode->pPrev != GNIL) return this->front_node(pNode->pPrev); else return pNode; } GINL const Node* back_node(const Node* pNode) const { if(pNode->pNext != GNIL) return this->back_node(pNode->pNext); else return pNode; } GINL _DataType& findmin(Node* pNode) const { if(pNode->pPrev == GNIL) return pNode->t; return this->findmin(pNode->pPrev); } GINL _DataType& findmax(Node* pNode) const { if(pNode->pNext == GNIL) return pNode->t; return this->findmax(pNode->pNext); } GINL Node* insert_node(Node* pNode, Node** ppResultNode, const _DataType& t, GAIA::BL& bResult) { if(pNode == GNIL) { bResult = GAIA::True; Node* pNewNode = m_pool.alloc(); pNewNode->t = t; pNewNode->h = 1; pNewNode->pPrev = GNIL; pNewNode->pNext = GNIL; pNewNode->pParent = GNIL; *ppResultNode = pNewNode; return pNewNode; } if(t < pNode->t) { pNode->pPrev = this->insert_node(pNode->pPrev, ppResultNode, t, bResult); if(pNode->pPrev != GNIL) pNode->pPrev->pParent = pNode; } else if(t > pNode->t) { pNode->pNext = this->insert_node(pNode->pNext, ppResultNode, t, bResult); if(pNode->pNext != GNIL) pNode->pNext->pParent = pNode; } else { *ppResultNode = pNode; return pNode; } pNode->h = this->height(pNode); this->balance(pNode); return pNode; } GINL Node* erase_node(Node* pNode, const _DataType& t, GAIA::BL& bResult) { if(pNode == GNIL) return GNIL; if(t < pNode->t) { pNode->pPrev = this->erase_node(pNode->pPrev, t, bResult); if(pNode->pPrev != GNIL) pNode->pPrev->pParent = pNode; } else if(t > pNode->t) { pNode->pNext = this->erase_node(pNode->pNext, t, bResult); if(pNode->pNext != GNIL) pNode->pNext->pParent = pNode; } else { bResult = GAIA::True; if(pNode->h == 1) { m_pool.release(pNode); return GNIL; } else if(pNode->pPrev != GNIL && pNode->pNext == GNIL) { pNode->pPrev->pParent = pNode->pParent; Node* pTemp = pNode; pNode = pNode->pPrev; m_pool.release(pTemp); return pNode; } else if(pNode->pPrev == GNIL && pNode->pNext != GNIL) { pNode->pNext->pParent = pNode->pParent; Node* pTemp = pNode; pNode = pNode->pNext; m_pool.release(pTemp); return pNode; } else if(pNode->pPrev != GNIL && pNode->pNext != GNIL) { const _DataType& mindata = this->findmin(pNode->pNext); pNode->t = mindata; pNode->pNext = this->erase_node(pNode->pNext, pNode->t, bResult); if(pNode->pNext != GNIL) pNode->pNext->pParent = pNode; } } pNode->h = this->height(pNode); this->balance(pNode); return pNode; } GINL Node* find_node(Node* pNode, const _DataType& t) { if(t < pNode->t) { if(pNode->pPrev != GNIL) return this->find_node(pNode->pPrev, t); } else if(t > pNode->t) { if(pNode->pNext != GNIL) return this->find_node(pNode->pNext, t); } else return pNode; return GNIL; } GINL const Node* find_node(Node* pNode, const _DataType& t) const { if(t < pNode->t) { if(pNode->pPrev != GNIL) return this->find_node(pNode->pPrev, t); } else if(t > pNode->t) { if(pNode->pNext != GNIL) return this->find_node(pNode->pNext, t); } else return pNode; return GNIL; } GINL Node* lower_bound_node(Node* pNode, const _DataType& t) const { if(pNode == GNIL) return GNIL; if(pNode->t < t) return this->lower_bound_node(pNode->pNext, t); else { Node* pNew = this->lower_bound_node(pNode->pPrev, t); if(pNew == GNIL) return pNode; return pNew; } } GINL Node* upper_bound_node(Node* pNode, const _DataType& t) const { if(pNode == GNIL) return GNIL; if(pNode->t > t) return this->upper_bound_node(pNode->pPrev, t); else { Node* pNew = this->upper_bound_node(pNode->pNext, t); if(pNew == GNIL) return pNode; return pNew; } } private: Node* m_pRoot; __PoolType m_pool; public: #ifdef GAIA_DEBUG_ROUTINE GINL GAIA::BL dbg_check_balance() { if(m_pRoot == GNIL) return GAIA::True; else return this->dbg_check_balance_node(m_pRoot); } GINL GAIA::BL dbg_check_balance_node(Node* pNode) { if(pNode == GNIL) return GAIA::True; _HeightType prevh = pNode->pPrev == GNIL ? 0 : pNode->pPrev->h; _HeightType nexth = pNode->pNext == GNIL ? 0 : pNode->pNext->h; if(prevh > nexth + 1 || nexth > prevh + 1) return GAIA::False; if(!this->dbg_check_balance_node(pNode->pPrev)) return GAIA::False; if(!this->dbg_check_balance_node(pNode->pNext)) return GAIA::False; return GAIA::True; } GINL GAIA::BL dbg_check_parent() { if(m_pRoot == GNIL) return GAIA::True; else { if(m_pRoot->pParent != GNIL) return GAIA::False; return this->dbg_check_parent_node(m_pRoot); } } GINL GAIA::BL dbg_check_parent_node(Node* pNode) { if(pNode == GNIL) return GAIA::True; if(pNode->pPrev != GNIL) { if(pNode->pPrev->pParent != pNode) return GAIA::False; } if(pNode->pNext != GNIL) { if(pNode->pNext->pParent != pNode) return GAIA::False; } if(!this->dbg_check_parent_node(pNode->pPrev)) return GAIA::False; if(!this->dbg_check_parent_node(pNode->pNext)) return GAIA::False; return GAIA::True; } #endif }; } } #endif
e2c9c92cfd115cb81080611618eabee02ce8359c
0892a175b1740f2ac638249bb9eab52f2f2c5760
/Demo1/24 set容器.cpp
64059539a83814fdc5a7116b9581fc5ee3553348
[]
no_license
xiaomohaa/Demo1
a38291784eab27a2f3cb90597ffd06d9b6f8a61e
3ef6747845fdd9dbdda0e7200813d73ba3c7e2b1
refs/heads/master
2023-02-21T02:26:05.121917
2021-01-25T07:35:53
2021-01-25T07:35:53
308,578,908
0
0
null
null
null
null
GB18030
C++
false
false
2,826
cpp
24 set容器.cpp
// ///* set/ multiset 容器 //* @ set 基本概念 //* > 简介 //* - 所有元素都会在插入时自动被排序 //* > 本质 //* - set/multiset属于关联式容器,底层结构是用二叉树实现。 //* > set 和 multiset 区别 //* - set 不允许容器中有重复的元素 //* - multiset 允许容器中有重复的元素 //* @ set 构造和赋值 //* > 功能描述 //* - 创建set容器以及赋值 //* > 构造 //* - set<T> st; // 默认构造函数 //* - set(const set &st); // 拷贝构造函数 //* > 赋值 //* - set& operator=(const set &st); // 重载等号操作符 //* ! set 容器插入数据时用insert //* @ set 大小和交换 //* > 功能描述 //* - 统计set容器大小以及交换set容器 //* > 函数原型 //* - size(); // 返回容器中元素的数目 //* - empty(); // 判断容器是否为空 //* - swap(st); // 交换两个集合容器 //* @ set 插入和删除 //* > 功能描述 //* - set 容器进行插入数据和删除数据 //* > 函数原型 //* - insert(elem); // 在容器中插入元素。 //* - clear(); // 清除所有元素 //* - erase(pos); // 删除pos迭代器所指的元素,返回下一个元素的迭代器。 //* - erase(beg, end); // 删除区间[beg,end)的所有元素 ,返回下一个元素的迭代器。 //* - erase(elem); // 删除容器中值为elem的元素。 //* ! 总结 //* - 插入 --- insert //* - 删除 --- erase //* - 清空 --- clear //* @ set 查找和统计 //* > 功能描述 //* - 对set容器进行查找数据以及统计数据 //* > 函数原型 //* - find(key); // 查找key是否存在,若存在,返回该键的元素的迭代器;若不存在,返回set.end(); //* - count(key); // 统计key的元素个数(对于set,结果为0或者1) //* @ set 和 multiset 区别 //* > 学习目标 //* - 掌握set和multiset的区别 //* > 区别 //* - set 不可以插入重复数据,而 multiset 可以 //* - set 插入数据的同时会返回插入结果,表示插入是否成功 //* - multiset 不会检测数据,因此可以插入重复数据 //* @ pair 对组创建 //* > 功能描述: //* - 成对出现的数据,利用对组可以返回两个数据 //* @ 两种创建方式 //* - pair<type, type> p ( value1, value2 ); //* - pair<type, type> p = make_pair( value1, value2 ); //* @ set 容器排序 //* > 学习目标 //* - set容器默认排序规则为从小到大,掌握如何改变排序规则 //* > 主要技术点 //* - 利用仿函数,可以改变排序规则 //*/ // // //#include <iostream> //#include <set> // //using namespace std; // // //void test01() //{ // //} // // //int main(void) //{ // cout << "wocao" << endl; // // test01(); // // return 0; //}
8553188718e99edeeeacb94f26a76732a34551c4
4a379b4cd84665ef6b1ac91e5a70af60488cdf78
/qt_project/PaintMaze/level1.cpp
205988340e8fc25654695ece90ab8142fbd1a90d
[]
no_license
mchavaillaz/cplusplus
d2af864f01f6a5a1d59b91505ec4ff4fda57a054
f461c5e222e5862061e3c4842aae62d8e55c7948
refs/heads/master
2020-12-30T11:15:15.339456
2014-04-13T13:26:22
2014-04-13T13:26:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,646
cpp
level1.cpp
#include "level1.h" #include <QVector3D> #include "wall.h" #include "endobject.h" Level1::Level1() { this->timeLimitMillis = 3 * 60 * 1000; // 1 minute fillListFormNonCollidable(); fillListFormCollidable(); } void Level1::fillListFormNonCollidable() { } void Level1::fillListFormCollidable() { double xScale = 4.0; double yScale = 1.0; double zScale = -4.0; this->startingPoint = new QVector3D(10, 1.85, 10); // this->startingPoint = new QVector3D(-5 + xScale*27, 1.85, -1-zScale*27); this->goalPoint = new QVector3D(xScale*27, yScale*0, -zScale*28-1); this->endObject = new EndObject(this->goalPoint); // Wall 1 QVector3D p11(4*xScale, 0*yScale, -4*zScale); QVector3D p12(6*xScale, 0*yScale, -4*zScale); QVector3D p13(6*xScale, 0*yScale, -30*zScale); QVector3D p14(4*xScale, 0*yScale, -30*zScale); this->listShapeCollidable.append(new Wall(&p11, &p12, &p13, &p14)); // Wall 2 QVector3D p21(6*xScale, 0*yScale, -14*zScale); QVector3D p22(14*xScale, 0*yScale, -14*zScale); QVector3D p23(14*xScale, 0*yScale, -16*zScale); QVector3D p24(6*xScale, 0*yScale, -16*zScale); this->listShapeCollidable.append(new Wall(&p21, &p22, &p23, &p24)); // Wall 3 QVector3D p31(0*xScale, 0*yScale, -22*zScale); QVector3D p32(10*xScale, 0*yScale, -22*zScale); QVector3D p33(10*xScale, 0*yScale, -24*zScale); QVector3D p34(0*xScale, 0*yScale, -24*zScale); this->listShapeCollidable.append(new Wall(&p31, &p32, &p33, &p34)); // Wall 4 QVector3D p41(10*xScale, 0*yScale, -18*zScale); QVector3D p42(18*xScale, 0*yScale, -18*zScale); QVector3D p43(18*xScale, 0*yScale, -20*zScale); QVector3D p44(10*xScale, 0*yScale, -20*zScale); this->listShapeCollidable.append(new Wall(&p41, &p42, &p43, &p44)); // Wall 5 QVector3D p51(10*xScale, 0*yScale, -20*zScale); QVector3D p52(12*xScale, 0*yScale, -20*zScale); QVector3D p53(12*xScale, 0*yScale, -28*zScale); QVector3D p54(10*xScale, 0*yScale, -28*zScale); this->listShapeCollidable.append(new Wall(&p51, &p52, &p53, &p54)); // Wall 6 QVector3D p61(8*xScale, 0*yScale, -6*zScale); QVector3D p62(18*xScale, 0*yScale, -6*zScale); QVector3D p63(18*xScale, 0*yScale, -8*zScale); QVector3D p64(8*xScale, 0*yScale, -8*zScale); this->listShapeCollidable.append(new Wall(&p61, &p62, &p63, &p64)); // Wall 7 QVector3D p71(12*xScale, 0*yScale, -2*zScale); QVector3D p72(14*xScale, 0*yScale, -2*zScale); QVector3D p73(14*xScale, 0*yScale, -6*zScale); QVector3D p74(12*xScale, 0*yScale, -6*zScale); this->listShapeCollidable.append(new Wall(&p71, &p72, &p73, &p74)); // Wall 8 QVector3D p81(18*xScale, 0*yScale, -6*zScale); QVector3D p82(20*xScale, 0*yScale, -6*zScale); QVector3D p83(20*xScale, 0*yScale, -14*zScale); QVector3D p84(18*xScale, 0*yScale, -14*zScale); this->listShapeCollidable.append(new Wall(&p81, &p82, &p83, &p84)); // Wall 9 QVector3D p91(20*xScale, 0*yScale, -10*zScale); QVector3D p92(32*xScale, 0*yScale, -10*zScale); QVector3D p93(32*xScale, 0*yScale, -12*zScale); QVector3D p94(20*xScale, 0*yScale, -12*zScale); this->listShapeCollidable.append(new Wall(&p91, &p92, &p93, &p94)); // Wall 10 QVector3D p101(24*xScale, 0*yScale, 0*zScale); QVector3D p102(26*xScale, 0*yScale, 0*zScale); QVector3D p103(26*xScale, 0*yScale, -8*zScale); QVector3D p104(24*xScale, 0*yScale, -8*zScale); this->listShapeCollidable.append(new Wall(&p101, &p102, &p103, &p104)); // Wall 11 QVector3D p111(28*xScale, 0*yScale, -2*zScale); QVector3D p112(30*xScale, 0*yScale, -2*zScale); QVector3D p113(30*xScale, 0*yScale, -10*zScale); QVector3D p114(28*xScale, 0*yScale, -10*zScale); this->listShapeCollidable.append(new Wall(&p111, &p112, &p113, &p114)); // Wall 12 QVector3D p121(18*xScale, 0*yScale, -16*zScale); QVector3D p122(20*xScale, 0*yScale, -16*zScale); QVector3D p123(20*xScale, 0*yScale, -22*zScale); QVector3D p124(18*xScale, 0*yScale, -22*zScale); this->listShapeCollidable.append(new Wall(&p121, &p122, &p123, &p124)); // Wall 13 QVector3D p131(18*xScale, 0*yScale, -24*zScale); QVector3D p132(32*xScale, 0*yScale, -24*zScale); QVector3D p133(32*xScale, 0*yScale, -26*zScale); QVector3D p134(18*xScale, 0*yScale, -26*zScale); this->listShapeCollidable.append(new Wall(&p131, &p132, &p133, &p134)); // Wall 14 QVector3D p141(24*xScale, 0*yScale, -18*zScale); QVector3D p142(26*xScale, 0*yScale, -18*zScale); QVector3D p143(26*xScale, 0*yScale, -20*zScale); QVector3D p144(24*xScale, 0*yScale, -20*zScale); this->listShapeCollidable.append(new Wall(&p141, &p142, &p143, &p144)); // Wall 15 QVector3D p151(24*xScale, 0*yScale, -16*zScale); QVector3D p152(30*xScale, 0*yScale, -16*zScale); QVector3D p153(30*xScale, 0*yScale, -18*zScale); QVector3D p154(24*xScale, 0*yScale, -18*zScale); this->listShapeCollidable.append(new Wall(&p151, &p152, &p153, &p154)); // Wall 16 QVector3D p161(30*xScale, 0*yScale, -18*zScale); QVector3D p162(32*xScale, 0*yScale, -18*zScale); QVector3D p163(32*xScale, 0*yScale, -24*zScale); QVector3D p164(30*xScale, 0*yScale, -24*zScale); this->listShapeCollidable.append(new Wall(&p161, &p162, &p163, &p164)); // Border Wall 1 QVector3D pb11(-2*xScale, 0*yScale, 0*zScale); QVector3D pb12(0*xScale, 0*yScale, 0*zScale); QVector3D pb13(0*xScale, 0*yScale, -30*zScale); QVector3D pb14(-2*xScale, 0*yScale, -30*zScale); this->listShapeCollidable.append(new Wall(&pb11, &pb12, &pb13, &pb14)); // Border Wall 2 QVector3D pb21(0*xScale, 0*yScale, -30*zScale); QVector3D pb22(32*xScale, 0*yScale, -30*zScale); QVector3D pb23(32*xScale, 0*yScale, -32*zScale); QVector3D pb24(0*xScale, 0*yScale, -32*zScale); this->listShapeCollidable.append(new Wall(&pb21, &pb22, &pb23, &pb24)); // Border Wall 3 QVector3D pb31(32*xScale, 0*yScale, 0*zScale); QVector3D pb32(34*xScale, 0*yScale, 0*zScale); QVector3D pb33(34*xScale, 0*yScale, -30*zScale); QVector3D pb34(32*xScale, 0*yScale, -30*zScale); this->listShapeCollidable.append(new Wall(&pb31, &pb32, &pb33, &pb34)); // Border Wall 4 QVector3D pb41(0*xScale, 0*yScale, 2*zScale); QVector3D pb42(32*xScale, 0*yScale, 2*zScale); QVector3D pb43(32*xScale, 0*yScale, 0*zScale); QVector3D pb44(0*xScale, 0*yScale, 0*zScale); this->listShapeCollidable.append(new Wall(&pb41, &pb42, &pb43, &pb44)); }
e092188e18fc23ee8c53cb327a36f53b42a34412
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/make/old_hunk_1418.cpp
853e3abef175e58e6b0c38f0718954132c4c422b
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
260
cpp
old_hunk_1418.cpp
if (!must_make) { DEBUGPR ("No need to remake target `%s'.\n"); notice_finished_file (file); return 0; } DEBUGPR ("Must remake target `%s'.\n"); /* Now, take appropriate actions to remake the file. */ remake_file (file);
cb904277359787ee1bcd3b0c07e3807a8878c943
04cfaa229151ec3686fcb17e43c8a29fa496eb46
/behavioral/command.cpp
7daa0fc77dd626dcb44efc91fa6fa2c41b6ab1be
[]
no_license
kokoslik/patterns
2051ab4765b00ec04595af8337d2e9caa9c7c192
108b881f031a022d8274508f46f3614bf1466683
refs/heads/master
2021-01-21T11:00:23.102504
2018-03-27T18:13:54
2018-03-27T18:13:54
91,717,078
0
0
null
null
null
null
UTF-8
C++
false
false
1,215
cpp
command.cpp
#include <iostream> #include <vector> #include <map> using namespace std; class VectorWrapper { private: vector<int> vec; public: VectorWrapper() = default; void push_back() { cout<<"Enter number: "; int a; cin>>a; vec.push_back(a); } void pop_back() { vec.pop_back(); } void back() { cout<<vec.back()<<endl; } void print() { for(int i: vec) cout<<i<<' '; cout<<endl; } }; class Command { public: typedef void(VectorWrapper::*Action)(); Command(VectorWrapper* vec_, Action act_):vec(vec_),act(act_){} void execute() { (vec->*act)(); } private: VectorWrapper* vec; Action act; }; int main() { map <string, Command::Action> cmd{{"push_back",&VectorWrapper::push_back},{"pop_back",&VectorWrapper::pop_back},{"back",&VectorWrapper::back},{"print", &VectorWrapper::print}}; VectorWrapper vec; string str; while(true) { cin>>str; if(str=="quit") break; if(cmd.find(str)!=cmd.end()) { Command comm(&vec, cmd[str]); comm.execute(); } } return 0; }
201b9a083389e068128ef8b9a4a8eb538b3bcc72
f7524a76f5a6fba87ad13348d604df2e19e2c0f7
/CodeChef/Xor Equality.cpp
a7a08db1e71ba96936cbb89e2f77b3f7e4fd5367
[]
no_license
Ravi2155/competitive_coding
2a484bdc8fc061f366a26274983a81a05b17876b
90a1e4dbe590750eed69cbbd27a55369b30e797a
refs/heads/main
2023-06-04T20:32:42.476668
2021-06-27T19:06:26
2021-06-27T19:06:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,893
cpp
Xor Equality.cpp
/* Solution by Rahul Surana *********************************************************** For a given N, find the number of ways to choose an integer x from the range [0,2N−1] such that x⊕(x+1)=(x+2)⊕(x+3), where ⊕ denotes the bitwise XOR operator. Since the number of valid x can be large, output it modulo 109+7. Input The first line contains an integer T, the number of test cases. Then the test cases follow. The only line of each test case contains a single integer N. Output For each test case, output in a single line the answer to the problem modulo 10^9+7 *********************************************************** */ #include <bits/stdc++.h> #define ll long long #define vl vector<ll> #define vi vector<int> #define pi pair<int,int> #define pl pair<ll,ll> #define all(a) a.begin(),a.end() #define mem(a,x) memset(a,x,sizeof(a)) #define pb push_back #define mp make_pair #define F first #define S second #define FOR(i,a) for(int i = 0; i < a; i++) #define trace(x) cerr<<#x<<" : "<<x<<endl; #define trace2(x,y) cerr<<#x<<" : "<<x<<" | "<<#y<<" : "<<y<<endl; #define trace3(x,y,z) cerr<<#x<<" : "<<x<<" | "<<#y<<" : "<<y<<" | "<<#z<<" : "<<z<<endl; #define fast_io std::ios::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) #define MOD 1000000007 using namespace std; ll pow(ll x,ll a){ ll res = 1; a--; while(a>0){ if(a&1) res = ((x%MOD) * (res%MOD))%MOD; x=((x%MOD) * (x%MOD))%MOD ; a = a >> 1; } return res%MOD; } int main() { fast_io; int t; cin >> t; while(t--) { ll f; cin >> f; // cout << (16^15)<<" "<< (18^17) <<"\n"; // FOR(i,100) cout <<i << " ^ " << i+1 << " " << (i^(i+1))<< "\n"; cout << pow((ll)2,f) <<"\n"; } }
35850cbb59656f6258a10e460ae0b8e4768886ea
c1f57795226874ba346cf14f586beb5e0faae440
/lib/Pitch/Yin/difference.cpp
41aa20b4d12c786ffc983988e20d043d601745cc
[ "MIT" ]
permissive
ForeverRainbow/speech-analysis
1b3658bea94b64d108c722affdab17ebb12f956e
1758655b9202c1c17b06049396672bf4eb63f264
refs/heads/master
2021-05-23T12:59:51.672157
2020-04-27T18:28:52
2020-04-27T18:28:52
253,298,283
0
0
MIT
2020-04-05T17:59:06
2020-04-05T17:59:05
null
UTF-8
C++
false
false
329
cpp
difference.cpp
#include "YIN.h" using namespace Eigen; ArrayXd YIN::difference(const ArrayXd & x) { const int N = x.size(); ArrayXd acorr = autocorrelation(x); ArrayXd yin_buffer(N / 2); for (int tau = 0; tau < N / 2; ++tau) { yin_buffer(tau) = acorr(0) + acorr(1) - 2 * acorr(tau); } return yin_buffer; }
6c8ef3b6764b8b47b34723245bad707082b0109a
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_old_hunk_2308.cpp
c8f6d38209a3ce190f38da4297f437c9d9efb5f0
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
575
cpp
httpd_old_hunk_2308.cpp
"attempt to include NPH CGI script"); #if defined(OS2) || defined(WIN32) #error mod_cgid does not work on this platform. If you teach it to, look #error at mod_cgi.c for required code in this path. #else if (r->finfo.filetype == 0) return log_scripterror(r, conf, HTTP_NOT_FOUND, 0, "script not found or unable to stat"); #endif if (r->finfo.filetype == APR_DIR) return log_scripterror(r, conf, HTTP_FORBIDDEN, 0, "attempt to invoke directory as script");
0ebfe05e8277c104782ec09281fc0ec389fcf037
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
/contest/1542587474.cpp
8deea3613e304894bf76569295e39419e328887a
[]
no_license
thegamer1907/Code_Analysis
0a2bb97a9fb5faf01d983c223d9715eb419b7519
48079e399321b585efc8a2c6a84c25e2e7a22a61
refs/heads/master
2020-05-27T01:20:55.921937
2019-11-20T11:15:11
2019-11-20T11:15:11
188,403,594
2
1
null
null
null
null
UTF-8
C++
false
false
743
cpp
1542587474.cpp
#include <bits/stdc++.h> using namespace std; map<int,int>m; set<int>s; pair<int,int>p; int n,x,y,c,k=10; int main() { string a[1000]; string g,v; cin>>g; cin>>n; for(int q=0;q<n;q++) cin>>a[q]; while(k--) { for(int i=0;i<n;i++) { v=a[i]; if (v[0]==g[0]&&v[1]==g[1]) { cout<<"YES"; return 0; } if(v[1]==g[0]&&x==0) { c++; x++; } if(v[0]==g[1]&&y==0) { c++; y++; } if(c==2) { cout<<"YES"; return 0; } } } cout<<"NO"; return 0; }
d3d0cd919b76d94b5a455463a8ea65c5dfb04d34
66934b2e78e7b7667334e94b7c8f64f10810e8cd
/sniffer.cpp
9a1529690498bff750a5c3f4450ce27ff1bca4bd
[]
no_license
itamarmaouda101/packet_sniffer
0071aada1ac8beecfa11e104c4127886e575d288
f15053c27941eb484834a5ffc27f22bafe455332
refs/heads/master
2022-12-01T17:58:13.852754
2020-08-18T11:25:50
2020-08-18T11:25:50
285,844,557
0
0
null
null
null
null
UTF-8
C++
false
false
6,336
cpp
sniffer.cpp
/* * Simple Sniffer * * Simple program to illustrate how to use the Sniffer class */ #include <iostream> #include <string.h> #include "httpLib.hpp" #include "sshLib.hpp" #include <map> #include "ftpLib.hpp" #include "EthernetLibs.hpp" #include <crafter.h> #include <bits/stdc++.h> using namespace std; using namespace Crafter; /* void packet_expulison(Packet* packet){ size_t number_of_layers = packet->GetLayerCount(); const Protocol* layer_ptr; Protocol* layer = packet->GetLayer(layer_ptr); }*/ void PacketHandler(Packet* sniff_packet, void* user) { /* sniff_packet -> pointer to the packet captured */ /* user -> void pointer to the data supplied by the user */ /* Check if there is a payload */ RawLayer* raw_payload = sniff_packet->GetLayer<RawLayer>(); UDP* udp_layer = sniff_packet->GetLayer<UDP>(); Ethernet* ether_layer = sniff_packet->GetLayer<Ethernet>(); TCP* tcp_layer = sniff_packet->GetLayer<TCP>(); IP* ip_layer = sniff_packet->GetLayer<IP>(); ARP* arp_layer = sniff_packet->GetLayer<ARP>(); ICMP* icmp_layer = sniff_packet->GetLayer<ICMP>(); SLL* sll_layer = sniff_packet->GetLayer<SLL>(); if (tcp_layer) {cout << "[+] ---- TCP_PACKET ---- [+]\n\n" << endl;} if (udp_layer) {cout << "[+] ---- UDP_PACKET ---- [+]\n\n" << endl;} if (arp_layer) {cout << "[+] ---- ARP_PACKET ---- [+]\n\n" << endl;} if (icmp_layer) {cout << "[+] ---- ICMP_PACKET ---- [+]\n\n" << endl;} if(sll_layer){ /*ssl is like the link layer, just antoher opsion by libpcap*/ cout << "[+ --- INFO FROM SLL LAYER --- [+]\n\n"<<endl; cout <<"[#] Packet address: " << sll_layer->GetAddressType()<<endl; cout <<"[#] Packet type: "<<sll_layer->GetPackeType()<<endl; cout <<"[#] Packet protocol: " << sll_layer->GetProtocol()<<endl; } if (ip_layer){ /*Summarize some data for it layer*/ cout << "[+] --- INFO FROM IP LAYER --- [+] \n\n"<< endl; cout << "[#] IP Packet ID:" <<ip_layer->GetID()<<endl; cout << "[#] IP Packet name:" <<ip_layer->GetName()<<endl; cout << "[#] IP Packet Source IP:" <<ip_layer->GetSourceIP()<<endl; cout << "[#] IP Packet Destination IP:" <<ip_layer->GetDestinationIP()<<endl; cout << "[#] IP Packet Identification:" <<ip_layer->GetIdentification()<<endl; cout << "[#] IP Packet Protocol:" <<ip_layer->GetProtocol()<<endl; cout << "[#] IP Packet TTL:" <<ip_layer->GetTTL()<<endl; cout << "[#] IP Packet Flags:" <<ip_layer->GetFlags()<<endl; } if (icmp_layer){ /*Summarize some data for icmp layer*/ cout << "[+] --- INFO FROM ICMP LAYER --- [+] \n\n"<< endl; cout << "[#] ICMP Packet ID:" <<icmp_layer->GetID()<<endl; cout << "[#] ICMP Packet Name:" <<icmp_layer->GetName()<<endl; cout << "[#] ICMP Packet Identifier:" << icmp_layer->GetIdentifier()<<endl; cout << "[#] ICMP Packet Gateway:" <<icmp_layer->GetGateway()<<endl; cout << "[#] ICMP Packet Type: " << icmp_layer->GetType()<<endl; cout << "[#] ICMP Packet SequenceNumber: " << icmp_layer-> GetSequenceNumber()<<endl; } if (arp_layer){ /*Summarize some data for arp layer*/ cout << "[+] --- INFO FROM ARP LAYER --- [+] \n\n"<< endl; cout << "[#] ARP Packet ID: " <<arp_layer->GetID() << endl; cout << "[#] ARP Packet Name: " <<arp_layer->GetName() << endl; cout << "[#] ARP Packet Operation: " <<arp_layer->GetOperation() << endl; cout << "[#] ARP Packet Sender IP: " <<arp_layer->GetSenderIP() << endl; cout << "[#] ARP Packet Target IP: " <<arp_layer->GetTargetIP() << endl; cout << "[#] ARP Packet Target MAC: " <<arp_layer->GetTargetMAC() << endl; cout << "[#] ARP Packet Sender MAC: " <<arp_layer->GetSenderMAC() << endl; cout << "[#] ARP Packet Protocol: " <<arp_layer->GetProtocolType() << endl; cout<<"\n"<<endl; } if (ether_layer){ /*Summarize some data for ethernet layer*/ cout << "[+] --- INFO FROM Ethernet LAYER --- [+] \n\n"<< endl; cout << "[#] Ethernet Packet ID: " << ether_layer->GetID() << endl; cout << "[#] Ethernet Packet Name: " << ether_layer->GetName() << endl; cout << "[#] Ethernet Packet Type " << ether_layer->GetType() << endl; cout << "[#] Ethernet Packet Source MAC: " << ether_layer->GetSourceMAC() << endl; cout << "[#] Ethernet Packet Destination MAC: " << ether_layer->GetDestinationMAC() << endl; cout << "[#] Ethernet Packet First field: " << ether_layer->GetField(0) << endl; cout <<"\n"<<endl; } if (tcp_layer){ /* Summarize some data for tcp layer */ cout << "[+] --- INFO FROM TCP LAYER --- [+] \n\n"<< endl; cout << "[#] TCP Packet ID: " << tcp_layer->GetID() << endl; cout << "[#] TCP Packet Name: " << tcp_layer->GetName() << endl; cout << "[#] TCP Packet Source Port: " << tcp_layer->GetSrcPort() << endl; cout << "[#] TCP Packet Destination Port: " << tcp_layer->GetDstPort() << endl; cout << "[#] TCP Packet Seq Number: " << tcp_layer->GetSeqNumber() << endl; cout << "[#] TCP Packet Ack Number: " << tcp_layer->GetAckNumber() << endl; cout << "[#] TCP Packet Fin flag:" << tcp_layer->GetFIN()<<endl; //string payload = tcp_layer->GetStringPayload(); //cout << payload << endl; } if (udp_layer) { cout << "[+] --- INFO FROM UDP LAYER --- [+] \n\n"<< endl; cout << "[#] UDP Packet ID: " << udp_layer->GetID()<<endl; cout << "[#] UDP Packet Name: " << udp_layer->GetName()<<endl; cout << "[#] UDP Packet Source Port: " << udp_layer-> GetSrcPort()<<endl; cout << "[#] UDP Packet Destination: " << udp_layer-> GetDstPort()<<endl; cout << "[#] UDP Packet Header Size:" << udp_layer->GetHeaderSize()<< endl; } if(raw_payload) { /* Summarize some data for rawpayload */ cout << "[+] --- INFO FROM RAW_PAYLOAD --- [+] \n\n"<< endl; cout << "[#] RAW Packet ID: " << raw_payload->GetID() << endl; cout << "[#] RAW Packet Name: " << raw_payload->GetName() << endl; cout << "[#] RAW Packet PayloadSize: " << raw_payload->GetPayloadSize() << endl; string payload = raw_payload->GetStringPayload(); cout << payload << endl; cout<<"xxxx\n"; } Http_check(sniff_packet); cout << "[==========================================================================]\n\n"; disconnect(sniff_packet); } /* Function for handling a packet */ int main() { /* Set the interface */ Sniffer sniff_tcp("src 192.168.1.214 or dst 192.168.1.214", iface, PacketHandler); sniff_tcp.Capture(-1); return 0; }
c6c0b2b7761b635f9c3e1e014fe22e38c421d8c8
7b1bec06083bbc6cc79f311f9cab44479995d8df
/App2.3/App2.3/App2.3.cpp
6649943e4f122014945b5965ea6a331e5b3456bb
[]
no_license
abhi1561/CTCI
f3fc46674dd8ddcc45a97b06f9b0ccb3e23c7750
979feb4df4d87c5889c2de882a900642d7c16edf
refs/heads/master
2020-05-03T16:15:38.780712
2019-05-08T03:06:43
2019-05-08T03:06:59
178,719,234
0
0
null
null
null
null
UTF-8
C++
false
false
851
cpp
App2.3.cpp
// App2.3.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "malloc.h" struct ll { int data; ll *next; }; ll* head; void DeleteMiddleNode(ll* llhead) { if ((llhead == NULL) || (llhead->next == NULL) ||(llhead->next->next == NULL)) return; ll* onehop = llhead; ll* dbhop = llhead->next->next; while (dbhop != NULL) { if (dbhop->next != NULL) { dbhop = dbhop->next->next; onehop = onehop->next; } else break; } onehop->next = onehop->next->next; } int main() { ll *tmp; int len = 20; for (int i = 0; i < len; i++) { if (i == 0) { tmp = (ll*)malloc(sizeof(struct ll)); tmp->data = i; head = tmp; } else { tmp->next = (ll*)malloc(sizeof(struct ll)); tmp = tmp->next; tmp->data = i; } } tmp->next = NULL; DeleteMiddleNode(head); return 0; }
79ebf2a5be02dd1b79c10cf65ac5d31df78ab31c
8e039772af95cba7b797011d15094d22a1c99057
/src/firmware-tests/Platform/Timer0/PollAfterTimer0Mock.inc
37d1dc2950cc5aec8a3b3fb5ac33e4f880956ef2
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
pete-restall/Cluck2Sesame-Prototype
44823861721bc9e8fb23ce4f71f376c49f53a64c
99119b6748847a7b6aeadc4bee42cbed726f7fdc
refs/heads/master
2021-09-13T11:42:31.684365
2018-04-29T07:40:19
2018-04-29T07:40:19
61,883,020
1
0
null
null
null
null
UTF-8
C++
false
false
218
inc
PollAfterTimer0Mock.inc
#ifndef __CLUCK2SESAME_TESTS_PLATFORM_TIMER0_POLLAFTERTIMER0MOCK_INC #define __CLUCK2SESAME_TESTS_PLATFORM_TIMER0_POLLAFTERTIMER0MOCK_INC extern initialisePollAfterTimer0Mock extern calledPollAfterTimer0 #endif
0331d7ac14b4ce8367bbdb1b00c37df72440e8f1
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/pdf/draw_utils/coordinates_unittest.cc
07dee79f501ee2758c15aa15177540b3d2206d38
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
11,789
cc
coordinates_unittest.cc
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "pdf/draw_utils/coordinates.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" namespace chrome_pdf { namespace draw_utils { namespace { constexpr int kBottomSeparator = 4; constexpr int kHorizontalSeparator = 1; constexpr PageInsetSizes kLeftInsets{5, 3, 1, 7}; constexpr PageInsetSizes kRightInsets{1, 3, 5, 7}; constexpr PageInsetSizes kSingleViewInsets{5, 3, 5, 7}; void CompareInsetSizes(const PageInsetSizes& expected_insets, const PageInsetSizes& given_insets) { EXPECT_EQ(expected_insets.left, given_insets.left); EXPECT_EQ(expected_insets.top, given_insets.top); EXPECT_EQ(expected_insets.right, given_insets.right); EXPECT_EQ(expected_insets.bottom, given_insets.bottom); } } // namespace TEST(CoordinateTest, AdjustBottomGapForRightSidePage) { gfx::Rect bottom_gap(0, 10, 500, 100); AdjustBottomGapForRightSidePage(250, &bottom_gap); EXPECT_EQ(gfx::Rect(250, 10, 250, 100), bottom_gap); bottom_gap.SetRect(15, 20, 700, 100); AdjustBottomGapForRightSidePage(365, &bottom_gap); EXPECT_EQ(gfx::Rect(365, 20, 350, 100), bottom_gap); bottom_gap.SetRect(100, 40, 951, 200); AdjustBottomGapForRightSidePage(450, &bottom_gap); EXPECT_EQ(gfx::Rect(450, 40, 475, 200), bottom_gap); } TEST(CoordinateTest, CenterRectHorizontally) { gfx::Rect page_rect(10, 20, 400, 300); CenterRectHorizontally(600, &page_rect); EXPECT_EQ(gfx::Rect(100, 20, 400, 300), page_rect); page_rect.SetRect(300, 450, 500, 700); CenterRectHorizontally(800, &page_rect); EXPECT_EQ(gfx::Rect(150, 450, 500, 700), page_rect); page_rect.SetRect(800, 100, 200, 250); CenterRectHorizontally(350, &page_rect); EXPECT_EQ(gfx::Rect(75, 100, 200, 250), page_rect); } TEST(CoordinateTest, ExpandDocumentSize) { gfx::Size doc_size(100, 400); // Test various expansion sizes. gfx::Size rect_size(100, 200); ExpandDocumentSize(rect_size, &doc_size); EXPECT_EQ(gfx::Size(100, 600), doc_size); rect_size.SetSize(200, 150); ExpandDocumentSize(rect_size, &doc_size); EXPECT_EQ(gfx::Size(200, 750), doc_size); rect_size.SetSize(100, 300); ExpandDocumentSize(rect_size, &doc_size); EXPECT_EQ(gfx::Size(200, 1050), doc_size); rect_size.SetSize(250, 400); ExpandDocumentSize(rect_size, &doc_size); EXPECT_EQ(gfx::Size(250, 1450), doc_size); } TEST(CoordinateTest, GetBottomGapBetweenRects) { EXPECT_EQ(gfx::Rect(95, 600, 350, 50), GetBottomGapBetweenRects(600, {95, 200, 350, 450})); EXPECT_EQ(gfx::Rect(200, 500, 350, 10), GetBottomGapBetweenRects(500, {200, 0, 350, 510})); // Test rectangle with a negative bottom value. EXPECT_EQ(gfx::Rect(150, -100, 400, 150), GetBottomGapBetweenRects(-100, {150, 0, 400, 50})); // Test case where `page_rect_bottom` >= `dirty_rect.bottom()`. EXPECT_EQ(gfx::Rect(0, 0, 0, 0), GetBottomGapBetweenRects(1400, {0, 10, 300, 500})); } TEST(CoordinateTest, GetMostVisiblePage) { // Test a single-view layout. std::vector<IndexedPage> visible_pages = { {0, {0, 0, 50, 100}}, {1, {0, 100, 100, 100}}, {2, {0, 200, 100, 200}}}; EXPECT_EQ(0, GetMostVisiblePage(visible_pages, {0, 0, 100, 100})); EXPECT_EQ(1, GetMostVisiblePage(visible_pages, {0, 100, 100, 100})); EXPECT_EQ(0, GetMostVisiblePage(visible_pages, {0, 50, 100, 100})); EXPECT_EQ(1, GetMostVisiblePage(visible_pages, {0, 51, 100, 100})); EXPECT_EQ(2, GetMostVisiblePage(visible_pages, {0, 180, 100, 100})); EXPECT_EQ(1, GetMostVisiblePage(visible_pages, {0, 160, 100, 100})); EXPECT_EQ(0, GetMostVisiblePage(visible_pages, {0, 77, 50, 50})); EXPECT_EQ(1, GetMostVisiblePage(visible_pages, {0, 85, 50, 50})); EXPECT_EQ(0, GetMostVisiblePage(visible_pages, {0, 0, 400, 400})); // Test a two-up view layout. visible_pages = {{0, {100, 0, 300, 400}}, {1, {400, 0, 400, 300}}, {2, {0, 400, 400, 250}}, {3, {400, 400, 200, 400}}, {4, {50, 800, 350, 200}}}; EXPECT_EQ(0, GetMostVisiblePage(visible_pages, {0, 0, 400, 500})); EXPECT_EQ(2, GetMostVisiblePage(visible_pages, {0, 200, 400, 500})); EXPECT_EQ(3, GetMostVisiblePage(visible_pages, {400, 200, 400, 500})); EXPECT_EQ(3, GetMostVisiblePage(visible_pages, {200, 200, 400, 500})); EXPECT_EQ(0, GetMostVisiblePage(visible_pages, {0, 0, 1600, 2000})); // Test case where no pages intersect with the viewport. EXPECT_EQ(0, GetMostVisiblePage(visible_pages, {1000, 2000, 150, 200})); // Test empty vector. std::vector<IndexedPage> empty_pages; EXPECT_EQ(-1, GetMostVisiblePage(empty_pages, {100, 200, 300, 400})); } TEST(CoordinateTest, GetPageInsetsForTwoUpView) { // Page is on the left side and isn't the last page in the document. CompareInsetSizes(kLeftInsets, GetPageInsetsForTwoUpView(0, 10, kSingleViewInsets, kHorizontalSeparator)); // Page is on the left side and is the last page in the document. CompareInsetSizes(kSingleViewInsets, GetPageInsetsForTwoUpView(10, 11, kSingleViewInsets, kHorizontalSeparator)); // Only one page in the document. CompareInsetSizes( kSingleViewInsets, GetPageInsetsForTwoUpView(0, 1, kSingleViewInsets, kHorizontalSeparator)); // Page is on the right side of the document. CompareInsetSizes( kRightInsets, GetPageInsetsForTwoUpView(1, 4, kSingleViewInsets, kHorizontalSeparator)); } TEST(CoordinateTest, GetRectForSingleView) { // Test portrait pages. EXPECT_EQ(gfx::Rect(50, 500, 200, 400), GetRectForSingleView({200, 400}, {300, 500})); EXPECT_EQ(gfx::Rect(50, 600, 100, 340), GetRectForSingleView({100, 340}, {200, 600})); // Test landscape pages. EXPECT_EQ(gfx::Rect(0, 1000, 500, 450), GetRectForSingleView({500, 450}, {500, 1000})); EXPECT_EQ(gfx::Rect(25, 1500, 650, 200), GetRectForSingleView({650, 200}, {700, 1500})); } TEST(CoordinateTest, GetScreenRect) { const gfx::Rect rect(10, 20, 200, 300); // Test various zooms with the position at the origin. EXPECT_EQ(gfx::Rect(10, 20, 200, 300), GetScreenRect(rect, {0, 0}, 1)); EXPECT_EQ(gfx::Rect(15, 30, 300, 450), GetScreenRect(rect, {0, 0}, 1.5)); EXPECT_EQ(gfx::Rect(5, 10, 100, 150), GetScreenRect(rect, {0, 0}, 0.5)); // Test various zooms with the position elsewhere. EXPECT_EQ(gfx::Rect(-390, -10, 200, 300), GetScreenRect(rect, {400, 30}, 1)); EXPECT_EQ(gfx::Rect(-385, 0, 300, 450), GetScreenRect(rect, {400, 30}, 1.5)); EXPECT_EQ(gfx::Rect(-395, -20, 100, 150), GetScreenRect(rect, {400, 30}, 0.5)); // Test various zooms with a negative position. EXPECT_EQ(gfx::Rect(-90, 70, 200, 300), GetScreenRect(rect, {100, -50}, 1)); EXPECT_EQ(gfx::Rect(-85, 80, 300, 450), GetScreenRect(rect, {100, -50}, 1.5)); EXPECT_EQ(gfx::Rect(-95, 60, 100, 150), GetScreenRect(rect, {100, -50}, 0.5)); // Test an empty rect always outputs an empty rect. const gfx::Rect empty_rect; EXPECT_EQ(gfx::Rect(-20, -500, 0, 0), GetScreenRect(empty_rect, {20, 500}, 1)); EXPECT_EQ(gfx::Rect(-20, -500, 0, 0), GetScreenRect(empty_rect, {20, 500}, 1.5)); EXPECT_EQ(gfx::Rect(-20, -500, 0, 0), GetScreenRect(empty_rect, {20, 500}, 0.5)); } TEST(CoordinateTest, GetSurroundingRect) { constexpr int kDocWidth = 1000; // Test various position, sizes, and document width. EXPECT_EQ(gfx::Rect(0, 97, 1000, 314), GetSurroundingRect(100, 300, kSingleViewInsets, kDocWidth, kBottomSeparator)); EXPECT_EQ(gfx::Rect(0, 37, 1000, 214), GetSurroundingRect(40, 200, kSingleViewInsets, kDocWidth, kBottomSeparator)); EXPECT_EQ(gfx::Rect(0, 197, 1000, 514), GetSurroundingRect(200, 500, kSingleViewInsets, kDocWidth, kBottomSeparator)); EXPECT_EQ( gfx::Rect(0, -103, 200, 314), GetSurroundingRect(-100, 300, kSingleViewInsets, 200, kBottomSeparator)); } TEST(CoordinateTest, GetLeftFillRect) { // Testing various rectangles with different positions and sizes. gfx::Rect page_rect(10, 20, 400, 500); EXPECT_EQ(gfx::Rect(0, 17, 5, 514), GetLeftFillRect(page_rect, kSingleViewInsets, kBottomSeparator)); page_rect.SetRect(200, 300, 400, 350); EXPECT_EQ(gfx::Rect(0, 297, 195, 364), GetLeftFillRect(page_rect, kSingleViewInsets, kBottomSeparator)); page_rect.SetRect(800, 650, 20, 15); EXPECT_EQ(gfx::Rect(0, 647, 795, 29), GetLeftFillRect(page_rect, kSingleViewInsets, kBottomSeparator)); // Testing rectangle with a negative y-component. page_rect.SetRect(50, -200, 100, 300); EXPECT_EQ(gfx::Rect(0, -203, 45, 314), GetLeftFillRect(page_rect, kSingleViewInsets, kBottomSeparator)); } TEST(CoordinateTest, GetRightFillRect) { constexpr int kDocWidth = 1000; // Testing various rectangles with different positions, sizes, and document // widths. gfx::Rect page_rect(10, 20, 400, 500); EXPECT_EQ(gfx::Rect(415, 17, 585, 514), GetRightFillRect(page_rect, kSingleViewInsets, kDocWidth, kBottomSeparator)); page_rect.SetRect(200, 300, 400, 350); EXPECT_EQ(gfx::Rect(605, 297, 395, 364), GetRightFillRect(page_rect, kSingleViewInsets, kDocWidth, kBottomSeparator)); page_rect.SetRect(200, 300, 400, 350); EXPECT_EQ( gfx::Rect(605, 297, 195, 364), GetRightFillRect(page_rect, kSingleViewInsets, 800, kBottomSeparator)); // Testing rectangle with a negative y-component. page_rect.SetRect(50, -200, 100, 300); EXPECT_EQ(gfx::Rect(155, -203, 845, 314), GetRightFillRect(page_rect, kSingleViewInsets, kDocWidth, kBottomSeparator)); } TEST(CoordinateTest, GetBottomFillRect) { // Testing various rectangles with different positions and sizes. gfx::Rect page_rect(10, 20, 400, 500); EXPECT_EQ(gfx::Rect(5, 527, 410, 4), GetBottomFillRect(page_rect, kSingleViewInsets, kBottomSeparator)); page_rect.SetRect(200, 300, 400, 350); EXPECT_EQ(gfx::Rect(195, 657, 410, 4), GetBottomFillRect(page_rect, kSingleViewInsets, kBottomSeparator)); page_rect.SetRect(800, 650, 20, 15); EXPECT_EQ(gfx::Rect(795, 672, 30, 4), GetBottomFillRect(page_rect, kSingleViewInsets, kBottomSeparator)); // Testing rectangle with a negative y-component. page_rect.SetRect(50, -200, 100, 300); EXPECT_EQ(gfx::Rect(45, 107, 110, 4), GetBottomFillRect(page_rect, kSingleViewInsets, kBottomSeparator)); } TEST(CoordinateTest, GetLeftRectForTwoUpView) { EXPECT_EQ(gfx::Rect(100, 100, 200, 400), GetLeftRectForTwoUpView({200, 400}, {300, 100})); EXPECT_EQ(gfx::Rect(0, 0, 300, 400), GetLeftRectForTwoUpView({300, 400}, {300, 0})); // Test empty rect gets positioned. EXPECT_EQ(gfx::Rect(100, 0, 0, 0), GetLeftRectForTwoUpView({0, 0}, {100, 0})); } TEST(CoordinateTest, GetRightRectForTwoUpView) { EXPECT_EQ(gfx::Rect(300, 100, 200, 400), GetRightRectForTwoUpView({200, 400}, {300, 100})); EXPECT_EQ(gfx::Rect(300, 0, 300, 400), GetRightRectForTwoUpView({300, 400}, {300, 0})); // Test empty rect gets positioned. EXPECT_EQ(gfx::Rect(100, 0, 0, 0), GetRightRectForTwoUpView({0, 0}, {100, 0})); } } // namespace draw_utils } // namespace chrome_pdf
434c4c6d5b689705dd68a6a98be7ba3800599d90
18130a67a65b1d6620c6b6e21b545362f523475a
/2021_3/day25-Pacific Atlantic Water Flow/C++/Pacific Atlantic Water Flow.cpp
d3e657e689e41dbbe17a4416725e4e6a1289f727
[]
no_license
Mealf/LeetCode
00bb32366cbf6d2b8a4094b7a2eb7db597fd6723
0f2b22134c2e06add4ac6b33c655651dbea62f0e
refs/heads/master
2023-04-01T05:13:52.066693
2021-03-31T09:57:51
2021-03-31T09:57:51
344,504,226
0
0
null
null
null
null
UTF-8
C++
false
false
2,047
cpp
Pacific Atlantic Water Flow.cpp
class Solution { public: vector<vector<int>> pacificAtlantic(vector<vector<int>>& matrix) { if(matrix.size()==0) return {}; //Pacific fill 1; Atlantic fill 2; Both fill 3(binary 11) vector<vector<int>> v(matrix.size(),vector<int>(matrix[0].size())); vector<vector<int>> result; /*fill edge*/ for(int i=0;i<v.size();i++){ v[i][0]|=1; v[i][v[0].size()-1]|=2; } for(int i=0;i<v[0].size();i++){ v[0][i]|=1; v[v.size()-1][i]|=2; } /*flood*/ for(int i=0;i<v.size();i++){ flood(i,0,v,matrix); flood(i,v[0].size()-1,v,matrix); } for(int i=0;i<v[0].size();i++){ flood(0,i,v,matrix); flood(v.size()-1,i,v,matrix); } for(int i=0;i<v.size();i++){ for(int j=0;j<v[0].size();j++){ if(v[i][j]==3) result.push_back({i,j}); } } return result; } /*從低地勢往高地勢找,當可以更新且有需要更新時再去更新,同時flood*/ void flood(int row, int col, vector<vector<int>> &v, vector<vector<int>> &m){ int value=m[row][col], w=v[row][col]; //a&b!=b 等同於 a&(b!=b) //往上找 if(row+1<m.size() && m[row+1][col]>=value && (v[row+1][col]&w)!=w){ v[row+1][col] |= v[row][col]; flood(row+1,col,v,m); } //往右找 if(col+1<m[0].size() && m[row][col+1]>=value && (v[row][col+1]&w)!=w){ v[row][col+1] |= w; flood(row,col+1,v,m); } //往下找 if(row!=0 && m[row-1][col]>=value && (v[row-1][col]&w)!=w){ v[row-1][col]|=w; flood(row-1,col,v,m); } //往左找 if(col!=0 && m[row][col-1]>=value && (v[row][col-1]&w)!=w){ v[row][col-1]|=w; flood(row,col-1,v,m); } } };
d610ba8b8face5bd4f41a9582eaa78bf1ecc061a
f250b150ec352905427e26cc8800b38676dead1e
/Extend/Ui.Plugins/CPP/Basic/AgUiPluginCppAddInEmbeddedWindow.cpp
b4b78ccb0d0b699535cdbcff65efff3ab17c7c55
[]
no_license
VB6Hobbyst7/SampleExamples
14874a50aeed2a19810d9bc11c6b488b3cb7c981
d826df6341c0999849d06a95ea7f266691dbf89b
refs/heads/master
2022-01-05T13:39:27.774406
2019-03-04T17:46:17
2019-03-04T17:46:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,080
cpp
AgUiPluginCppAddInEmbeddedWindow.cpp
// // This is a part of the STK Developer Kit. // Copyright (c) Analytical Graphics, Inc. All rights reserved. // // CAgUiPluginCppAddInEmbeddedWindow.cpp : implementation file // #include "AgUiPluginCppAddInStd.h" #include "AgUiPluginTutorial.h" #include "AgUiPluginCppAddInEmbeddedWindow.h" #include "AgUiPluginCppAddInCmds.h" #include "AgUiPluginUtils.h" extern BOOL LoadIconFromResource(LPCTSTR lpIconName, IPictureDisp** ppRetVal); // CAgUiPluginCppAddInEmbeddedWindow dialog IMPLEMENT_DYNAMIC(CAgUiPluginCppAddInEmbeddedWindow, CDialog) BEGIN_MESSAGE_MAP(CAgUiPluginCppAddInEmbeddedWindow, CDialog) ON_WM_SIZE() ON_COMMAND(ID_POPUPMENU_CLEAREVENTLOG, OnPopupmenuClearEventLog) ON_NOTIFY(NM_RCLICK, IDC_OBJECTMODEL_EVENT_VIEWER, OnNMRclickObjectmodelEventViewer) END_MESSAGE_MAP() BEGIN_INTERFACE_MAP(CAgUiPluginCppAddInEmbeddedWindow, CCmdTarget) INTERFACE_PART(CAgUiPluginCppAddInEmbeddedWindow, __uuidof(IAgUiPluginEmbeddedWindowHandle), EmbeddedPlugin) INTERFACE_PART(CAgUiPluginCppAddInEmbeddedWindow, __uuidof(IEventLogger), EventLogger) INTERFACE_PART(CAgUiPluginCppAddInEmbeddedWindow, __uuidof(IAgUiPluginEmbeddedControl), ExtUIObject) END_INTERFACE_MAP() CAgUiPluginCppAddInEmbeddedWindow::CAgUiPluginCppAddInEmbeddedWindow() : CDialog(CAgUiPluginCppAddInEmbeddedWindow::IDD), m_dwCookie(0), m_pSink(0) { } void CAgUiPluginCppAddInEmbeddedWindow::OnPopupmenuClearEventLog() { m_eventLV.DeleteAllItems(); } void CAgUiPluginCppAddInEmbeddedWindow::OnNMRclickObjectmodelEventViewer(NMHDR *pNMHDR, LRESULT *pResult) { NMITEMACTIVATE *pHdr = (NMITEMACTIVATE*)pNMHDR; CMenu popupMenu; popupMenu.LoadMenu(IDR_TREEVIEW_POPUPMENU); CPoint pt; pt.x = pHdr->ptAction.x; pt.y = pHdr->ptAction.y; ClientToScreen(&pt); popupMenu.GetSubMenu(0)->TrackPopupMenu(TPM_LEFTALIGN|TPM_LEFTBUTTON, pt.x, pt.y, this, 0); *pResult = 1; } CAgUiPluginCppAddInEmbeddedWindow::~CAgUiPluginCppAddInEmbeddedWindow() { //------------------------------------------- // Disconnect from the STK Object Model events //------------------------------------------- UnadviseAutomationEvents(); delete m_pSink; } void CAgUiPluginCppAddInEmbeddedWindow::PostNcDestroy() { // Destroy the instance when the reference count has reached zero. if (m_dwRef <= 0) delete this; } HRESULT CAgUiPluginCppAddInEmbeddedWindow::GetSTKObjectRoot(IDispatch** ppRetVal) { USES_CONVERSION; CComPtr<IAgUiApplication> pDisp; //------------------------------------------- // get_Application returns a pointer to the // AGI Application Object Model. //------------------------------------------- HRESULT hr = E_FAIL; if (m_pSite && SUCCEEDED(hr = m_pSite->get_Application(&pDisp))) { if (FAILED(hr = AgGetStkObjectRoot(CComQIPtr<IDispatch>(pDisp), ppRetVal))) { CString strMsg; strMsg = "Cannot retrieve a root object of the STK Object Model."; m_pSite->LogMessage(eUiPluginLogMsgDebug, CComBSTR((LPCTSTR)strMsg)); } } return hr; } BOOL CAgUiPluginCppAddInEmbeddedWindow::OnInitDialog() { if (!__super::OnInitDialog()) return FALSE; m_eventLV.SetExtendedStyle(m_eventLV.GetExtendedStyle()|LVS_EX_FULLROWSELECT); m_eventLV.InsertColumn(0, _T("Time"), LVCFMT_LEFT, 120); m_eventLV.InsertColumn(1, _T("Event Name"), LVCFMT_LEFT, 200, 1); m_eventLV.InsertColumn(2, _T("Description"), LVCFMT_LEFT, 300, 2); //------------------------------------------- // Connect to the STK Object Model events //------------------------------------------- CComQIPtr<IEventLogger> pEventLogger (GetInterface(&__uuidof(IEventLogger))); m_pSink = new CObjectModelEventSink(pEventLogger); AdviseAutomationEvents(); //------------------------------------------- // Didnt find the object model so lets // disable the tree control. //------------------------------------------- if (!m_pRootDisp) { m_eventLV.EnableWindow(FALSE); } return TRUE; } void CAgUiPluginCppAddInEmbeddedWindow::UnadviseAutomationEvents() { LPUNKNOWN pUnkSink = m_pSink->GetIDispatch(FALSE); if (m_pRootDisp) { // Terminate a connection between source and sink. // m_dwCookied is a value obtained through AfxConnectionAdvise. AfxConnectionUnadvise(m_pRootDisp, __uuidof(IAgStkObjectRootEvents), pUnkSink, FALSE, m_dwCookie); // Release the object model's root object. m_pRootDisp.Release(); } } void CAgUiPluginCppAddInEmbeddedWindow::AdviseAutomationEvents() { if (SUCCEEDED(GetSTKObjectRoot(&m_pRootDisp))) { CComQIPtr<IAgStkObjectRoot> pRoot (m_pRootDisp); if (pRoot) { // Get a pointer to the sink's IUnknown without AddRef'ing it. CObjectModelEventSink // implements only dispinterface, so the IUnknown and IDispatch pointers will be the same. LPUNKNOWN pUnkSink = m_pSink->GetIDispatch(FALSE); // Establish a connection between source and sink. // m_dwCookie is a cookie identifying the connection, and is needed // to terminate the connection. AfxConnectionAdvise(m_pRootDisp, __uuidof(IAgStkObjectRootEvents), pUnkSink, FALSE, &m_dwCookie); } else { CString strMsg; strMsg = "Cannot get the STK Object Model root object."; m_pSite->LogMessage(eUiPluginLogMsgDebug, CComBSTR((LPCTSTR)strMsg)); } } } BOOL CAgUiPluginCppAddInEmbeddedWindow::Create(IAgUiPluginSite* pSite) { m_pSite.Release(); m_pSite = pSite; // Create a modeless dialog using a given resource ID return CDialog::Create(CAgUiPluginCppAddInEmbeddedWindow::IDD); } void CAgUiPluginCppAddInEmbeddedWindow::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_OBJECTMODEL_EVENT_VIEWER, m_eventLV); } void CAgUiPluginCppAddInEmbeddedWindow::OnSize(UINT nType, int cx, int cy) { __super::OnSize(nType, cx, cy); CWnd* pWnd = GetDlgItem(IDC_OBJECTMODEL_EVENT_VIEWER); if (pWnd != NULL) { pWnd->MoveWindow(0, 0, cx, cy); } } // CAgUiPluginCppAddInEmbeddedWindow message handlers STDMETHODIMP CAgUiPluginCppAddInEmbeddedWindow::XEmbeddedPlugin::get_HWND(OLE_HANDLE* pRetVal) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); METHOD_PROLOGUE_EX_(CAgUiPluginCppAddInEmbeddedWindow, EmbeddedPlugin) if (pRetVal == NULL) return E_POINTER; // Unsafe type cast! *pRetVal = (OLE_HANDLE)(INT_PTR)pThis->GetSafeHwnd(); return S_OK; } STDMETHODIMP CAgUiPluginCppAddInEmbeddedWindow::XEmbeddedPlugin::Apply(void) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); METHOD_PROLOGUE_EX_(CAgUiPluginCppAddInEmbeddedWindow, EmbeddedPlugin) return S_OK; } STDMETHODIMP_(ULONG) CAgUiPluginCppAddInEmbeddedWindow::XEmbeddedPlugin::AddRef() { AFX_MANAGE_STATE(AfxGetStaticModuleState()); METHOD_PROLOGUE_EX_(CAgUiPluginCppAddInEmbeddedWindow, EmbeddedPlugin) return pThis->ExternalAddRef(); } STDMETHODIMP_(ULONG) CAgUiPluginCppAddInEmbeddedWindow::XEmbeddedPlugin::Release() { AFX_MANAGE_STATE(AfxGetStaticModuleState()); METHOD_PROLOGUE_EX_(CAgUiPluginCppAddInEmbeddedWindow, EmbeddedPlugin) return pThis->ExternalRelease(); } STDMETHODIMP CAgUiPluginCppAddInEmbeddedWindow::XEmbeddedPlugin::QueryInterface( REFIID iid, LPVOID far* ppvObj) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); METHOD_PROLOGUE_EX_(CAgUiPluginCppAddInEmbeddedWindow, EmbeddedPlugin) return pThis->ExternalQueryInterface(&iid, ppvObj); } //////////////////////////////////////////////////////////////////////////////// // IEventLogger STDMETHODIMP CAgUiPluginCppAddInEmbeddedWindow::XEventLogger::LogEvent(const CString& rEvent, const CString& rString) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); METHOD_PROLOGUE_EX_(CAgUiPluginCppAddInEmbeddedWindow, EventLogger) TCHAR buf[100]; time_t t = time(0); struct tm* time = localtime(&t); _tcsftime(buf, sizeof(buf), _T("%#c"), time); // Check if the window handle has been destroyed but the object still is lingering around if (::IsWindow(pThis->GetSafeHwnd())) { int iPos = pThis->m_eventLV.InsertItem(pThis->m_eventLV.GetItemCount(), buf); pThis->m_eventLV.SetItem(iPos, 1, LVIF_TEXT, rEvent, 0, 0, 0, 0); pThis->m_eventLV.SetItem(iPos, 2, LVIF_TEXT, rString, 0, 0, 0, 0); pThis->m_eventLV.EnsureVisible(iPos, FALSE); } return S_OK; } STDMETHODIMP_(ULONG) CAgUiPluginCppAddInEmbeddedWindow::XEventLogger::AddRef() { AFX_MANAGE_STATE(AfxGetStaticModuleState()); METHOD_PROLOGUE_EX_(CAgUiPluginCppAddInEmbeddedWindow, EventLogger) return pThis->ExternalAddRef(); } STDMETHODIMP_(ULONG) CAgUiPluginCppAddInEmbeddedWindow::XEventLogger::Release() { AFX_MANAGE_STATE(AfxGetStaticModuleState()); METHOD_PROLOGUE_EX_(CAgUiPluginCppAddInEmbeddedWindow, EventLogger) return pThis->ExternalRelease(); } STDMETHODIMP CAgUiPluginCppAddInEmbeddedWindow::XEventLogger::QueryInterface( REFIID iid, LPVOID far* ppvObj) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); METHOD_PROLOGUE_EX_(CAgUiPluginCppAddInEmbeddedWindow, EventLogger) return pThis->ExternalQueryInterface(&iid, ppvObj); } STDMETHODIMP CAgUiPluginCppAddInEmbeddedWindow::XExtUIObject::SetSite(IAgUiPluginEmbeddedControlSite* pSite) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); METHOD_PROLOGUE_EX_(CAgUiPluginCppAddInEmbeddedWindow, ExtUIObject) pThis->m_pContainerSite.Release(); pThis->m_pContainerSite = pSite; if (pThis->m_pContainerSite) { pThis->m_pContainerSite->SetModifiedFlag(VARIANT_TRUE); } return S_OK; } STDMETHODIMP CAgUiPluginCppAddInEmbeddedWindow::XExtUIObject::OnClosing() { AFX_MANAGE_STATE(AfxGetStaticModuleState()); return S_OK; } STDMETHODIMP CAgUiPluginCppAddInEmbeddedWindow::XExtUIObject::OnSaveModified() { AFX_MANAGE_STATE(AfxGetStaticModuleState()); METHOD_PROLOGUE_EX_(CAgUiPluginCppAddInEmbeddedWindow, ExtUIObject) return S_OK; } STDMETHODIMP CAgUiPluginCppAddInEmbeddedWindow::XExtUIObject::GetIcon(/*[out,retval]*/IPictureDisp** ppRetVal) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); if(ppRetVal) { // Uncomment to associate a custom icon with the window //return LoadIconFromResource(MAKEINTRESOURCE(IDI_HOURGLASS_ICON), ppRetVal); *ppRetVal = NULL; return S_OK; } return S_OK; } STDMETHODIMP_(ULONG) CAgUiPluginCppAddInEmbeddedWindow::XExtUIObject::AddRef() { AFX_MANAGE_STATE(AfxGetStaticModuleState()); METHOD_PROLOGUE_EX_(CAgUiPluginCppAddInEmbeddedWindow, ExtUIObject) return pThis->ExternalAddRef(); } STDMETHODIMP_(ULONG) CAgUiPluginCppAddInEmbeddedWindow::XExtUIObject::Release() { AFX_MANAGE_STATE(AfxGetStaticModuleState()); METHOD_PROLOGUE_EX_(CAgUiPluginCppAddInEmbeddedWindow, ExtUIObject) return pThis->ExternalRelease(); } STDMETHODIMP CAgUiPluginCppAddInEmbeddedWindow::XExtUIObject::QueryInterface( REFIID iid, LPVOID far* ppvObj) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); METHOD_PROLOGUE_EX_(CAgUiPluginCppAddInEmbeddedWindow, ExtUIObject) return pThis->ExternalQueryInterface(&iid, ppvObj); }
0be1d293a05fcaa1c8802f20c8877faaee3680b0
ad37ef79b60413aabfb36300a7f4f104f1198824
/79.cpp
3b64ac95b1c5f3723b6d0b4612f0a1029e0ab73b
[]
no_license
luyongkang/leetcode
13fe45cbd153e5b64c463d445b1b5e4ddff87129
c7eca5d9cc0b23dad9aa803939fbef03f4712641
refs/heads/main
2023-07-22T15:00:49.890576
2021-09-14T10:56:02
2021-09-14T10:56:02
389,047,844
0
0
null
null
null
null
UTF-8
C++
false
false
504
cpp
79.cpp
#include <iostream> #include <vector> #include <stack> using namespace std; void checkAround(int x, int y, vector<vector<char>> &board, stack<int> &temp, char c) { int m = board.size() - 1; int n = board.at(0).size() - 1; } bool exist(vector<vector<char>> &board, string word) { int m = board.size() - 1; int n = board.at(0).size() - 1; stack<int> temp; for (; m != -1; m--) { for (; n != -1; n--) { if (board[m][n] == word.at(0)) { checkAround(m, n, board, temp, ); } } } }
147840b8db7d7d2b50e574e46d9a18cf833669b5
c4e2ce6e7024e50134fa7367e9e71a65b8dd4c35
/mainwindow.h
69ae1f5683d19b5958fe17727d2542c342a463ff
[]
no_license
raoleynik/unix-course-assign
26c0e548c9f1fce5133d9c93800c8181ad4e4b6e
502d33334eb83ac7a47e5f02c7e0c7a8a2d262ae
refs/heads/master
2021-03-14T18:03:12.263370
2020-05-25T21:49:52
2020-05-25T21:49:52
246,782,017
0
0
null
null
null
null
UTF-8
C++
false
false
774
h
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include "conv_length.h" #include "conv_mass.h" #include "conv_temp.h" #include "conv_time.h" QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: void on_PushButton_exit_clicked(); void on_PushButton_Conv_Length_Open_clicked(); void on_PushButton_Conv_Temp_Open_clicked(); void on_PushButton_Conv_Mass_Open_clicked(); void on_PushButton_Conv_Time_Open_clicked(); private: Ui::MainWindow *ui; Conv_Length *lwindow; conv_mass *mwindow; conv_temp *twindow; conv_time *t2window; }; #endif // MAINWINDOW_H
11fd4afee4f5d7317a2975f1c564c6244eaa331e
17ee2b4e876ca2f9b3cbabc63b0d5ee6522fb5e3
/resol.h
18ef1568bd1bd344f398d6ba1234af8f1f12488d
[]
no_license
sasq64/revoke
4de10524d105997b573ce9d06608d9f9df862c96
dee5f6f69d382fe0156fc452237f772b818d536a
refs/heads/master
2020-04-01T05:21:10.263004
2019-01-12T21:32:36
2019-01-12T21:32:36
152,899,770
0
0
null
null
null
null
UTF-8
C++
false
false
5,190
h
resol.h
#pragma once #include "revoke.h" #include "sol2/sol.hpp" #include <map> #include <string> struct CSLua { struct CSStaticCall { sol::variadic_results operator()(const sol::variadic_args va) { printf("Called with %lu args\n", va.size()); sol::variadic_results r; return r; } }; struct CSConstruct { cs::csptr classObj; struct Member { Member(std::string const& name, cs::csptr mi, int typ) : name(name), memberInfo(mi), type(typ) {} std::string name; cs::csptr memberInfo; int type; }; std::map<std::string, Member> memberMap; CSConstruct(ObjectRef* classPtr) : classObj(classPtr) { #if 0 void** target = new void*[100]; int count = Revoke::instance().GetMembers(classPtr, target); printf("Found %d members\n", count); for (int i = 0; i < count; i++) { auto* name = (const char*)target[i * 3]; auto mt = (MemberType)(uint64_t)target[i * 3 + 1]; auto* p = target[i * 3 + 2]; printf("%s %u\n", name, mt); Member member(name, cs::make_csptr(p), mt); memberMap.try_emplace(name, member); } #endif } cs::Obj operator()() { printf("Constructor on %p\n", classObj.get()); auto* obj = Revoke::instance().NamedCall("new", classObj.get(), 0, nullptr); return cs::Obj(cs::make_csptr(obj), classObj); } }; struct CSCall { cs::csptr method; CSCall(void* ptr) : method(cs::make_csptr(ptr)) {} sol::variadic_results operator()(cs::Obj& thiz, const sol::variadic_args va) { printf("MEMBER Called with %lu args\n", va.size()); int rc; int i = 0; void** pargs = new void*[va.size()]; // = {convert(args)...}; for (const auto& v : va) { auto t = v.get_type(); pargs[i] = nullptr; printf("TYPE %d\n", (int)t); switch (t) { case sol::type::number: printf("NUMBER\n"); rc = (int)v; pargs[i] = Revoke::instance().CreateFrom(ObjType::INT, &rc); break; case sol::type::string: pargs[i] = Revoke::instance().CreateFrom( ObjType::STRING, (void*)v.get<std::string>().c_str()); break; case sol::type::userdata: printf("TABLE\n"); if (v.is<cs::Obj>()) { printf("OBJ\n"); cs::Obj obj = v.get<cs::Obj>(); pargs[i] = obj.ptr.get(); } break; default: break; } i++; } Revoke::instance().MethodCall(method.get(), thiz.ptr.get(), va.size(), pargs); sol::variadic_results r; return r; } }; static sol::state& lua() { static sol::state lua; return lua; } enum MemberType { Constructor = 1, Property = 2, Field = 4, Method = 8 }; static void my_setter(const cs::Obj& obj, const char*, sol::object, sol::this_state s) { printf("In setter\n"); } static sol::object my_getter(const cs::Obj& obj, std::string const& name, sol::this_state s) { printf("In getter\n"); Revoke::instance().GetMember(); if (name == "TestFn") { return sol::make_object( s, [](cs::Obj& z, int x, cs::Obj& y) -> int { return 3; }); } return sol::make_object(s, 3); } static void init() { lua().open_libraries(sol::lib::base, sol::lib::package); std::string className = "GameObject"; void* t = Revoke::instance().GetType(className.c_str()); lua().new_usertype<cs::Obj>( className, "new", sol::factories(CSConstruct(t)), sol::meta_function::index, &my_getter, sol::meta_function::new_index, &my_setter //,sol::meta_function::new_index, &cs::Obj::set_field ); lua()["println"] = &puts; printf("Running script\n"); lua().script(R"( go = GameObject.new() go:TestFn(4, go) println("Test called") y = go.transform print(y) println("here") )"); // lua()["GameObject"]["static_call"] = CSStaticCall(); // lua()["GameObject"]["member_call"] = CSCall(); // lua().script("GameObject.static_call(1,2,3)\ngo = " // "GameObject.new()\ngo:member_call(3)\n"); } };
c7b37723aa8c94bf38218cd476641f496dd0658b
0f85d3cc4e7a81cf1578e8a8501c4abdc1aeba8b
/Berlin2/Berlin2.ino
50174c178caeb5cda1ac8916840c9ad5706206f7
[]
no_license
contrechoc/arduino_scripts
2407dbc4af1135da54a728ef0a80c19e6d4be81f
f5dbc2bc8e5a5eb0667c0313c27382c1606fd5b9
refs/heads/master
2021-01-13T01:26:27.187332
2014-05-12T17:25:20
2014-05-12T17:25:20
19,707,910
1
0
null
null
null
null
UTF-8
C++
false
false
10,658
ino
Berlin2.ino
// include the library code: #include <LiquidCrystal.h> #include <avr/pgmspace.h> // initialize the library with the numbers of the interface pins LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // sine lookup table pre-calculated prog_uchar PROGMEM sinetable[256] = { 128,131,134,137,140,143,146,149,152,156,159,162,165,168,171,174, 176,179,182,185,188,191,193,196,199,201,204,206,209,211,213,216, 218,220,222,224,226,228,230,232,234,236,237,239,240,242,243,245, 246,247,248,249,250,251,252,252,253,254,254,255,255,255,255,255, 255,255,255,255,255,255,254,254,253,252,252,251,250,249,248,247, 246,245,243,242,240,239,237,236,234,232,230,228,226,224,222,220, 218,216,213,211,209,206,204,201,199,196,193,191,188,185,182,179, 176,174,171,168,165,162,159,156,152,149,146,143,140,137,134,131, 128,124,121,118,115,112,109,106,103,99, 96, 93, 90, 87, 84, 81, 79, 76, 73, 70, 67, 64, 62, 59, 56, 54, 51, 49, 46, 44, 42, 39, 37, 35, 33, 31, 29, 27, 25, 23, 21, 19, 18, 16, 15, 13, 12, 10, 9, 8, 7, 6, 5, 4, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 15, 16, 18, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 42, 44, 46, 49, 51, 54, 56, 59, 62, 64, 67, 70, 73, 76, 79, 81, 84, 87, 90, 93, 96, 99, 103,106,109,112,115,118,121,124 }; // lookup table for output waveform unsigned char wavetable[256]; char a[3][14] = { "Happy doing", "Happy fabrics", "Happy sewing" }; // make some custom characters: byte heart[8] = { 0b00000, 0b01010, 0b11111, 0b11111, 0b11111, 0b01110, 0b00100, 0b00000 }; byte smiley[8] = { 0b00000, 0b00000, 0b01010, 0b00000, 0b00000, 0b10001, 0b01110, 0b00000 }; byte frownie[8] = { 0b00000, 0b00000, 0b01010, 0b00000, 0b00000, 0b00000, 0b01110, 0b10001 }; byte armsDown[8] = { 0b00100, 0b01010, 0b00100, 0b00100, 0b01110, 0b10101, 0b00100, 0b01010 }; byte armsUp[8] = { 0b00100, 0b01010, 0b00100, 0b10101, 0b01110, 0b00100, 0b00100, 0b01010 }; byte smile1[8] = { 0b10000, 0b10111, 0b10000, 0b00000, 0b01110, 0b00000, 0b10001, 0b01110 }; byte smile2[8] = { 0b01010, 0b11111, 0b01010, 0b00100, 0b00100, 0b00100, 0b10001, 0b01110 }; byte smile3[8] = { 0b00001, 0b11101, 0b01001, 0b00000, 0b01110, 0b00000, 0b11011, 0b01110 }; byte xxxxx[8] = { 0b10101, 0b01010, 0b10101, 0b01010, 0b10101, 0b01010, 0b10101, 0b01010 }; byte yyyyy[8] = { 0b10101, 0b01010, 0b00100, 0b01110, 0b00100, 0b01010, 0b10101, 0b01010 }; byte p1[8] = { 0b00000, 0b00100, 0b00000, 0b01000, 0b00010, 0b00000, 0b10000, 0b00010, }; byte p2[8] = { 0b10000, 0b00100, 0b00010, 0b01010, 0b01010, 0b00010, 0b10100, 0b10010, }; int px, px1 = 3; volatile int ff = 5; int timer1_counter, ccc; char cc, recycle, turn = 0; char t1 = 0; volatile char noInt = 1; void sineWave() { for (int i = 0; i < 256; ++i) { wavetable[i] = pgm_read_byte_near(sinetable + i); } } void setup() { sineWave(); lcd.createChar(0, heart); lcd.createChar(1, smiley); lcd.createChar(2, frownie); lcd.createChar(3, armsDown); lcd.createChar(4, armsUp); lcd.createChar(5, smile1); lcd.createChar(6, smile2); lcd.createChar(7, smile3); lcd.createChar(8, xxxxx); lcd.createChar(9, yyyyy); lcd.createChar(10, p1); lcd.createChar(11, p2); // set up the lcd's number of columns and rows: lcd.begin(16, 4); lcd.setCursor(0, 0); lcd.clear(); lcd.home(); saw(); circle(); turn = 1; writeFlight(9,10); writeTextiles(); delay(1000); writeFlight(10, 11); writeRecycle(); delay(1000); // initialize timer1 noInterrupts(); // disable all interrupts TCCR1A = 0; TCCR1B = 0; // Set timer1_counter to the correct value for our interrupt interval //timer1_counter = 64886; // preload timer 65536-16MHz/256/100Hz //timer1_counter = 64286; // preload timer 65536-16MHz/256/50Hz timer1_counter = 64286/11*10; // preload timer 65536-16MHz/256/2Hz TCNT1 = timer1_counter; // preload timer TCCR1B |= (1 << CS10) | (1 << CS12); // 256 prescaler TIMSK1 |= (1 << TOIE1); // enable timer overflow interrupt interrupts(); // enable all interrupts ff = 0; writeHappy(); } void loop() { if ( px > 12 ) { px = 4; writeHappy(); } cli(); lcd.setCursor(0, 0); sei(); character(px++,1); if (px1 < 1) px1 = 5; cli(); lcd.setCursor(0,0); sei(); character(px1--,3); turn++; if ( turn > 2 ){ writeTextiles(); turn = 0; writeHappy(); recycle++; } if ( recycle > 3){ recycle = 0; writeRecycle(); } /* while(ff> 0) { lcd.setCursor(0, 0); lcd.clear(); int fx = analogRead(A0)/255; int fy = analogRead(1)/64; lcd.setCursor(fx,fy); lcd.write(5); delay(10); lcd.setCursor(fx,fy); lcd.write(6); delay(10); lcd.setCursor(fx,fy); lcd.write(7); delay(100); ff--; } */ } ISR(TIMER1_OVF_vect) // interrupt service routine { if ( noInt == 1 ) { TCNT1 = timer1_counter; // preload timer lcd.setCursor((cc++)/4,ccc); if (ff == 0) lcd.write(5); else if (ff == 1) lcd.write(6); else if (ff == 2) lcd.write(7); ff++; if ( ff > 3) ff = 0; if ( cc > 60 ) { cc = 0; ccc = random(4); } } } void character(int cx, int cy){ // map the result to 200 - 1000: int delayTime = 150; // set the cursor to the bottom row, 5th position: cli(); lcd.setCursor(cx, cy); lcd.write(3); sei(); delay(delayTime); cli(); lcd.setCursor(cx, cy); lcd.write(4); sei(); delay(delayTime); } void writeHappy(){ cli(); lcd.setCursor(0, 0); lcd.clear(); sei(); if ( t1 == 0 ) { cli(); lcd.print("Happy Fabrics"); sei(); t1=2; } else if ( t1 == 1) { cli(); lcd.print("Happy Threading"); sei(); t1++; } else if ( t1 == 2) { cli(); lcd.print("Happy Living"); sei(); t1++; } else if ( t1 == 3) { cli(); lcd.print("Happy Working"); sei(); t1++; } else if ( t1 == 4) { cli(); lcd.print("Happy Thinking"); sei(); t1++; } else if ( t1 == 5) { cli(); lcd.print("Happy Doing"); sei(); t1 = 0; } int pos[3] = { random(3),random(3),random(3) }; int h = random(3); while ( h == pos[0] ) h = random(3); pos[1] = h; h = random(3); while ( (h == pos[0]) || (h == pos[1]) ) h = random(3); pos[2] = h; cli(); lcd.setCursor(random(8),1); lcd.print( a[pos[0]] ); lcd.setCursor(random(4),2); lcd.print(a[pos[1]]); lcd.setCursor(random(5),3); lcd.print(a[pos[2]] ); sei(); delay(500); } void writeTextiles(){ while (turn-- > 0 ){ //lcd.scrollDisplayLeft(); cli(); lcd.clear(); lcd.home(); sei(); for ( int i = 0; i < 4 ; i++){ cli(); lcd.setCursor(15, i+1); delay(30); lcd.write(5); sei(); } delay(500); for ( int i = 0; i < 2 ; i++) for ( int i2 = 0; i2 < 16 ; i2++){ cli(); lcd.setCursor(i2, i); lcd.write(8); sei(); delay(30); } for ( int i = 2; i < 4 ; i++) for ( int i2 = 0; i2 < 16 ; i2++){ cli(); lcd.setCursor(i2-4, i); lcd.write(9); sei(); delay(50); } delay(500); for ( int i2 = 0; i2 < 10 ; i2++){ cli(); lcd.setCursor(i2+3, 1); lcd.write(" "); lcd.setCursor(i2-1, 2); lcd.write(" "); sei(); delay(50); } delay(500); cli(); lcd.setCursor( 3, 1); lcd.write(" happy e-"); lcd.setCursor(0, 2); lcd.write("textiles"); sei(); delay(500); } } void writeRecycle(){ noInt = 0; cli(); lcd.setCursor(0, 0); lcd.clear(); lcd.print("Please"); lcd.setCursor(0,1); lcd.print(" Recycle! "); lcd.setCursor(1,2); lcd.print("me! "); lcd.setCursor(2,3); lcd.print(" :-):-):-):-):-) "); sei(); delay(1000); noInt = 1; } void writeFlight(int whichSign, int whichSign2){ cli(); lcd.setCursor(0, 0); lcd.clear(); sei(); lcd.setCursor(0, 0); lcd.write(whichSign); lcd.setCursor(0, 1); lcd.write(whichSign); lcd.setCursor(-4, 2); lcd.write(whichSign); lcd.setCursor(-4, 3); lcd.write(whichSign); lcd.scrollDisplayLeft(); for ( int i2 = 0; i2 < 16 ; i2++){ cli(); lcd.scrollDisplayRight(); sei(); delay(150); } for ( int i2 = 0; i2 < 16 ; i2++){ cli(); lcd.scrollDisplayLeft(); sei(); delay(150); } for ( int i = 0; i < 4 ; i++){ for ( int i2 = 0; i2 < 16 ; i2++){ if ( i < 2 ) lcd.setCursor(i2, i); else lcd.setCursor(i2 - 4, i); lcd.write(whichSign); } delay(150); for ( int i2 = 0; i2 < 16 ; i2++){ if ( i < 2 ) lcd.setCursor(i2, i); else lcd.setCursor(i2 - 4, i); lcd.print(" "); } delay(150); } // delay(2000); lcd.setCursor(0, 0); lcd.clear(); for ( int i = 3; i >=0 ; i--){ for ( int i2 = 0; i2 < 17 ; i2++){ if ( i < 2 ) lcd.setCursor(i2, i); else lcd.setCursor(i2 - 4, i); lcd.write(whichSign2); } delay(150); for ( int i2 = 0; i2 < 16 ; i2++){ if ( i < 2 ) lcd.setCursor(i2, i); else lcd.setCursor(i2 - 4, i); lcd.print(" "); } delay(150); } delay(500); lcd.setCursor(0, 0); lcd.clear(); } void circle(){ lcd.setCursor(0, 0); lcd.clear(); for ( int i2 = 0; i2 < 255 ; i2+=5){ int xp = 16*wavetable[ i2]/256; int yp = 4*wavetable[ (i2 + 64)%255]/256; if ( yp < 2 ) lcd.setCursor(xp, yp); else lcd.setCursor(xp-4, yp); lcd.print("*"); delay(100); } delay(500); lcd.setCursor(1, 1); lcd.print("threading"); lcd.setCursor(-2, 2); lcd.print("the universe"); delay(1000); } void saw(){ lcd.setCursor(0, 0); lcd.clear(); for ( int i2 = 0; i2 < 256*4; i2+=25){ int xp = i2/64; int yp = 4*wavetable[ i2%255]/256; if ( yp < 2 ) lcd.setCursor(xp, yp); else lcd.setCursor(xp-4, yp); lcd.print("*"); //delay(50); } delay(500); lcd.setCursor(1, 1); lcd.print(" fabrics"); lcd.setCursor(-2, 2); lcd.print(" of space"); delay(1000); }
9e4f55552ce580ff34c15933f80b815966b98e3b
9c7c58220a546d583e22f8737a59e7cc8bb206e6
/Project/MyProject/MyProject/Source/MyProject/Private/BaseFrame/Libs/Math/MWrapQuaternion.cpp
764bc70c2b6e87c906ec2f9296b7fee74a18e250
[]
no_license
SiCoYu/UE
7176f9ece890e226f21cf972e5da4c3c4c4bfe41
31722c056d40ad362e5c4a0cba53b05f51a19324
refs/heads/master
2021-03-08T05:00:32.137142
2019-07-03T12:20:25
2019-07-03T12:20:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,471
cpp
MWrapQuaternion.cpp
#include "MyProject.h" #include "MWrapQuaternion.h" #include "UtilMath.h" MY_BEGIN_NAMESPACE(MyNS) MWrapQuaternion::MWrapQuaternion() { this->mIsEulerAngleInvalid = true; this->setRotation(UtilMath::UnitQuat); } MWrapQuaternion::MWrapQuaternion(float x, float y, float z, float w) { this->mIsEulerAngleInvalid = true; FQuat rotation(x, y, z, w); this->setRotation(rotation); } void MWrapQuaternion::clear() { this->mIsEulerAngleInvalid = true; FQuat rotation(0, 0, 0, 1); this->setRotation(rotation); } void MWrapQuaternion::setRotateXYZW(float x, float y, float z, float w) { this->mIsEulerAngleInvalid = true; this->mRotate = FQuat(x, y, z, w); } float MWrapQuaternion::getX() { return this->mRotate.X; } float MWrapQuaternion::getY() { return this->mRotate.Y; } float MWrapQuaternion::getZ() { return this->mRotate.Z; } float MWrapQuaternion::getW() { return this->mRotate.W; } FVector& MWrapQuaternion::getRotateEulerAngle() { if (this->mIsEulerAngleInvalid) { this->mRotateEulerAngle = this->mRotate.Euler(); this->mIsEulerAngleInvalid = false; } return this->mRotateEulerAngle; } void MWrapQuaternion::setRotateEulerAngle(FVector& rotation) { this->mRotateEulerAngle = rotation; this->mRotate = FQuat::MakeFromEuler(rotation); } FQuat& MWrapQuaternion::getRotate() { return this->mRotate; } void MWrapQuaternion::setRotation(FQuat& rotation) { this->mIsEulerAngleInvalid = true; this->mRotate = rotation; } MY_END_NAMESPACE
f71e2e8f661c6f173c4e177c52143daeb23f650b
3e2b6d4966cc7d63b56d02646d891af8723683e7
/Problem.h
3dbf06d2df332fbbb7966c2cc04b4b9957b10a9d
[]
no_license
JarJarBB/TLBO
150bf8aa71de4b9af4364ad223038797aab86c33
ca843ff5925999a7c4d07217d20747de9580abd1
refs/heads/master
2021-08-27T18:00:38.435498
2021-08-25T20:02:09
2021-08-25T20:02:09
157,550,825
0
0
null
null
null
null
UTF-8
C++
false
false
1,037
h
Problem.h
#ifndef PROBLEM_H #define PROBLEM_H #include <iostream> #include <vector> using namespace std; enum fonction {Rosenbrock, Rastrigin, Ackley, Schwefel, Schaffer, Weierstrass, TheSpecialFunction}; class Problem { public: Problem(int dimension, fonction f); ~Problem(); friend ostream& operator<<(ostream& os, const Problem& pbm); friend istream& operator>>(istream& is, Problem& pbm); Problem& operator=(const Problem& pbm); bool operator==(const Problem& pbm) const; bool operator!=(const Problem& pbm) const; Problem& operator++(); string name() const; int dimension() const; fonction func() const; long long int callsToFunction() const; void max_intervalle (const int val); void min_intervalle (const int val); double max_intervalle () const; double min_intervalle () const; private: int _dimension; fonction _fonction; double _max_intervalle; double _min_intervalle; long long int _calls_to_function; }; #endif // PROBLEM_H
59d64fab8d66b0bb10ef711c492ce623640b7e97
328d6b40cd67a9ef5dfb54ce9637bc9383fa40d6
/window_issuebook.h
5802c8da5d51b6d6d530263c5ce5501cb514d969
[]
no_license
Nilsae/LibraryManagementSystem
b9b6d05e9af873aceb39be5dfce891cae026e0d0
638a79efcdbdf8970834748a9362a51b6fe70294
refs/heads/master
2023-07-18T07:08:27.950115
2021-09-12T19:00:20
2021-09-12T19:00:20
272,802,962
1
1
null
null
null
null
UTF-8
C++
false
false
439
h
window_issuebook.h
#ifndef WINDOW_ISSUEBOOK_H #define WINDOW_ISSUEBOOK_H #include <QDialog> namespace Ui { class Window_IssueBook; } class Window_IssueBook : public QDialog { Q_OBJECT public: explicit Window_IssueBook(QWidget *parent = nullptr); ~Window_IssueBook(); private slots: void on_pushButton_IssueBook_clicked(); void on_pushButton_search_clicked(); private: Ui::Window_IssueBook *ui; }; #endif // WINDOW_ISSUEBOOK_H
3f141b3054a68fabb412ffb53584865d78f91916
5a64100bc513863583ce95fb835d84c027646ece
/main.cpp
1377079c49830e8327d975a1e60f5b2f7ccbb3bd
[]
no_license
JJ-NavaC/ASM-Examples
56d1ee2df7345ca558e48a94d41fb04a831ba4ea
c9cf5a8e115b304b7e7e4e82f57eb608bf54227d
refs/heads/main
2023-08-15T08:21:14.894998
2021-10-12T01:05:20
2021-10-12T01:05:20
416,134,340
0
0
null
null
null
null
UTF-8
C++
false
false
768
cpp
main.cpp
#include <stdio.h> #include <iostream> using namespace std; int main() { int a, b, add, sub, mul, quo, res; cout << "Enter 2 numbers: "; cin >> a; cin >> b; __asm__ ( "addl %%ebx, %%eax;" : "=a" (add) : "a" (a) , "b" (b) ); __asm__ ( "subl %%ebx, %%eax;" : "=a" (sub) : "a" (a) , "b" (b) ); __asm__ ( "imull %%ebx, %%eax;" : "=a" (mul) : "a" (a) , "b" (b) ); __asm__ ( "movl $0x0, %%edx;" "movl %2, %%eax;" "movl %3, %%ebx;" "idivl %%ebx;" : "=a" (quo), "=d" (res) : "a" (a), "b" (b) ); cout << a << " + " << b << " = " << add << endl; cout << a << " - " << b << " = " << sub << endl; cout << a << " * " << b << " = " << mul << endl; cout << a << " / " << b << " = " << quo << endl; return 0; }
1d20a10f6d1a2b1a4b49b8bdd9e2b6065f8b8074
792c698496d15a7386c60dd3eac0a189e3ee64e7
/kadane.cpp
b567ed095d1d3ffdf43a4942893fcd1ad80872ef
[]
no_license
upeshsahu/algos-and-comp-code
72313decd5bcc2444f8bd95037a619bbb35a03f9
2022f8cba9bf27a59a79bbdf558e0e42b709a17e
refs/heads/master
2018-09-25T17:39:56.570536
2018-06-07T06:01:15
2018-06-07T06:01:15
120,885,145
2
0
null
null
null
null
UTF-8
C++
false
false
626
cpp
kadane.cpp
#include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int a[n]; for(int i=0;i<n;i++) cin>>a[i]; int max_ending=0, max_so_far=INT_MIN; for(int i=0;i<n;i++) { max_ending+=a[i]; if(max_ending>max_so_far) max_so_far=max_ending; if(max_ending<0) max_ending=0; } //very effective for negative numbers for nagatibe numbers int max_ending=a[0], max_so_far=a[0]; for(int i=0;i<n;i++) { max_ending=max(max_ending+a[i],a[i]); max_so_far=max(max_so_far,max_ending); } cout<<max_so_far<<endl; return 0; }
74bfa197333036c0b098bd0320d7fe8017479fbd
ed00c2a0a3844976618e6604a2c3af8d3b76c8ba
/seaweed.h
6345387de64c2aeab7ffdbc0fec54afe19b16130
[]
no_license
AurelieT1/javaquarium
9a1f382124477036bf808595ab1ca299c265584e
b41048c1f125a3ad7ddb16014715f575ee93cfa7
refs/heads/master
2016-09-01T09:18:56.317016
2016-04-19T19:32:51
2016-04-19T19:32:51
55,862,002
0
0
null
null
null
null
UTF-8
C++
false
false
286
h
seaweed.h
#ifndef SEAWEED_H #define SEAWEED_H class Seaweed { public: void addHealthPoints(unsigned i); void removeHealthPoints(unsigned i); unsigned getHealthPoints() const { return healthPoints; } private: unsigned healthPoints = 10; }; #endif // SEAWEED_H
a71a23769190646fd5e9cc51d0226731929c9c67
3d8d2e4ebe08730cbbed3edd590c3ffa0b9bb732
/Inversions in Array/naive_inversion.cpp
d8050d0658c897c7a32d3ebb9a4783210ab4e5e9
[]
no_license
InnoCentCoder5497/DSA-in-C-plus-plus
762ce2e9ccf30ac98f15f6821c4f3e737bc7ebfa
4afc9afd47c6ea9ca0fe0dad95e767d402a74d4a
refs/heads/master
2022-12-09T06:29:31.930326
2020-09-14T08:30:49
2020-09-14T08:30:49
285,457,864
3
0
null
null
null
null
UTF-8
C++
false
false
574
cpp
naive_inversion.cpp
#include<iostream> using namespace std; void print_inversions(int[], int); int main() { int arr[5] = {2, 3, 8, 6, 1}; int i; cout << "Input Array : " << endl; for(i = 0; i < 5; i++) cout << arr[i] << " "; cout << endl; print_inversions(arr, 5); return 0; } void print_inversions(int arr[], int size){ int i, j; for(i = 0; i < size; i++){ for(j = i+1; j < size; j++){ if(arr[i] > arr[j]){ cout << "Inversion : (" << arr[i] << " , " << arr[j] << ")" << endl; } } } }
809b529209e7219e852a224989364bb8f536b690
4c6a5de3be02e8b585e6e0ab3e7feff5b83d03c4
/SESH++/LittleRedundantVampire/src/Observer/IListener.h
59fc3a2a930c1db165d55f185b74c9ef13129631
[]
no_license
henrikgram/SeshExamC-PlusPLus
1187747e62564c6d634486bdd0c70a04e8ed6975
09d8ace0c2a8cddf62cbf385ab31b37a2f894802
refs/heads/main
2023-04-30T08:09:25.299863
2021-05-28T12:42:25
2021-05-28T12:42:25
360,512,153
0
0
null
null
null
null
UTF-8
C++
false
false
560
h
IListener.h
#ifndef ILISTENER_H #define ILISTENER_H #include <string> /// <summary> /// Observer: Interface for listeners to events. /// </summary> class IListener { public: /// <summary> /// Executes code that should happen when Notify is called for an event that this listener is subscribed to. /// </summary> /// <param name="eventName"> The name of the event that has occured </param> /// <param name="sender"> A listener, typically the one who called the Notify method. </param> virtual void OnNotify(std::string eventName, IListener* sender) = 0; }; #endif
3edf5274899a2cbfdf289654fac952ed6b660613
7033a9f0cf9ae1ef0312d100af01cc3e69b54fd8
/patternPrint.cpp
cad6d20ccdba155e5241d77879db77c3d73b9645
[]
no_license
sivajayaraman/Interview-Preparation
5dd9161ff08dda15f3ea5792c62e59c2b3b9bfca
4d0fd5a6cc2d71739e7f5ef04ae8f715799fa5d1
refs/heads/master
2021-07-06T12:46:27.723295
2020-07-31T11:09:26
2020-07-31T11:09:26
151,400,512
0
0
null
null
null
null
UTF-8
C++
false
false
410
cpp
patternPrint.cpp
#include <iostream> using namespace std; int printPrime(int n){ while(1){ for(i=2;;i++){ } } } int printComposite(){ } int main(){ int n,i,j,prime=1,composite=3; cin>>n; for(i=1;i<=n;i++){ for(j=1;j<=i;j++){ if(i%2==0){ composite=printComposite(composite); cout<<composite<<" "; } else { prime=printPrime(prime); cout<<prime<<" "; } } cout<<endl; } return 0; }
74fc9d25dbf48421e7dd16e2863a5bf7037751fe
624c21d571563a2f76ee9892fd333b8e329e8e22
/MathsTest/Maths/Convert.h
d74f4dc3a076cc0119840aa0e0cc3428f0758ae9
[ "MIT" ]
permissive
JSlowgrove/GCP-Assignment-1-Quats-Vs-Mats
0bb29f83672fd55ae2aca0417bdad56e74feae40
0b4a1681e955466904edc8a354749db94c5cbdba
refs/heads/master
2020-03-30T20:11:30.967249
2018-10-05T16:57:19
2018-10-05T16:57:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
681
h
Convert.h
//DISCLAMER - This is a modified version of code from one of my other assignments. #pragma once #include "MathsDefs.h" /** @brief The namespace for all maths code. */ namespace Maths { /** @brief Contains maths conversion functions for use within the code. */ namespace Convert { /** @brief Converts the degree to a radian. @param angle The angle to convert. @returns The converted radian. */ float convertDegreeToRadian(float angle); /** @brief Converts the radian to a degree. @param angle The angle to convert. @returns The converted degree. */ float convertRadianToDegree(float angle); }//End of Convert namespace }//End of Maths namespace
9d561dd3d49eabc2d93f76d7a44bd2dfa72f8d55
3ee7b57056d946c8f9ec2ea886c0b613a65d8131
/客户端/mySHA.h
647db9ed6ea93bdb5d748750ddc22fb69e853481
[]
no_license
zhangshaoxiao/CryptoServer
f163c08dc5d483efb68e2cf996856689b1966f0d
412dc14b609e9fea3e789c26bb8e028fcd35c2b9
refs/heads/master
2021-01-20T15:43:00.024117
2017-09-19T09:42:47
2017-09-19T09:42:47
95,709,157
2
1
null
null
null
null
UTF-8
C++
false
false
226
h
mySHA.h
#include<string> //using namespace std; #ifndef mySHA_H #define mySHA_H void CalculateDigest(std::string &Digest, const std::string &Message); bool VerifyDigest(const std::string &Digest, const std::string &Message); #endif
c9cbd68bd75916672ba218659bbf18fc964d51b3
668c769bbdd6cf72391d150b36502d3bd55b629b
/Hash_Tagger.cpp
8d68246e1aa61cdeb2d45d018af98b08b2e718ce
[]
no_license
AKKamath/Naive_Bayes_Classifier
c3568244febc97e1ef4091d0da9d56ce5ae6061a
d40d1cc7a414776ea93dc72567d90b5bb931d2a9
refs/heads/master
2022-11-15T04:07:19.198486
2022-11-05T08:09:06
2022-11-05T08:09:06
92,395,991
0
0
null
null
null
null
UTF-8
C++
false
false
5,044
cpp
Hash_Tagger.cpp
#include <iostream> #include <string.h> #include <map> #include <string> #include <fstream> #include <vector> #include <algorithm> #include <sys/stat.h> #include <stdlib.h> using namespace std; #define TAG_SIZE unsigned int struct stat sb; // Check if file exists bool fileExists(const char *fileName) { ifstream infile(fileName); return infile.good(); } // Structure of a tag struct TagStructure { TAG_SIZE id; string name; string category; TagStructure() { id = 0; name = ""; category = ""; } }; // Used to store tags class TagStorage { // Stores the tags // string is the tagName, TAG_SIZE is the ID map<string, TagStructure> tag; public: // Used to read from file and create tags void init(string file); // Access tags by string name TAG_SIZE operator [] (string tag_name) { if(tag[tag_name].id == 0) return -1; return tag[tag_name].id; } // Get the TagStructure itself TagStructure get(string tag_name) { return tag[tag_name]; } // Output all tags void print(); }; // Output all tags and details void TagStorage::print() { cout<<"Name\tTag\n"; for(map<string, TagStructure>::iterator it = tag.begin(); it != tag.end(); ++it) { cout<<it->first<<"\t"<<it->second.id<<"\n"; } } // Read tags from file and assign values void TagStorage::init(string file) { if(!fileExists(file.c_str())) { cout<<"Error, "<<file<<" does not exist!\n"; return; } ifstream f(file.c_str(), ios::in); // Read tag id, create data, and store string s; while(getline(f, s, ',')) { if(s.empty()) break; TagStructure t; t.id = stoi(s); getline(f, s, ','); t.name = s; getline(f, s); t.category = s; tag[t.name] = t; } } // Read training data from files void assignValues(string directory, TagStorage tags) { // Start from 0.txt int i = 0; // We found a save file, save time and start from where we left off? if(fileExists((directory + "save_state.sav").c_str())) { cout<<"Save found, continue from this location? (1 = Yes, 0 = No)\n"; int opt; cin>>opt; // Nah, delete all saved data and restart if(opt == 0) { remove((directory + "save_state.sav").c_str()); system("rm -r Data"); } // Resume from last saved location else { ifstream in((directory + "save_state.sav").c_str()); in>>i; ++i; } } string word; for(;; ++i) { // No more files of required format found if(!fileExists((directory + to_string(i) + ".txt").c_str()) || !fileExists((directory + to_string(i) + ".key").c_str())) { cout<<"Reached "<<i<<".txt\n"; break; } // Open required files ifstream main_file((directory + to_string(i) + ".txt").c_str(), ios::in); ifstream tag_file((directory + to_string(i) + ".key").c_str(), ios::in); vector<TAG_SIZE> v; map<string, int> counter; string s; // Read tags from file while(getline(tag_file, s)) { if(tags[s] != -1) v.push_back(tags[s]); } bool skip = false; while(!main_file.eof()) { // Read character by character char l; main_file.read((char *)&l, sizeof(l)); // Ignore lines within <> and punctuation if(l == '>') skip = false; else if(l == '<') skip = true; if(skip) continue; if(l == '\'') continue; // Completed a word, so we store it if(!isalpha(l)) { if(word.length() != 0) { counter[word]++; } word.clear(); } // Didn't complete a word, so concatenate last letter to current word else { word += tolower(l); } } // Check if Data directory exists, if not create it if (!(stat("./Data", &sb) == 0 && S_ISDIR(sb.st_mode))) { system("mkdir Data"); } // Store all words encountered for(map<string, int>::iterator c_iter = counter.begin(); c_iter != counter.end(); ++c_iter) { map<TAG_SIZE, int> inp; string path = ("Data/" + c_iter->first + ".word"); // Word has been encountered before, increment tags for that word if(fileExists(path.c_str())) { ifstream infile(path.c_str(), ios::in | ios::binary); TAG_SIZE t; int val; // Read values for each tag while(infile.read((char *) &t, sizeof(t))) { infile.read((char *) &val, sizeof(val)); inp[t] = val; } infile.close(); } // Increment values for each tag for(vector<TAG_SIZE>::iterator it = v.begin(); it != v.end(); ++it) inp[*it] += c_iter->second; ofstream outfile(path.c_str(), ios::out | ios::binary); // Write back new values to the file for(map<TAG_SIZE, int>::iterator it = inp.begin(); it != inp.end(); ++it) { outfile.write((char *) &it->first, sizeof(it->first)); outfile.write((char *) &it->second, sizeof(it->second)); } outfile.close(); } main_file.close(); tag_file.close(); // Create a save state ofstream out((directory + "save_state.sav").c_str(), ios::out); out<<i; } } int main(int argv, char *argc[]) { if(argv < 3) { cout<<"Argument format: Vocabulary Test_Location\n"; return 1; } TagStorage tag; tag.init(argc[1]); //tag.print(); assignValues(argc[2], tag); return 0; }
a5dbc2b0257839513e00c0a73be906baa8906000
44ab57520bb1a9b48045cb1ee9baee8816b44a5b
/Engine/Code/AssistTools/GenerateProjects/GenerateTemplateModuleVcxprojFilters.cpp
ab33c9b3231db2afad6f195fb8230ba8fce686a3
[ "BSD-3-Clause" ]
permissive
WuyangPeng/Engine
d5d81fd4ec18795679ce99552ab9809f3b205409
738fde5660449e87ccd4f4878f7bf2a443ae9f1f
refs/heads/master
2023-08-17T17:01:41.765963
2023-08-16T07:27:05
2023-08-16T07:27:05
246,266,843
10
0
null
null
null
null
GB18030
C++
false
false
1,142
cpp
GenerateTemplateModuleVcxprojFilters.cpp
/// Copyright (c) 2010-2022 /// Threading Core Render Engine /// /// 作者:彭武阳,彭晔恩,彭晔泽 /// 联系作者:94458936@qq.com /// /// 标准:std:c++20 /// 引擎版本:0.9.0.12 (2022/04/29 13:48) #include "AssistTools/AssistToolsExport.h" #include "GenerateTemplateModuleVcxprojFilters.h" #include "Detail/GenerateTemplateModuleVcxprojFiltersImpl.h" #include "CoreTools/Helper/ClassInvariant/AssistToolsClassInvariantMacro.h" AssistTools::GenerateTemplateModuleVcxprojFilters::GenerateTemplateModuleVcxprojFilters(const System::String& templateFileName, const System::String& projectName, const System::String& moduleName) : impl{ templateFileName, projectName, moduleName } { ASSIST_TOOLS_SELF_CLASS_IS_VALID_1; } CLASS_INVARIANT_STUB_DEFINE(AssistTools, GenerateTemplateModuleVcxprojFilters) void AssistTools::GenerateTemplateModuleVcxprojFilters::GenerateTo(const System::String& resourceDirectory, const System::String& solutionName, const System::String& newModuleName) const { ASSIST_TOOLS_CLASS_IS_VALID_CONST_1; return impl->GenerateTo(resourceDirectory, solutionName, newModuleName); }
c7d2ad6988557c89cf5606fd1929e7309aa5bf60
b310a77e681dff025075d2b9bb3c1bdf5759d73b
/Laboratorio5/ejercicio2.cpp
301c5c37aea62223cc4d8ffcb276232c5ead1b9a
[]
no_license
RebV20/FundaLabos
291e2cf5eb754d0bafce8824368545df930d8437
43415c7563fe1d2bf1f3516c0708e39be62fffc7
refs/heads/master
2022-11-21T07:22:32.878604
2020-07-12T15:41:46
2020-07-12T15:41:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
742
cpp
ejercicio2.cpp
#include "iostream" using namespace std; int hora(int hour,int minuto, int segundo); int main(){ int hour,minuto,segundo, hora_s; cout<<"Ingrese una hora y aparecera un segundo despues \nIngrese la hora (formato 24 horas)"<<endl; cin>>hour; cout<<"Ingrese los minutos"<<endl; cin>>minuto; cout<<"Ingrese los segundos"<<endl; cin>>segundo; segundo++; hora_s= hora(hour, minuto, segundo); cout<<"La hora un segundo despues es: "<<hour<<":"<<minuto<<":"<<segundo; } int hora(int hour,int minuto, int segundo){ if(segundo>=59){ segundo=0; minuto=minuto++; } if(minuto>=59){ minuto=0; hour=hour++; } if(hour>=59){ hour=0; } }
0f406cf7ec9f70ace408a7fe7c771e4d153974da
36d57b306e434cfad38907a29eef45e9c720a271
/BlackWindowEngine/Object.h
dae142cc0d0801591e8164777ac57388eca7839d
[]
no_license
SHSongs/BlackWindowEngine
1f9a726d7cb6cfbe6ab5e8a164324a72b5558187
36d2e50b15c0caad4f98feec2ee1cd2f62fddac4
refs/heads/master
2021-03-18T04:13:36.160437
2020-05-03T07:34:46
2020-05-03T07:34:46
258,995,719
1
0
null
null
null
null
UTF-8
C++
false
false
1,293
h
Object.h
#pragma once #include<iostream> #include "Unit.h" class Object { protected: std::string name; std::string shape; std::string Type; FPosition position; Area area; std::string Direction; float Speed = 0.2; FPosition Up = { 0, Speed }; FPosition Down = { 0, -Speed }; FPosition Left = { -Speed, 0 }; FPosition Right = { Speed, 0 }; public: Object(); Object(FPosition p); Object(FPosition p, std::string name, std::string shape, std::string Type); Object(FPosition p, std::string name, std::string shape, Area area, std::string Type); Object(FPosition p, std::string name, std::string shape, std::string direction, std::string Type); Object(FPosition p, std::string name, std::string shape, Area Area, std::string direction, std::string Type); std::string GetName(); void SetName(std::string name); FPosition GetPosition(); void SetPosition(FPosition p); std::string GetShape(); void SetShape(std::string shape); std::string getDirection(); void setDirection(std::string D); std::string getType(); void setType(std::string t); void Push(std::string Direction); void Translate(FPosition p); void Translate(FPosition p, std::string shape); void TryWork(); Area GetArea(); virtual void Work(); virtual void OnCollision(Object* other); };
f7b4d449bfeab10f37208ac98daa69800e8b5367
9e48764d4ac607eb6baf775b1ac439f30cba06be
/parse_headers.re
71804dcbaefc493e9b5aaa99a8e4eb1c01f5cc00
[ "CC0-1.0" ]
permissive
rlew631/the-bike-shed
19b1cf525c2ce66ca0371df13111421640a1bc48
19713075795e711f38f81c44d9442b24450b5f48
refs/heads/master
2023-08-19T23:31:57.755736
2021-10-22T19:24:42
2021-10-22T19:24:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
736
re
parse_headers.re
enum HEADER_TYPE { HEADER_TYPE_INVALID, HEADER_TYPE_OTHER, HEADER_TYPE_LAST_MODIFIED, HEADER_TYPE_ETAG, }; struct ParsedHeader { int type; char * value; }; static struct ParsedHeader parse_header(char *YYCURSOR) { char * YYMARKER, * start = 0, * end; struct ParsedHeader ret = {HEADER_TYPE_INVALID, 0}; #define RET(m_type) ({ ret.type = HEADER_TYPE_ ## m_type; ret.value = start; return ret; }) /*!stags:re2c format = 'char *@@;'; */ /*!re2c re2c:define:YYCTYPE = char; re2c:yyfill:enable = 0; re2c:flags:tags = 1; * { RET(OTHER); } [\x00] { RET(INVALID); } "Last-Modified:" [ ]* @start { RET(LAST_MODIFIED); } "ETag:" [ ]* ["] @start [^\x00]* @end ["] { *end = 0; RET(ETAG); } */ }
a3d6d5d8cb7d18a0c4716242aa6dd9fd77e6c108
83010fe0442b0cf6f7260ee71a452d087f328a5d
/felinar.cpp
4d39f15137c2e6b6feb311eebf1d579778ea6afa
[]
no_license
samkumartp/Competitive-programming-problems
d6b32233d36dbd91fe5c78d2f4b4e37afcfe67df
399d966d5e77aae4c3823405e3989b4e1b1bbea5
refs/heads/master
2020-04-08T11:54:06.225640
2017-09-17T16:25:35
2017-09-17T16:25:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,454
cpp
felinar.cpp
# include <cstdio> # include <vector> # include <cstring> # include <algorithm> # define NR 10005 using namespace std; vector <int> v[NR]; int i,j,n,m,cuplate,sol,x,y; int M1[NR], M2[NR], ap[NR], SL[NR], SR[NR]; int match (int k) { int i; if (ap[k]) return 0; ap[k]=1; for (i=0; i<v[k].size(); ++i) if (! M2[v[k][i]]) { M1[k]=v[k][i]; M2[v[k][i]]=k; SL[k] = 1; return 1; } for (i=0; i<v[k].size(); ++i) if (match(M2[v[k][i]])) { M1[k]=v[k][i]; M2[v[k][i]]=k; SL[k] = 1; return 1; } return 0; } void support(int k) { for(int i=0; i<v[k].size(); ++i) if(! SR[v[k][i]]) { SR[v[k][i]] = 1; SL[M2[v[k][i]]] = 0; support(M2[v[k][i]]); } } int main () { freopen ("felinare.in", "r", stdin); freopen ("felinare.out", "w", stdout); scanf ("%d%d", &n, &m); for (i=1; i<=m; ++i) { scanf ("%d%d", &x, &y); v[x].push_back(y); } cuplate=1; while (cuplate) { cuplate=0; memset (ap, 0, sizeof(ap)); for (i=1; i<=n; ++i) if (!M1[i]) cuplate+=match(i); } for (i=1; i<=n; ++i) if (M1[i]) ++sol; printf("%d\n", 2*n - sol); for(i=1; i<=n; ++i) if(!SL[i]) support(i); for(i=1; i<=n; ++i) printf("%d\n",3-SL[i]-2*SR[i]); return 0; }
e2bbae822bc4b7f196c8828ca9444640ed4badc5
cac6f203a469df349a01e26097864c3aa4915e72
/examples/SerialTest/SerialTest/SerialTest.ino
9cbb97390b0c081f8f5e29abc39adb5f7b8f7295
[]
no_license
stembotvn/Alcohol_MQ3
4d78a0c049b29a238ac4d142f4fc96109a16dc48
1344209c3ccf657e536644509fb83e6a1f05bf80
refs/heads/master
2020-12-05T06:52:00.546356
2020-01-06T08:32:33
2020-01-06T08:32:33
232,039,794
0
0
null
null
null
null
UTF-8
C++
false
false
398
ino
SerialTest.ino
#include <MQ3_alcohol.h> MQ3 mq3; void setup() { // put your setup code here, to run once: Serial.begin(9600); Serial.println("Calibrating..."); mq3.setupMQ3(A0,1000); mq3.calibrateMQ3(); Serial.println("Ready"); delay(1000); } void loop() { // put your main code here, to run repeatedly: Serial.print("Alcohol: "); Serial.print(mq3.getAlcohol()); Serial.println(" mg/L"); delay(1000); }
605b65a45c60e34af9f9a80510dfdb56748c1ac5
87ed265b0aa7d3ac0fea44500c52f1e7d7d8254e
/gui/mainwindow.h
983628cdca56d0768ffefe47080bd8a1db01bc35
[]
no_license
surajroland/cam-calib
e17bdd52c4612631cf9144040a6689fdf606e412
167ce66d66ecc73c45211fcb4186796f490d472f
refs/heads/master
2021-01-10T03:10:00.308014
2016-03-23T04:01:58
2016-03-23T04:01:58
54,202,240
0
0
null
null
null
null
UTF-8
C++
false
false
870
h
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include "ui_mainwindow.h" #include <QFileDialog> #include <QPixmap> #include <QMessageBox> #include <QGraphicsPixmapItem> #include <QRadioButton> #include <QString> #include <processors/improc.h> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); signals: void sendImageToProcessor(QImage inputImage); void sendSelectedFilter(FeatureDetectors::filter h); private slots: void loadButtonClicked(); void applyButtonClicked(); void saveButtonClicked(); void displayProcessedImage(QImage ImageToDisplay); private: Ui::MainWindow *ui; QString fileName; QPixmap image; QImage *imageObject; QGraphicsScene *scene; }; #endif // MAINWINDOW_H
cba9acaab0101a43f373f91d3483a087ec3bf988
13b14c9c75143bf2eda87cb4a41006a52dd6f02b
/AOJ/2160/2160.cpp
7450444c1f0932b99d19e52665930fc64f826b41
[]
no_license
yutaka-watanobe/problem-solving
2c311ac856c79c20aef631938140118eb3bc3835
f0b92125494fbd3c8d203989ec9fef53f52ad4b4
refs/heads/master
2021-06-03T12:58:39.881107
2020-12-16T14:34:16
2020-12-16T14:34:16
94,963,754
0
1
null
null
null
null
UTF-8
C++
false
false
5,179
cpp
2160.cpp
#include<iostream> #include<cfloat> #include<cassert> #include<cmath> #include<vector> #include<queue> using namespace std; #define EPS (1e-10) #define equals(a, b) (fabs((a) - (b)) < EPS ) #define dle(a, b) (equals(a, b) || a < b ) static const double PI = acos(-1); class Point{ public: double x, y; Point ( double x = 0, double y = 0): x(x), y(y){} Point operator + ( Point p ){ return Point(x + p.x, y + p.y); } Point operator - ( Point p ){ return Point(x - p.x, y - p.y); } Point operator * ( double a ){ return Point(x*a, y*a); } Point operator / ( double a ){ return Point(x/a, y/a); } double abs() { return sqrt(norm());} double norm() { return x*x + y*y; } bool operator < ( const Point &p ) const { return x != p.x ? x < p.x : y < p.y; } bool operator == ( const Point &p ) const { return fabs(x-p.x) < EPS && fabs(y-p.y) < EPS; } }; typedef Point Vector; class Segment{ public: Point p1, p2; Segment(Point s = Point(), Point t = Point()): p1(s), p2(t){} }; typedef Segment Line; typedef vector<Point> Polygon; double norm( Vector a ){ return a.x*a.x + a.y*a.y; } double abs( Vector a ){ return sqrt(norm(a)); } Point polar( double a, double r ){ return Point(cos(r)*a, sin(r)*a);} double getDistance( Vector a, Vector b ){ return abs(a - b); } double dot( Vector a, Vector b ){ return a.x*b.x + a.y*b.y; } double cross( Vector a, Vector b ){ return a.x*b.y - a.y*b.x; } double arg(Vector p){ return atan2(p.y, p.x); } Point project( Segment s, Point p ){ Vector base = s.p2 - s.p1; double t = dot(p - s.p1, base)/norm(base); return s.p1 + base*t; } Point reflect( Segment s, Point p ){ return p + (project(s, p) - p)*2.0; } bool isOnSegment( Point a, Point b, Point c){ if ( a == c || b == c ) return true; return (abs(a-c) + abs(c-b) < abs(a-b) + EPS ); } bool isOrthogonal( Vector a, Vector b ){ return equals( dot(a, b), 0.0 ); } bool isOrthogonal( Point a1, Point a2, Point b1, Point b2 ){ return isOrthogonal( a1 - a2, b1 - b2 ); } bool isOrthogonal( Segment s1, Segment s2 ){ return equals( dot(s1.p2 - s1.p1, s2.p2 - s2.p1), 0.0 ); } bool isParallel( Vector a, Vector b ){ return equals( cross(a, b), 0.0 ); } bool isParallel( Point a1, Point a2, Point b1, Point b2){ return isParallel( a1 - a2, b1 - b2 ); } bool isParallel( Segment s1, Segment s2 ){ return equals( cross(s1.p2 - s1.p1, s2.p2 - s2.p1), 0.0 ); } static const int COUNTER_CLOCKWISE = 1; static const int CLOCKWISE = -1; static const int ONLINE_BACK = 2; static const int ONLINE_FRONT = -2; static const int ON_SEGMENT = 0; int ccw( Point p0, Point p1, Point p2 ){ Vector a = p1 - p0; Vector b = p2 - p0; if ( cross(a, b) > EPS ) return COUNTER_CLOCKWISE; if ( cross(a, b) < -EPS ) return CLOCKWISE; if ( dot(a, b) < -EPS ) return ONLINE_BACK; if ( norm(a) < norm(b) ) return ONLINE_FRONT; return ON_SEGMENT; } bool isIntersect(Point p1, Point p2, Point p3, Point p4){ return ( ccw(p1, p2, p3) * ccw(p1, p2, p4) <= 0 && ccw(p3, p4, p1) * ccw(p3, p4, p2) <= 0 ); } bool isIntersect(Segment s1, Segment s2){ return isIntersect(s1.p1, s1.p2, s2.p1, s2.p2); } Point getCrossPoint(Segment s1, Segment s2){ assert( isIntersect(s1, s2) ); Vector base = s2.p2 - s2.p1; double d1 = abs(cross(base, s1.p1 - s2.p1)); double d2 = abs(cross(base, s1.p2 - s2.p1)); double t = d1/(d1 + d2); return s1.p1 + (s1.p2 - s1.p1)*t; } Point getCrossPointLines( Line s1, Line s2){ Vector a = s1.p2 - s1.p1; Vector base = s2.p2 - s2.p1; return s1.p1 + a * cross(base, s2.p1 - s1.p1)/cross(base, a); } Polygon cutPolygon( Polygon P, Line l ){ Polygon u; for ( int i = 0; i < P.size(); i++ ){ Point a = P[i], b = P[(i+1)%P.size()]; if ( ccw(l.p1, l.p2, a) != CLOCKWISE ) u.push_back(a); if ( ccw(l.p1, l.p2, a) * ccw(l.p1, l.p2, b) == -1 ){ u.push_back(getCrossPointLines(Segment(a, b), l)); } } return u; } double getArea(Polygon p){ double sum = 0.0; for(int i = 0; i < p.size(); i++){ sum += cross(p[i], p[(i+1)%p.size()]); } return abs(sum/2); } Line getCutLine( Point p1, Point p2 ){ Vector v = p2 - p1; v = polar(abs(v), arg(v)+PI/2.0); double dx = (p2.x + p1.x)/2.0; double dy = (p2.y + p1.y)/2.0; return Line(Point(dx, dy), Point(v.x+dx, v.y+dy)); } #define MAX 10 vector<Polygon> getVoronoi( Polygon base, Point PV[MAX], int n){ vector<Polygon> V; for ( int i = 0; i < n; i++ ){ Polygon P = base; for ( int j = 0; j < n; j++ ){ if ( i == j ) continue; P = cutPolygon(P, getCutLine(PV[i], PV[j])); } V.push_back(P); } return V; } int N, M; int main(){ double x, y; while(1){ cin >> N >> M; if ( N == 0 && M == 0 ) break; Polygon base; Point PV[MAX]; for ( int i = 0; i < N; i++ ){ cin >> x >> y; base.push_back(Point(x, y)); } for ( int i = 0; i < M; i++ ){ cin >> x >> y; PV[i] = Point(x, y); } vector<Polygon> v = getVoronoi(base, PV, M); for ( int i = 0; i < v.size(); i++ ){ printf("%.8lf\n", getArea(v[i])); } } return 0; }
61eb6a77069d6cab810275bbe5efda768f34cf0f
05844fd418ce64c6fff6ce4df0a925656be0c5a6
/Finite.Difference.Time.Domain/Problems/Drude_1D_DNG_Transmission_Coefficient/Cpp/src/FDTD1DDNGMain.cpp
873e8c833fd14892712c6804235a3140f84469fb
[]
no_license
Motorfan/computational-electromagnetics
010127c166cfd72783015311415d5bc4807e6ead
2e8b9297b04d32f888b387b43d30da8194b32c47
refs/heads/master
2021-05-02T17:12:22.986497
2015-12-23T10:35:15
2015-12-23T10:35:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
900
cpp
FDTD1DDNGMain.cpp
#include <FDTD1DDNG.h> #include <iostream> using namespace std; int main() { CFDTD1DDNG TestSim(/*Size=*/4U*1024U, /*SourceLocation=*/10U, /*SnapshotInterval=*/16U, /*SourceChoice=*/1U); TestSim.StartTimer(); cout << "Memory required for simulation = " << TestSim.SimSize() << " bytes (" << (double)TestSim.SimSize()/1024UL << "kB/" << (double)TestSim.SimSize()/1024UL/1024UL << "MB)." << endl; cout << "HDD space required for data storage = " << TestSim.HDDSpace() << " bytes (" << (double)TestSim.HDDSpace()/1024UL << "kB/" << (double)TestSim.HDDSpace()/1024UL/1024UL << "MB)." << endl; TestSim.AllocateMemoryCPU(); TestSim.InitialiseCPU(); TestSim.DryRunCPU(); TestSim.InitialiseExHyCPU(); TestSim.RunSimulationCPU(true); TestSim.StopTimer(); cout << "Time taken = " << TestSim.GetElapsedTime() << " seconds." << endl; cout << "Exiting..." << endl; return 0; }
a6d6e0bc23297210d780085981b43a80e22a60f4
395f5870ba1a3d428a3294cf166d63891b3346e0
/robot2005/src/include/devices/tesla.h
c9d834dda2d7840f9b41f1605b273251802d49af
[]
no_license
BackupTheBerlios/robotm6
08a57f8cbb9100734c85ef0e444260f16e7efa6f
dc26ad2d1f3575c016c6c9104bd49ec6fb4d812d
refs/heads/master
2021-01-01T19:25:40.673078
2005-06-03T21:18:04
2005-06-03T21:18:04
39,962,329
0
0
null
null
null
null
UTF-8
C++
false
false
1,427
h
tesla.h
// gestion de l'electroaimant #pragma once #include "robotDevice.h" #define BigTesla BigTeslaCL::instance() #define Tesla BigTeslaCL::instance() enum TeslaMode { TESLA_MODE_0V = 0, TESLA_MODE_5V = 5, // envoie du petit sur l'electro aimant TESLA_MODE_12V = 12, TESLA_MODE_28V = 28}; class BigTeslaCL : public RobotDeviceCL { public: /** @brief Constructeur */ BigTeslaCL(); virtual ~BigTeslaCL(); /** @brief Retourne l'instance unique*/ static BigTeslaCL* instance(); virtual bool reset() { return true; } virtual bool exists() const { return false; } /** verification que le detecteur d'accrochage marche, a faire avait le debut du match */ virtual bool testDetector(bool& result) { return false;} /** ne demarrer le capteur qu'apres avoir demarre l'aimant */ virtual bool enableDetector(){ return false; } /** arreter le detecteur avant d'arreter l'aimant */ virtual bool disableDetector(){ return false; } /** arrete l'electro aimant */ virtual bool stopTesla() { return false; } /** passer la carte alime dans le mode correspondant avant de demarrer l'electroaimant! */ virtual bool startTesla(TeslaMode mode) { return false; } /** tache peridoci qui verifie si on a accroche */ virtual void periodicTask() {} private: static BigTeslaCL* tesla_; }; inline BigTeslaCL* BigTeslaCL::instance() { assert(tesla_); return tesla_; }
7ee5513a4afe977113fb9e07b86738bc382461ab
1075f2ad320c48a245c8f2b795621b773c3375db
/module_5/ex03/RobotomyRequestForm.cpp
36b678e30041c01a52194bbb4acbfc31e1eabbc0
[ "MIT" ]
permissive
cgriceld/42-cpp-piscine
59d1f197a620a12605e5326aeabdcccdeff2b343
2d07a886f0eca3216b50a17da807c721d6684e5d
refs/heads/main
2023-07-02T17:36:59.044027
2021-08-16T10:54:04
2021-08-16T10:54:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
888
cpp
RobotomyRequestForm.cpp
#include "RobotomyRequestForm.hpp" RobotomyRequestForm::RobotomyRequestForm() : Form("RobotomyRequestForm", 72, 45) { set_target("default"); }; RobotomyRequestForm::RobotomyRequestForm(std::string target) : Form("RobotomyRequestForm", 72, 45) { set_target(target); } RobotomyRequestForm::RobotomyRequestForm(const RobotomyRequestForm &copy) : Form(copy) { set_target(copy.get_target()); } RobotomyRequestForm::~RobotomyRequestForm() {}; RobotomyRequestForm &RobotomyRequestForm::operator = (const RobotomyRequestForm &copy) { if (this != &copy) { Form::operator = (copy); set_target(copy.get_target()); } return (*this); }; void RobotomyRequestForm::action(void) const { std::cout << "* drilling noises *\n"; std::rand() % 2 ? std::cout << get_target() << " has been robotomized successfully\n" : \ std::cout << "failed to robotomized " << get_target() << std::endl; }
80954a4b8af47ed3a1995c1571c778c82bc7406e
3135309ac61e6ea3e9e0bdb9e767df31d29f81a7
/src/filesystem/image.cpp
fe4a249708194871f339bcada45bc3d5cb3e1d1d
[]
no_license
lb2016github/water
e989325996aa6ea407f2058f18f24f3476877a88
d929d47d908ff3ed783483b092c4a643a4dd16d9
refs/heads/master
2020-04-26T15:49:55.620180
2020-01-07T13:50:32
2020-01-07T13:50:32
173,658,890
1
0
null
null
null
null
UTF-8
C++
false
false
1,752
cpp
image.cpp
#include "image.h" #define STB_IMAGE_IMPLEMENTATION #include "stb_image/stb_image.h" #include "common/log.h" #include "filesystem.h" namespace water { namespace filesystem { bool Image::do_load() { stbi_set_flip_vertically_on_load(true); auto fs = FileSystem::get_instance(); auto abs_path = fs->get_absolute_path(m_file_path); auto extension = fs->get_extension(m_file_path); void* data_ptr = nullptr; if (extension == ".hdr") { m_data_f = stbi_loadf(abs_path.c_str(), &m_width, &m_height, &m_channel_in_file, 4); m_data_format = ImageDataFormat::DATA_FLOAT; data_ptr = m_data_f; } else { m_data = stbi_load(abs_path.c_str(), &m_width, &m_height, &m_channel_in_file, 4); m_data_format = ImageDataFormat::DATA_CHAR; data_ptr = m_data; } if (data_ptr == nullptr) { log_error("[Image]Failed to load image: %s", m_file_path.c_str()); return false; } log_info("[Image]Success to load image: %s", m_file_path.c_str()); return true; } void Image::get_data(unsigned char ** data_ptr) { *data_ptr = m_data; } void Image::get_data(float ** data_ptr) { *data_ptr = m_data_f; } void Image::set_data(int width, int height, int channels, unsigned char ** data_ptr) { m_width = width; m_height = height; m_channel_in_file = channels; m_data = *data_ptr; m_loaded = true; m_data_format = ImageDataFormat::DATA_CHAR; } ImageDataFormat Image::get_data_format() { return m_data_format; } math3d::Vector2 Image::get_size() { return math3d::Vector2(m_width, m_height); } void Image::release() { if (m_data) { stbi_image_free(m_data); m_data = nullptr; } } Image::~Image() { release(); } } }
5c0e53678e56025f22cca5283074723b3840766e
9edbbde0fa31feb4c42a3c935301c5ed1211b1f2
/krab/Practice/ONP.cpp
296bc34964aac68345201cabcb110b33d76f6add
[]
no_license
Raman077/Codechef
4aa057ef9a86d73cbb1258463a630a9a16106575
3a4ea75eea424d79f91373d32ea7b062c3a09b84
refs/heads/master
2020-03-23T00:03:25.702902
2018-07-13T12:02:29
2018-07-13T12:02:29
140,841,324
0
0
null
null
null
null
UTF-8
C++
false
false
379
cpp
ONP.cpp
#include<bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { stack<char> s; string str; cin>>str; for (int i=0;i<str.size();i++) { if(str[i]=='-'||str[i]=='*'||str[i]=='/'||str[i]=='^'||str[i]=='+'||str[i]=='(') s.push(str[i]); else if(str[i]==')') { cout<<s.top(); if(!s.empty()) s.pop(); if(!s.empty()) s.pop(); } else cout<<str[i]; } cout<<endl; } }
c65d07b0949b5cfc4ceeb319a1bc45dd18da742d
73200cd0a8bd2b05ff330ddd2e84f55d91b0b156
/CS341Project2/main.cpp
a467c0b97f3021b35eb8230449ffe3203141651b
[]
no_license
DanUnix/Netflix-Movie-Reviews
6f2607bc649f7434f62cba6975950610d5b7d1c2
da90fa6c451ab6d536ade164ed23a512882d34df
refs/heads/master
2021-05-03T10:02:24.087252
2016-09-22T02:11:00
2016-09-22T02:11:00
67,321,616
0
0
null
null
null
null
UTF-8
C++
false
false
7,081
cpp
main.cpp
// // Netflix Movie Review Analysis // // <<Daniel Pulley>> // U. of Illinois, Chicago // CS341, Fall 2016 // HW #02 // // Preprocess Directives #include <iostream> #include <iterator> #include <iomanip> #include <fstream> #include <string> #include <sstream> #include <vector> #include <numeric> #include <algorithm> #include <map> #include "Movie.h" #include "Review.h" // using namespace std using std::string; using std::ifstream; using std::vector; using std::map; using std::pair; using std::stringstream; using std::getline; using std::stoi; using std::sort; using std::cout; using std::cin; using std::endl; using std::setw; using std::count; /* * inputMovies function * * Function takes movie vector and then inputs data from movies CSV file into the vector */ void inputMovies(vector<Movie>& myMovie) { // Open movie.csv file ifstream movie_file("movies.csv"); // String values to get Movie statistics string line, movie_id, movie_name, publish_year, avg, num_reviews; avg = "0.0"; num_reviews = "0"; // Check if movies file exist, if not exit program if (!movie_file.good()) { cout << "Cannot open movie file!" << endl; cout << "Exiting Program!" << endl; return; } // Skip header getline(movie_file, line); while (getline(movie_file, line)) { // Use stringstream to help parse CSV file stringstream ss(line); // parse line: getline(ss, movie_id, ','); getline(ss, movie_name, ','); getline(ss, publish_year, ','); getline(ss, avg, ','); getline(ss, num_reviews); Movie M(stoi(movie_id), movie_name, stoi(publish_year),stoi(avg),stoi(num_reviews)); // insert @ end myMovie.push_back(M); } } /* End of inputMovies File */ /* * inputReviews function * * Function takes review vector and then inputs data from reviews CSV file into the vector */ void inputReviews(vector<Review>& myReview) { // Open Review CSV file ifstream review_file("reviews.csv"); // String values to get Movie statistics string line, movie_id, user_id, movie_rating, review_date; // Check if movies file exist, if not exit program if (!review_file.good()) { cout << "Cannot open review file!" << endl; cout << "Exiting Program!" << endl; return; } // Skip header getline(review_file, line); while (getline(review_file, line)) { // Use stringstream to help parse CSV file stringstream ss(line); // parse line: getline(ss, movie_id, ','); getline(ss, user_id, ','); getline(ss, movie_rating, ','); getline(ss, review_date); Review R(stoi(movie_id), stoi(user_id), stoi(movie_rating), review_date); // insert @ end myReview.push_back(R); } } /* End of inputReviews Function */ /* * topTenMovies Function * Function displays the top-10 movies (based on average rating) * */ void topTenMovies(vector<Movie>& myMovie, vector<Review>& myReview) { cout << endl << ">> Top-10 Movies <<" << endl << endl; // Display top ten movies cout << "Rank" << "\t" << "ID" << "\t" << "Reviews" << "\t" << "Avg" << "\t" << "Name" << endl; for (Review& myR : myReview) { myMovie[myR.movieID - 1].avg += myR.rating; myMovie[myR.movieID - 1].nreviews++; myMovie[myR.movieID - 1].num_of_reviews[myR.rating - 1]++; } // Calculate the average rating for each movie listed for (Movie& myM : myMovie) { myM.avg = (myM.avg / myM.nreviews); } // Sort the average ratings sort(myMovie.begin(), myMovie.end(), [&](Movie a, Movie b) { return a.avg > b.avg; }); for (auto i = 0; i < 10; ++i) { cout << i+1 << ".\t" << myMovie[i].movieID << "\t" << myMovie[i].nreviews << "\t" << myMovie[i].avg << "\t'" << myMovie[i].movieName << "'" << endl; } } /* End of topTenMovies */ /* * topTenUsers Function * Display the top-10 users based on number of reviews submitted * */ void topTenUsers(vector<Movie>& myMovie, vector<Review>& myReview) { cout << ">> Top-10 Users <<" << endl << endl; // Implement a map to put userIDs with Number of reviews together map<int, int> myUserReview; for (Review& myR : myReview) myUserReview[myR.userID]++; // user vector combination vector<pair<int, int>> myNewUserInfo(myUserReview.begin(), myUserReview.end()); // Sort the new vector sort(myNewUserInfo.begin(), myNewUserInfo.end(), [&](pair<int, int> a, pair<int, int> b) { return (a.second > b.second); }); cout << "Rank" << "\t" << "ID" << "\t" << "Reviews" << endl; for (auto i = 0; i < 10; ++i) { cout << i + 1 << ".\t" << myNewUserInfo[i].first << "\t" << myNewUserInfo[i].second << endl; } } /* End of topTenUsers */ /* * movieInformation Function * Interactive loop that allows the user to search by movie id. * If movie is found, output data about the movie */ void movieInformation(vector<Movie>& myMovie, vector<Review>& myReview) { cout << ">> Movie Information <<" << endl << endl; // get movie ID from user int movie_id; // Sort movies by movieID sort(myMovie.begin(), myMovie.end(), [&](Movie a, Movie b) { return (a.movieID < b.movieID); }); // Prompt User to enter a movieID to be searched cout << "Please enter a movie ID " << "[1.." << myMovie.size() << "], 0 to stop: "; cin >> movie_id; cout << endl; // Create while loop to for interactive loop that will stop when user inputs 0 while (movie_id != 0) { // Condition - if user inputs a movie id greater than number of movies or less than 0 // Prompt them to try again if (movie_id > myMovie.size() || movie_id < 0) cout << "** Invalid movie id, please try again..." << endl; else { // Output the data of the movie depending on the inputted movie ID Movie selectedMovie = myMovie[movie_id - 1]; // Create new Movie object cout << "Movie:" << "\t\t'" << selectedMovie.movieName << "'" << endl; cout << "Year: " << "\t\t" << selectedMovie.publishYear << endl; cout << "Avg rating:" << "\t" << selectedMovie.avg << endl; cout << "Num reviews: " << "\t" << selectedMovie.nreviews << endl; } cout << endl; // Prompt User to enter a movieID to be searched again cout << "Please enter a movie ID" << "[1.." << myMovie.size() << "], 0 to stop: "; cin >> movie_id; } } /* End of movieInformation*/ /* * main Function * */ int main() { // Print Title of Program cout << "** Netflix Movie Review Analysis **" << endl << endl; // Create Movie vector to input movie data from file vector<Movie> movies; // Input movies into vector inputMovies(movies); // Create Review vector to input review data from file vector<Review> reviews; // Input reviews into vector inputReviews(reviews); // Display number of movies and number of reviews cout << ">> Reading movies... " << movies.size() << endl; cout << ">> Reading reviews... " << reviews.size() << endl; // Display top 10 movies based on average rating topTenMovies(movies,reviews); cout << endl; // Display top 10 users based on number of reviews topTenUsers(movies, reviews); cout << endl; // Movie Information movieInformation(movies, reviews); // Done cout << endl << endl << "** DONE! ** " << endl; system("PAUSE"); } /* End of Main Function */
bc24e80ff7d4cfa29738aaebc3c64b4140520949
e9f3aed4d520b7a2634ae6bd9467a5504dbbdfa2
/obj/ObjectHeaderUnknownCTypeGenerator_def.hpp
62ec27b3599ccc95ee96976ffb3fea310ee43755
[]
no_license
tfoerch/LMP
4b7e50f72796e96f8c40691c3cfab1c5c64f2ca9
b82e2665778e6d984f166ba2242add0f78cf4857
refs/heads/master
2021-01-01T03:48:57.646358
2018-12-18T22:01:17
2018-12-18T22:01:17
58,702,868
0
0
null
null
null
null
UTF-8
C++
false
false
2,298
hpp
ObjectHeaderUnknownCTypeGenerator_def.hpp
#ifndef LMP_OBJ_OBJECTHEADER_UNKNOWN_CTYPE_GENERATOR_DEF_HPP_ #define LMP_OBJ_OBJECTHEADER_UNKNOWN_CTYPE_GENERATOR_DEF_HPP_ /* * ObjectHeaderUnknownCTypeGenerator_def.hpp * * Created on: 28.02.2015 * Author: tom */ #include "obj/ObjectHeaderUnknownCTypeAstAdapted.hpp" #include "obj/ObjectHeaderUnknownCTypeGenerator.hpp" #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/qi_binary.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_fusion.hpp> #include <boost/spirit/include/phoenix_stl.hpp> #include <boost/phoenix/object/static_cast.hpp> #include <boost/fusion/adapted/struct/adapt_struct.hpp> #include <boost/fusion/include/adapt_struct.hpp> #include <type_traits> namespace lmp { namespace obj { template <typename ObjClassTraits> lmp::DWORD getLength( const ast::ObjectHeaderUnknownCType<ObjClassTraits>& objClassUnknownCTypeData) { return ( c_objHeaderLength + objClassUnknownCTypeData.m_data.size() ); } namespace generator { namespace fusion = boost::fusion; namespace phoenix = boost::phoenix; namespace qi = boost::spirit::qi; template <typename OutputIterator, ObjectClass objClass> object_header_unknown_ctype_grammar<OutputIterator, objClass>::object_header_unknown_ctype_grammar() : object_header_unknown_ctype_grammar::base_type(object_header_unknown_ctype_rule, "object_header_unknown_ctype") { using qi::byte_; using qi::big_word; using qi::big_dword; using qi::eps; using phoenix::at_c; using namespace qi::labels; object_header_unknown_ctype_rule = ( eps(at_c<1>(_val)) << byte_ [ _1 = ( at_c<0>(_val) | lmp::obj::c_negotiableMask ) ] | byte_ [ _1 = at_c<0>(_val) ] ) // class type << byte_ [ _1 = static_cast<typename std::underlying_type<ObjectClass>::type>(objClass) ] // object class << big_word [ _1 = _r1 ] // length ; object_header_unknown_ctype_rule.name("object_header_unknown_ctype"); } } } // namespace obj } // namespace lmp #endif /* LMP_OBJ_OBJECTHEADER_UNKNOWN_CTYPE_GENERATOR_DEF_HPP_ */
53d852eaac94e6d64eaf37a9f0cb55e1c2ef512a
607f1925d45868f8defff9c38131e5093892bf0e
/trackingstrategy.h
8e8713344569947b36fb7749fbb68882b11c5878
[]
no_license
nagyistoce/vision-global-futbol-robots
be7fd13cff61c69e2fcb9d266ed6db707dfc1db7
84f5dcb9ae1d64675ad727676c93507199819c2c
refs/heads/master
2021-01-22T09:09:15.992852
2013-11-22T19:18:55
2013-11-22T19:18:55
32,746,937
1
0
null
null
null
null
UTF-8
C++
false
false
2,075
h
trackingstrategy.h
//======================================================================== // This software is free: you can redistribute it and/or modify // it under the terms of the GNU General Public License Version 3, // as published by the Free Software Foundation. // // This software is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // Version 3 in the file COPYING that came with this distribution. // If not, see <http://www.gnu.org/licenses/>. //======================================================================== /*! \file trackingstrategy.h \brief C++ Interface: TrackingStrategy \author Guillermo Eduardo Torres, (C) 2012 */ //======================================================================== #ifndef TRACKINGSTRATEGY_H_ #define TRACKINGSTRATEGY_H_ #include <QThread> #include <QMutex> #include <QWaitCondition> #include <cv.h> #include "datastruct.h" #include "visionstack.h" #include "framedata.h" #include "plugin_colorconversions.h" #include "plugin_colorsegmentation.h" #include "plugin_morphology.h" #include "plugin_detect_balls.h" #include "plugin_find_blobs.h" #include "plugin_find_secondaries_blobs.h" #include "plugin_networking.h" using namespace std; using namespace cv; class TrackingStrategy : public QThread { Q_OBJECT protected: IplImage *frame; CvRect roi; VisionStack s; FrameBuffer * rb; QMutex stack_mutex; //this mutex protects multi-threaded operations on the stack QMutex stoppedMutex; volatile bool stopped; protected: virtual void run()=0; public: TrackingStrategy(); virtual ~TrackingStrategy(); void setFrameBuffer(FrameBuffer * _rb); FrameBuffer * getFrameBuffer() const; virtual void process(IplImage *frame)=0; //virtual void postProcess(IplImage *frame)=0; virtual void stopTrackingStrategy()=0; }; #endif /* TRACKINGSTRATEGY_H_ */
850d0621021914c3721d8b64e5f8523480c2d63d
b6498036ac7955a26892584a7c9562e2029fd336
/src/main.cpp
3829875129c66a0c141ea1b93d987ac828b06b19
[ "MIT" ]
permissive
Projet-ReseauDeNeurones-M1CHPS/MNISTNN2
1d73ed192925456edda0b9c67e43e3b07f7f30ae
bf7e0f8a114d2ca492d1c2c6c76fe348857ab4ff
refs/heads/master
2020-03-16T09:40:52.124886
2018-05-08T20:29:36
2018-05-08T20:29:36
132,620,565
0
0
null
null
null
null
UTF-8
C++
false
false
11,885
cpp
main.cpp
/// \file #include <iostream> #include <stdio.h> #include <fstream> #include <Eigen/Dense> #include "Perceptron.hpp" #include <cstdlib> #include <tbb/tbb.h> #include <tbb/task_scheduler_init.h> #define BLACK '#' #define WHITE '_' /// \brief Permet de savoir si dans quelle mode lire les metadonnees d'un fichier IDX (low-endien ou big-endian) /// \param f Pointeur sur la chaine de caractere contenant le nom du fichier IDX /// \return le mode selon lequel lire le fichier IDX (0 ou 1) /// \warning teste uniquement sur des processeurs Intel!!! int idxEndianness(char* f) { int n = 0; char* r = nullptr; r = (char*)&n; std::ifstream in(f, std::ifstream::in); //On lit les 4 premiers octets in.read(r, 4); if(n != 2049 && n!= 2051) { return 0; } else { return 1; } } /// \brief Lire les metadonnees d'un fichier IDX (fonction recursive) /// \param in Flux du fichier IDX a lire /// \param mode Mode Mode pour lire le fichier selon l'endianness /// \param n Reference vers la variable dans laquelle mettre la prochaine metadonnee a lire /// \param args References vers les prochaines variable dans laquelle mettre les metadonnees suivantes a lire /// \warning teste uniquement sur des processeurs Intel!!! template<typename... Args> void idxMeta(std::ifstream& in, int mode, std::size_t& n, Args& ...args) { char* r = nullptr; r = (char*)&n; //On lit les 4 premiers octets in.read(r, 4); //Sur Intel, on les inverses if(mode==0) { char tmp; tmp = r[0]; r[0] = r[3]; r[3] = tmp; tmp = r[1]; r[1] = r[2]; r[2] = tmp; } idxMeta(in, mode, args...); } /// \brief Dernier appel recursif de idxMeta /// \warning teste uniquement sur des processeurs Intel!!! template<> void idxMeta(std::ifstream& in, int mode, std::size_t& n) { char* r = nullptr; r = (char*)&n; //On lit les 4 premiers octets in.read(r, 4); //Sur Intel, on les inverses if(mode == 0) { char tmp; tmp = r[0]; r[0] = r[3]; r[3] = tmp; tmp = r[1]; r[1] = r[2]; r[2] = tmp; } } /// \brief On charge dans une entree-sortie de reseau le prochain element qui se trouve dans un fichier IDX /// \param fin Flux du fichier IDX a lire /// \param vout Reference vers l'entree-sortie de reseau dans laquelle on charge le prochain element du fichier /// \param size Taille du prochain element a lire /// \return Rien /// \tparam t Type de l'entree-sortie de reseau dans laquelle on charge le prochain element du fichier IDX /// \tparam SIZE Taille de l'entree-sortie de reseau dans laquelle on charge le prochain element du fichier IDX /// \warning teste uniquement sur des processeurs Intel!!! template<typename t, int SIZE> void nextIdx(std::ifstream& fin, neuralnetwork::InOut<t, SIZE>& vout, std::size_t size) { for (unsigned int i = 0; i < size; ++i) { unsigned char r; fin.read((char*)&r, 1); vout(i) = r; } } /// \brief Conversion d'un label entier en label vecteur pour la classification de caractere numerique /// \param in Label entier /// \param out Label vecteur en sortie /// \return Rien /// \tparam t Type d'entree du reseau (a priori un double) /// \tparam INPUT_SIZE Taille d'entree du reseau template<typename t, int INPUT_SIZE> void labelToVector(int in, neuralnetwork::InOut<t, INPUT_SIZE>& out) { out << 0, 0, 0, 0, 0, 0, 0, 0, 0, 0; out(in) = 1; } /// \brief Affiche une entree-sortie de reseau contenant une images de MNIST (principalement utile au debugage) /// \param rows Nombre de lignes de l'image (a priori 28) /// \param cols Nombre de colonnes de l'image (a priori 28) /// \param v Entree-sortie de reseau a afficher /// \return Rien /// \tparam t Type de l'entree-sortie de reseau a afficher /// \tparam SIZE Taille de l'entree-sortie a afficher template<typename t, int SIZE> void printInOut(std::size_t rows, std::size_t cols, neuralnetwork::InOut<t, SIZE> v) { for(int i = 0; i < rows; ++i) { for(int j = 0; j < cols; ++j) { if (v(i*rows + j) != 0) { std::cout << BLACK; } else { std::cout << WHITE; } } std::cout << std::endl; } } /// \brief Entrainement du reseau pour la classification de caracteres /// \param pathImages Pointeur vers la chaine de caractere contenant le nom de fichier des images d'entrainement /// \param pathLabels Pointeur vers la chaine de caractere contenant le nom de fichier des labels d'entrainement /// \param net Reseau a entrainer /// \param step Pas d'apprentissage /// \param nbIter Nombre d'iterations a effectuer sur l'ensemble des images d'entrainement /// \param nbImages Nombre d'images a charger en memoire simultanement /// \return -1 en cas de probleme d'allocation memoires (trop d'images a charger simultanement) /// \tparam DEPTH Profondeur du reseau de neurones template<std::size_t DEPTH> int train(char* pathImages, char* pathLabels, neuralnetwork::Perceptron<DEPTH>& net, double step, std::size_t nbIter, std::size_t nbImages) { std::size_t magicImTrain = 0, magicLabTrain = 0; std::size_t nbImagesTrain = 0; std::size_t rows = 0; std::size_t cols = 0; neuralnetwork::InOut<double, 784>* inIm = NULL; neuralnetwork::InOut<double, 1>* inLab = NULL; neuralnetwork::InOut<double, 10>* inLabVect = NULL; int mode = idxEndianness(pathLabels); //Si on a 0 en nombre d'exemples a charger en memoire on chargera tous les exemples de la base de donnees if(nbImages == 0) { std::ifstream flabels(pathLabels, std::ifstream::in); idxMeta(flabels, mode, magicLabTrain, nbImagesTrain); nbImages = nbImagesTrain; flabels.close(); } inIm = new neuralnetwork::InOut<double, 784> [nbImages]; inLab = new neuralnetwork::InOut<double, 1> [nbImages]; inLabVect = new neuralnetwork::InOut<double, 10> [nbImages]; if(inIm == NULL || inLab == NULL || inLabVect == NULL) { return -1; } //On entraine autant de fois que voulu for(unsigned int iter = 0; iter < nbIter; ++iter) { std::cout << "Iteration [" << iter + 1 << "/" << nbIter << "]" << std::endl; std::ifstream fimages(pathImages, std::ifstream::in); std::ifstream flabels(pathLabels, std::ifstream::in); idxMeta(flabels, mode, magicLabTrain, nbImagesTrain); idxMeta(fimages, mode, magicImTrain, nbImagesTrain, rows, cols); //Tant que l'on a pas fait tous les exemples for(unsigned int n = 0; n < nbImagesTrain; n+=nbImages) { std::cout << "\tLot [" << n + 1 << " - " << n + nbImages << "/" << nbImagesTrain << "]" << std::endl; //On charge les exemples et les labels for(unsigned int i = 0; i < nbImages; ++i) { //On charge l'exemple et le label nextIdx(fimages, inIm[i], 784); nextIdx(flabels, inLab[i], 1); int valLab = inLab[i](0); //Conversion du label en vecteur labelToVector(valLab, inLabVect[i]); } //std::cout << "Iteration " << iter + 1 << ", entrainement avec les image de " << n << " a " << n+nbImages << "..." << std::endl; //On entraine sur le lot charge net.parallel_backpropagation(inIm, inLabVect, nbImages, step); //net.backpropagation(inIm, inLabVect, nbImages, step); } fimages.close(); flabels.close(); } delete [] inIm; delete [] inLab; delete [] inLabVect; return 0; } /// \brief Test du reseau pour la classification de caracteres /// \param pathImages Pointeur vers la chaine de caractere contenant le nom de fichier des images de test /// \param pathLabels Pointeur vers la chaine de caractere contenant le nom de fichier des labels de test /// \param net Reseau a tester /// \return Pourcentage de reussite /// \tparam DEPTH Profondeur du reseau de neurones template<std::size_t DEPTH> double test(char* pathImages, char* pathLabels, neuralnetwork::Perceptron<DEPTH>& net) { std::size_t magicImTest = 0, magicLabTest = 0; std::size_t nbImagesTest = 0; std::size_t rows = 0; std::size_t cols = 0; neuralnetwork::InOut<double, 784> inImTest; neuralnetwork::InOut<double, 1> inLabTest; int mode = idxEndianness(pathLabels); std::ifstream fimagesTest(pathImages, std::ifstream::in); std::ifstream flabelsTest(pathLabels, std::ifstream::in); idxMeta(flabelsTest, mode, magicLabTest, nbImagesTest); idxMeta(fimagesTest, mode, magicImTest, nbImagesTest, rows, cols); int count = 0; //Pour tous les exemples de tests for(int i = 0; i < 10000; ++i) { neuralnetwork::InOut<double, 10> out; neuralnetwork::InOut<double, 10> realOut; //On charge les exemples avec leurs labels nextIdx(fimagesTest, inImTest, 784); nextIdx(flabelsTest, inLabTest, 1); //On convertit le label en vecteur labelToVector(inLabTest(0), realOut); //On fait evaluer l'exemple par le reseau de neurones //net.feedForward(inImTest, out, false, false); net.parallel_feedForward(inImTest, out); //Pour chaque element i du vecteur de sortie, s'il est superieur a 0.5, on estime que le reseau a trouve que l'exemple est i - 1 //Par exemple si le reseau renvoi [0.12, 0.23, 0.87, 0.34, 0.45, 0.47, 0.37, 0.28, 0.19 , 0.09] alors on interprete que le solution trouvee est [0, 0, 1, 0, 0, 0, 0, 0, 0, 0] et donc que le nombre trouve est 2 for(int j = 0; j < 10; ++j) { if(out(j) > 0.5) { out(j) = 1.0; } else { out(j) = 0.0; } } //Si la bonne solution est trouvee, alors on incremente le coompteur if(out == realOut) { ++count; } } //On retourne le pourcentage de reussite return count*100.0/10000.0; } /// \brief Itere un certain nombre de fois sur la base d'entrainement et apres chaque iteration test le reseau sur la base de test, le taux de reussite de chaque test est stocke dans un fichier /// \param pathImTrain Pointeur vers la chaine de caractere contenant le nom de fichier des images d'entrainement /// \param pathLabTrain Pointeur vers la chaine de caractere contenant le nom de fichier des labels d'entrainement /// \param pathImTest Pointeur vers la chaine de caractere contenant le nom de fichier des images de test /// \param pathLabTest Pointeur vers la chaine de caractere contenant le nom de fichier des labels de test /// \param plot Pointeur vers la chaine de caractere contenant le nom de fichier dans lequel stocker les resultats /// \param net Reseau a entrainer /// \param step Pas d'apprentissage /// \param nbIter Nombre d'iterations a effectuer sur l'ensemble des images d'entrainement /// \param nbImages Nombre d'images a charger en memoire simultanement /// \return Rien /// \tparam DEPTH Profondeur du reseau de neurones template<std::size_t DEPTH> void bench(char* pathImTrain, char* pathLabTrain, char* pathImTest, char* pathLabTest, char* plot, neuralnetwork::Perceptron<DEPTH>& net, double step, std::size_t nbIter, std::size_t nbImages) { std::ofstream fplot(plot, std::ofstream::out); for(int i = 0; i < nbIter; ++i) { train(pathImTrain, pathLabTrain, net, step, 1, nbImages); double resTest = test(pathImTest, pathLabTest, net); fplot << resTest << std::endl; } } int main() { char pathImTrain [] = "../datas/imTrain"; char pathLabTrain [] = "../datas/labTrain"; char pathImTest [] = "../datas/imTest"; char pathLabTest [] = "../datas/labTest"; neuralnetwork::Perceptron<3> net( -0.0001, 0.0001, 784, 200, neuralnetwork::activation::SIGMOID, neuralnetwork::activation::D_SIGMOID, 200, neuralnetwork::activation::SIGMOID, neuralnetwork::activation::D_SIGMOID, 10, neuralnetwork::activation::SIGMOID, neuralnetwork::activation::D_SIGMOID ); net.initGraph(0.1, 4); train(pathImTrain, pathLabTrain, net, 0.1, 35, 1000); double res = test(pathImTest, pathLabTest, net); std::cout << "Reussite de " << res << " pourcents apres entrainement" << std::endl; return 0; }
e7e6fe60f2fd1e8e5847edf1bd63f9471a5a9bec
373973a49d5a44317f4ae270d0528e69086f6fa4
/USACO/Section 1.3/Prime Cryptarithm/miguelsandim.cpp
4a9e9c34988c47c26f2a954b649eaa6552eae96a
[]
no_license
ferrolho/feup-contests
c72cfaa44eae4a4d897b38bd9e8b7a27b753c6bb
d515e85421bed05af343fda528a076ce62283268
refs/heads/master
2021-01-10T21:03:53.996687
2017-03-29T17:34:35
2017-03-29T17:34:35
13,063,931
9
3
null
null
null
null
UTF-8
C++
false
false
3,298
cpp
miguelsandim.cpp
/* ID: migueel1 PROG: crypt1 LANG: C++ */ #include <iostream> #include <fstream> #include <vector> #include <string> using namespace std; int numbers[9]; int subset_number; unsigned int solution_number; bool existsInSubSet(int num) { for (int i=0; i < subset_number; i++) if (numbers[i] == num) return true; return false; } bool validSolution(int top[], int bottom[]) { //printf("Vou testar com os valores\nTop: %d,%d,%d;\nBot: %d,%d\n\n",top[2],top[1],top[0], //bottom[1],bottom[0]); getchar(); int partial1[3], partial2[3], sum, carry=0; for (unsigned int i=0; i < 2; i++) { for (unsigned int j=0; j < 3; j++) { int mul = bottom[i]*top[j]; //printf("Mul deu %d\n",mul); getchar(); if (carry) {mul+= carry; carry = 0;} if (mul >= 10) carry = mul/10; //printf("Mul com carry %d\n",mul); getchar(); mul = mul%10; //printf("Mul final %d\n",mul); getchar(); if (!existsInSubSet(mul)) return false; //else printf("passou\n"); if (i==0) partial1[j] = mul; else partial2[j] = mul; if (j == 2 && carry) // se sobrou carry, não pode return false; //else printf("passou\n"); } } //printf("Agora as somas\npartial1: %d,%d,%d;\npartial2: %d,%d,%d\n\n",partial1[2],partial1[1],partial1[0], //partial2[2],partial2[1],partial2[0]); getchar(); sum = partial1[1] + partial2[0]; //printf("Soma deu %d\n",sum); getchar(); if (sum >= 10) carry = 1; sum = sum%10; //printf("Soma final deu %d\n",sum); getchar(); if (!existsInSubSet(sum)) return false; //else printf("passou\n"); sum = partial1[2] + partial2[1]; //printf("Soma deu %d\n",sum); getchar(); if (carry) {sum+= carry; carry=0;} //printf("Soma com carry %d\n",sum); getchar(); if (sum >= 10) carry = sum/10; sum = sum%10; //printf("Soma final deu %d\n",sum); getchar(); if (!existsInSubSet(sum)) return false; //else printf("passou\n"); sum = partial2[2]; //printf("Soma deu %d\n",sum); getchar(); if (carry) {sum+= carry; carry=0;} //printf("Soma com carry %d\n",sum); getchar(); if (sum >= 10) carry = sum/10; sum = sum%10; //printf("Soma final deu %d\n",sum); getchar(); if (!existsInSubSet(sum)) return false; //else printf("passou\n"); return carry==0; } int main() { // receive input ifstream input("crypt1.in"); input >> subset_number; for(int i=0; i < subset_number; i++) input >> numbers[i]; input.close(); // VARIABLE DECLARATION int top[3], bottom[2], solution_number=0; for(int i=0; i < subset_number; i++) for(int j=0; j < subset_number; j++) for(int k=0; k < subset_number; k++) for(int l=0; l < subset_number; l++) for(int m=0; m < subset_number; m++) { top[0] = numbers[i]; top[1] = numbers[j]; top[2] = numbers[k]; bottom[0] = numbers[l]; bottom[1] = numbers[m]; //top[0] = 9; top[1] = 7; top[2] = 2; //bottom[0] = 8; bottom[1] = 7; if (validSolution(top,bottom)) solution_number++; } //SAVE OUTPUT ofstream output("crypt1.out"); output << solution_number << endl; output.close(); return 0; }
8d55649a884aac63627855e9ccbe8581cddcc25f
2aec811bf06b8e8356822436829eeb7002b13576
/src/draw/tile.cpp
795771ed142e2949387932ec4e5953642f33ac92
[]
no_license
YueZhuAnn/cc3k_3d
c4825d028e6f567f2f90eacf275df12eec377ed9
1eb023164ef65ab9f249f3165640e2eae3f663e7
refs/heads/master
2022-01-20T02:24:09.348428
2019-07-20T14:59:51
2019-07-20T14:59:51
197,945,106
0
0
null
null
null
null
UTF-8
C++
false
false
1,677
cpp
tile.cpp
#include "draw/tile.hpp" using namespace std; using namespace glm; Tile::Tile(){ m_mode = GL_TRIANGLES; m_size = 2*3; m_type = GL_UNSIGNED_INT; } Tile::~Tile(){} void Tile::registerUniform(){ setUniformPos("P"); setUniformPos("V"); setUniformPos("M"); setUniformPos("colour"); } void Tile::uploadModel(){ float verts[4*3]; unsigned index = 0; // upload the vertices for(unsigned x = 0; x < 2; x++){ for(unsigned z = 0; z < 2; z++){ verts[index*3] = x*1-0.5f; verts[index*3+1] = 0.0f; verts[index*3+2] = z*1-0.5f; index++; } } // upload the indices unsigned indices[] = { 0, 1, 2, 1, 2, 3 }; // Create the vertex array to record buffer assignments. glGenVertexArrays( 1, &m_vao ); glBindVertexArray( m_vao ); // Create the cube vertex buffer glGenBuffers( 1, &m_vbo ); glBindBuffer( GL_ARRAY_BUFFER, m_vbo ); glBufferData( GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW ); // Create the cube elements buffer glGenBuffers( 1, &m_ebo ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_ebo ); glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW ); // Specify the means of extracting the position values properly. GLint posAttrib = m_shader.getAttribLocation( "position" ); glEnableVertexAttribArray( posAttrib ); glVertexAttribPointer( posAttrib, 3, GL_FLOAT, GL_FALSE, 0, nullptr ); // Reset state to prevent rogue code from messing with *my* // stuff! glBindVertexArray( 0 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); }
bbd6d577f183239885dfe1a13518abde37cdcb4c
dde1120eef1431f410b24a162ce79ccea6f5b031
/SpaceX/KramerProjectionSolver.h
ef4f38d9760111b93c86ebd19e8a5b8b77e1262a
[]
no_license
fascinatingwind/Projection
f14dce919493351296fe4acd99ee01239935aefc
b58a805408363ac59981ed037cf2ec88d5f65e90
refs/heads/main
2023-09-01T23:55:14.268735
2021-11-07T07:16:07
2021-11-07T07:16:07
423,066,480
1
0
null
null
null
null
UTF-8
C++
false
false
832
h
KramerProjectionSolver.h
#pragma once #ifndef KRAMER_PROJECTION_SOLVER_H #define KRAMER_PROJECTION_SOLVER_H #include "dllexport.h" #include "FPoint3D.h" #include "FLine3D.h" #include "FMatrix3x3.h" namespace SpaceX { // Store method for find projection point class SpaceX_ExportDll KramerProjectionSolver { public: KramerProjectionSolver() = delete; ~KramerProjectionSolver() = delete; // Find projection point using Kramer's method for solve SLE static FPoint3D CalculateProjection(const FLine3D& line, const FPoint3D& point); private: // Return matrix representation of line in 3d space static FMatrix3x3 GetMatrixRepresentation(const FLine3D& line); // Return two non zero points from matrix in 3d space static std::array<FPoint3D, 2> Get2NonZeroRows(const FMatrix3x3& matrix); }; } #endif // !KRAMER_PROJECTION_SOLVER_H
7eede3753d99548f7a54a1c7eca8ea18db755bfe
e740520065b12eb15e0e59b16362679464b69c42
/LintCode/LintCode/Permutations.cpp
04546c66dd18abd37243831538400333a457c443
[]
no_license
watsonyanghx/algorithm
ad8fa73ec1672129879bd761e8990a20919106bf
afea8ea4f9f22ac049e9229e64de4905f6939668
refs/heads/master
2021-06-18T08:31:54.164042
2017-03-13T10:57:41
2017-03-13T10:57:41
53,142,005
0
0
null
null
null
null
UTF-8
C++
false
false
2,728
cpp
Permutations.cpp
#include <stdio.h> #include <stdlib.h> #include <vector> #include <queue> #include <unordered_set> using namespace std; //without using recursion // class Solution { public: /** * @param nums: A list of integers. * @return: A list of permutations. * @date: 2016-10-2 */ vector<vector<int> > permute(vector<int> nums) { // write your code here vector<vector<int> > rs; if (nums.size() < 1) { rs.push_back(vector<int>()); return rs; } else if (nums.size() < 2) { rs.push_back(nums); return rs; } rs.push_back(vector<int>(1, nums[0])); for (int i = 1; i < nums.size(); i++) { int n = rs.size(); for (int j = 0; j < n; j++) { for (int k = 0; k < rs[j].size(); k++) { vector<int> per = rs[j]; per.insert(per.begin() + k, nums[i]); rs.push_back(per); } rs[j].push_back(nums[i]); } } return rs; } }; //recursion class Solution { public: /** * @param nums: A list of integers. * @return: A list of permutations. * @date: 2016-10-2 */ vector<vector<int> > permute(vector<int> nums) { // write your code here vector<vector<int> > rs; if (nums.size() < 1) { rs.push_back(vector<int>()); return rs; } else if (nums.size() < 2) { rs.push_back(nums); return rs; } vector<int> curr; dfs(nums, rs, curr, 0, nums.size() - 1); return rs; } void dfs(vector<int> nums, vector<vector<int> > &rs, vector<int> &curr, int start, int end) { int n = end - start + 1; if (n == 2) { curr.push_back(nums[start]); curr.push_back(nums[end]); rs.push_back(curr); curr.pop_back(); curr.pop_back(); curr.push_back(nums[end]); curr.push_back(nums[start]); rs.push_back(curr); curr.pop_back(); curr.pop_back(); return; } else { for (int i = start; i < end + 1; i++) { vector<int> new_nums = swap_op(nums, start, i); curr.push_back(new_nums[start]); dfs(new_nums, rs, curr, start + 1, end); curr.pop_back(); } } } vector<int> swap_op(vector<int> nums, int start, int i) { vector<int> new_nums(nums.begin(), nums.end()); new_nums[start] = nums[i]; new_nums[i] = nums[start]; return new_nums; } };
67d40427b2f01764ea1694e23c64bd994e6f4c70
dd79e25d75ddfc2ee4909ea270297dfa29ac90b3
/1073FRC11/SmartJoystick.cpp
e3fc8e649ae19e33eb1687befc64f7b4cf6aea7e
[]
no_license
cha63506/robot11-googlecode-hg-archive
9196fcf7e1edbd6ab319618fe385dcc698aea077
25c147e308df2c63f3f56744d2e9c869327fa744
refs/heads/master
2018-05-29T20:40:03.206376
2016-01-18T23:43:33
2016-01-18T23:43:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,607
cpp
SmartJoystick.cpp
////////////////////////////////////////////////////////// // Filename: SmartJoystick.cpp // Author: Ken Cowan // Date: Feb 6, 2011 // // This file contains ... // ////////////////////////////////////////////////////////// #include "SmartJoystick.h" bool SmartJoystick::ButtonClickDown(UINT32 button) { StateMap::iterator it = buttonStates.find(button); bool current_state = GetRawButton(button); // If this is the first time the button is being queried, add it // to our state map using the current state if (it == buttonStates.end()) { buttonStates[button] = current_state; return false; } // Get the previous state of the button bool old_state = (*it).second; // Update the state it->second = current_state; // If the button was up, but now is down, we have a ClickDown event if ((old_state == false) && (current_state == true)) return true; return false; } bool SmartJoystick::ButtonClickUp(UINT32 button) { StateMap::iterator it = buttonStates.find(button); bool current_state = GetRawButton(button); // If this is the first time the button is being queried, add it // to our state map using the current state if (it == buttonStates.end()) { buttonStates[button] = current_state; return false; } // Get the previous state of the button bool old_state = (*it).second; // Update the state it->second = current_state; // If the button was down, but now is up, we have a ClickUp event if ((old_state == true) && (current_state == false)) return true; return false; }
ba2a1f193209a90adf3c64bc35e13afdf2e211a1
ba876bce84da34997c8dc6a8fcb8f173eec24e14
/src/preprocess/gltf.inl
b5d1e4d87490193d66fa9e82ebc7a77ba1b84de8
[ "MIT" ]
permissive
shacklettbp/bps3D
4fa7294c57aa7e5a47903d841de400dc72884b07
be0a725f74df8512204628bde8fcf5ba510f8643
refs/heads/master
2023-06-22T09:46:35.948654
2021-06-28T22:15:18
2021-06-28T22:15:18
338,671,043
13
1
null
null
null
null
UTF-8
C++
false
false
23,067
inl
gltf.inl
#include "gltf.hpp" #include "import.hpp" #include <bps3D_core/utils.hpp> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/transform.hpp> #include <fstream> #include <iostream> #include <type_traits> #include <unordered_set> using namespace std; namespace bps3D { namespace SceneImport { struct GLBHeader { uint32_t magic; uint32_t version; uint32_t length; }; struct ChunkHeader { uint32_t chunkLength; uint32_t chunkType; }; GLTFScene gltfLoad(filesystem::path gltf_path) noexcept { GLTFScene scene; scene.sceneName = gltf_path.stem(); scene.sceneDirectory = gltf_path.parent_path(); auto suffix = gltf_path.extension(); bool binary = suffix == ".glb"; if (binary) { ifstream binary_file(string(gltf_path), ios::in | ios::binary); GLBHeader glb_header; binary_file.read(reinterpret_cast<char *>(&glb_header), sizeof(GLBHeader)); uint32_t total_length = glb_header.length; ChunkHeader json_header; binary_file.read(reinterpret_cast<char *>(&json_header), sizeof(ChunkHeader)); vector<uint8_t> json_buffer(json_header.chunkLength + simdjson::SIMDJSON_PADDING); binary_file.read(reinterpret_cast<char *>(json_buffer.data()), json_header.chunkLength); try { scene.root = scene.jsonParser.parse( json_buffer.data(), json_header.chunkLength, false); } catch (const simdjson::simdjson_error &e) { cerr << "GLTF loading '" << gltf_path << "' failed: " << e.what() << endl; abort(); } if (json_header.chunkLength < total_length) { ChunkHeader bin_header; binary_file.read(reinterpret_cast<char *>(&bin_header), sizeof(ChunkHeader)); assert(bin_header.chunkType == 0x004E4942); scene.internalData.resize(bin_header.chunkLength); binary_file.read( reinterpret_cast<char *>(scene.internalData.data()), bin_header.chunkLength); } } else { scene.root = scene.jsonParser.load(string(gltf_path)); } try { for (const auto &buffer : scene.root["buffers"]) { string_view uri {}; const uint8_t *data_ptr = nullptr; auto uri_elem = buffer.at_key("uri"); if (uri_elem.error() != simdjson::NO_SUCH_FIELD) { uri = uri_elem.get_string(); } else { data_ptr = scene.internalData.data(); } scene.buffers.push_back(GLTFBuffer { data_ptr, uri, }); } for (const auto &view : scene.root["bufferViews"]) { uint64_t stride_res; auto stride_error = view["byteStride"].get(stride_res); if (stride_error) { stride_res = 0; } scene.bufferViews.push_back(GLTFBufferView { static_cast<uint32_t>(view["buffer"].get_uint64()), static_cast<uint32_t>(view["byteOffset"].get_uint64()), static_cast<uint32_t>(stride_res), static_cast<uint32_t>(view["byteLength"].get_uint64()), }); } for (const auto &accessor : scene.root["accessors"]) { GLTFComponentType type; uint64_t component_type = accessor["componentType"]; if (component_type == 5126) { type = GLTFComponentType::FLOAT; } else if (component_type == 5125) { type = GLTFComponentType::UINT32; } else if (component_type == 5123) { type = GLTFComponentType::UINT16; } else { cerr << "GLTF loading '" << gltf_path << "' failed: unknown component type" << endl; abort(); } uint64_t byte_offset; auto offset_error = accessor["byteOffset"].get(byte_offset); if (offset_error) { byte_offset = 0; } scene.accessors.push_back(GLTFAccessor { static_cast<uint32_t>(accessor["bufferView"].get_uint64()), static_cast<uint32_t>(byte_offset), static_cast<uint32_t>(accessor["count"].get_uint64()), type, }); } auto images_elem = scene.root.at_key("images"); if (images_elem.error() != simdjson::NO_SUCH_FIELD) { for (const auto &json_image : images_elem.get_array()) { GLTFImage img {}; string_view uri {}; auto uri_err = json_image["uri"].get(uri); if (!uri_err) { img.type = GLTFImageType::EXTERNAL; img.filePath = uri; } else { uint64_t view_idx = json_image["bufferView"]; string_view mime = json_image["mimeType"]; if (mime == "image/jpeg") { img.type = GLTFImageType::JPEG; } else if (mime == "image/png") { img.type = GLTFImageType::PNG; } else if (mime == "image/x-basis") { img.type = GLTFImageType::BASIS; } img.viewIdx = view_idx; } scene.images.push_back(img); } } auto textures_elem = scene.root.at_key("textures"); if (textures_elem.error() != simdjson::NO_SUCH_FIELD) { for (const auto &texture : textures_elem.get_array()) { uint64_t source_idx; auto src_err = texture["source"].get(source_idx); if (src_err) { auto ext_err = texture["extensions"]["GOOGLE_texture_basis"]["source"] .get(source_idx); if (ext_err) { cerr << "GLTF loading '" << gltf_path << "' failed: texture without source" << endl; abort(); } } uint64_t sampler_idx; auto sampler_error = texture["sampler"].get(sampler_idx); if (sampler_error) { sampler_idx = 0; } scene.textures.push_back(GLTFTexture { static_cast<uint32_t>(source_idx), static_cast<uint32_t>(sampler_idx), }); } } for (const auto &material : scene.root["materials"]) { const auto &pbr = material["pbrMetallicRoughness"]; simdjson::dom::element base_tex; // FIXME assumes tex coord 0 uint64_t tex_idx; auto tex_err = pbr["baseColorTexture"]["index"].get(tex_idx); if (tex_err) { tex_idx = scene.textures.size(); } glm::vec4 base_color(0.f); simdjson::dom::array base_color_json; auto color_err = pbr["baseColorFactor"].get(base_color_json); if (!color_err) { float *base_color_data = glm::value_ptr(base_color); for (double comp : base_color_json) { *base_color_data = comp; base_color_data++; } } double metallic; auto metallic_err = pbr["metallicFactor"].get(metallic); if (metallic_err) { metallic = 0; } double roughness; auto roughness_err = pbr["roughnessFactor"].get(roughness); if (roughness_err) { roughness = 1; } scene.materials.push_back(GLTFMaterial { static_cast<uint32_t>(tex_idx), base_color, static_cast<float>(metallic), static_cast<float>(roughness), }); } for (const auto &mesh : scene.root["meshes"]) { simdjson::dom::array prims = mesh["primitives"]; if (prims.size() != 1) { cerr << "GLTF loading '" << gltf_path << "' failed: " << "Only single primitive meshes supported" << endl; } simdjson::dom::element prim = prims.at(0); simdjson::dom::element attrs = prim["attributes"]; optional<uint32_t> position_idx; optional<uint32_t> normal_idx; optional<uint32_t> uv_idx; optional<uint32_t> color_idx; uint64_t position_res; auto position_error = attrs["POSITION"].get(position_res); if (!position_error) { position_idx = position_res; } uint64_t normal_res; auto normal_error = attrs["NORMAL"].get(normal_res); if (!normal_error) { normal_idx = normal_res; } uint64_t uv_res; auto uv_error = attrs["TEXCOORD_0"].get(uv_res); if (!uv_error) { uv_idx = uv_res; } uint64_t color_res; auto color_error = attrs["COLOR_0"].get(color_res); if (!color_error) { color_idx = color_res; } scene.meshes.push_back(GLTFMesh { position_idx, normal_idx, uv_idx, color_idx, static_cast<uint32_t>(prim["indices"].get_uint64()), static_cast<uint32_t>(prim["material"].get_uint64()), }); } for (const auto &node : scene.root["nodes"]) { vector<uint32_t> children; simdjson::dom::array json_children; auto children_error = node["children"].get(json_children); if (!children_error) { for (uint64_t child : json_children) { children.push_back(child); } } uint64_t mesh_idx; auto mesh_error = node["mesh"].get(mesh_idx); if (mesh_error) { mesh_idx = scene.meshes.size(); } glm::mat4 txfm(1.f); simdjson::dom::array matrix; auto matrix_error = node["matrix"].get(matrix); if (!matrix_error) { float *txfm_data = glm::value_ptr(txfm); for (double mat_elem : matrix) { *txfm_data = mat_elem; txfm_data++; } } else { glm::mat4 translation(1.f); simdjson::dom::array translate_raw; auto translate_error = node["translation"].get(translate_raw); if (!translate_error) { glm::vec3 translate_vec; float *translate_ptr = glm::value_ptr(translate_vec); for (double vec_elem : translate_raw) { *translate_ptr = vec_elem; translate_ptr++; } translation = glm::translate(translate_vec); } glm::mat4 rotation(1.f); simdjson::dom::array quat_raw; auto quat_error = node["rotation"].get(quat_raw); if (!quat_error) { glm::quat quat_vec; float *quat_ptr = glm::value_ptr(quat_vec); for (double vec_elem : quat_raw) { *quat_ptr = vec_elem; quat_ptr++; } rotation = glm::mat4_cast(quat_vec); } glm::mat4 scale(1.f); simdjson::dom::array scale_raw; auto scale_error = node["scale"].get(scale_raw); if (!scale_error) { glm::vec3 scale_vec; float *scale_ptr = glm::value_ptr(scale_vec); for (double vec_elem : scale_raw) { *scale_ptr = vec_elem; scale_ptr++; } scale = glm::scale(scale_vec); } txfm = translation * rotation * scale; } scene.nodes.push_back(GLTFNode { move(children), static_cast<uint32_t>(mesh_idx), txfm}); } simdjson::dom::array scenes = scene.root["scenes"]; if (scenes.size() > 1) { cerr << "GLTF loading '" << gltf_path << "' failed: Multiscene files not supported" << endl; abort(); } for (uint64_t node_idx : scenes.at(0)["nodes"]) { scene.rootNodes.push_back(node_idx); } } catch (const simdjson::simdjson_error &e) { cerr << "GLTF loading '" << gltf_path << "' failed: " << e.what() << endl; abort(); } return scene; } template <typename T> static StridedSpan<T> getGLTFBufferView(const GLTFScene &scene, uint32_t view_idx, uint32_t start_offset = 0, uint32_t num_elems = 0) { const GLTFBufferView &view = scene.bufferViews[view_idx]; const GLTFBuffer &buffer = scene.buffers[view.bufferIdx]; if (buffer.dataPtr == nullptr) { cerr << "GLTF loading failed: external references not supported" << endl; } size_t total_offset = start_offset + view.offset; const uint8_t *start_ptr = buffer.dataPtr + total_offset; ; uint32_t stride = view.stride; if (stride == 0) { stride = sizeof(T); } if (num_elems == 0) { num_elems = view.numBytes / stride; } return StridedSpan<T>(start_ptr, num_elems, stride); } template <typename T> static StridedSpan<T> getGLTFAccessorView(const GLTFScene &scene, uint32_t accessor_idx) { const GLTFAccessor &accessor = scene.accessors[accessor_idx]; return getGLTFBufferView<T>(scene, accessor.viewIdx, accessor.offset, accessor.numElems); } static void dumpGLTFTexture(const GLTFScene &scene, const GLTFImage &img, string_view texture_dir, string_view texture_name) { const GLTFBufferView &buffer_view = scene.bufferViews[img.viewIdx]; if (buffer_view.stride > 1) { cerr << "GLTF import: cannot dump strided texture" << endl; abort(); } ofstream tex_dump(filesystem::path(texture_dir) / texture_name); const uint8_t *tex_ptr = scene.internalData.data() + buffer_view.offset; tex_dump.write(reinterpret_cast<const char *>(tex_ptr), buffer_view.numBytes); } template <typename MaterialType> vector<MaterialType> gltfParseMaterials(const GLTFScene &scene, optional<string_view> texture_dir) { vector<MaterialType> materials; materials.reserve(scene.materials.size()); unordered_set<uint32_t> internal_tracker; for (const auto &gltf_mat : scene.materials) { uint32_t tex_idx = gltf_mat.textureIdx; string tex_name = ""; if (tex_idx < scene.textures.size()) { const GLTFImage &img = scene.images[scene.textures[tex_idx].sourceIdx]; if (img.type == GLTFImageType::EXTERNAL) { tex_name = img.filePath; } else { const char *ext; if (img.type == GLTFImageType::JPEG) { ext = ".jpg"; } else if (img.type == GLTFImageType::PNG) { ext = ".png"; } else if (img.type == GLTFImageType::BASIS) { ext = ".basis"; } else { cerr << "GLTF: Unsupported internal image type" << endl; abort(); } tex_name = scene.sceneName + "_" + to_string(tex_idx) + ext; if (texture_dir.has_value()) { auto inserted = internal_tracker.emplace(tex_idx); if (inserted.second) { dumpGLTFTexture(scene, img, texture_dir.value(), tex_name); } } } } materials.push_back(MaterialType::make(tex_name, gltf_mat.baseColor, gltf_mat.roughness)); } return materials; } template <typename T, typename = int> struct HasPosition : std::false_type {}; template <typename T> struct HasPosition<T, decltype((void)T::px, 0)> : std::true_type {}; template <typename T, typename = int> struct HasNormal : std::false_type {}; template <typename T> struct HasNormal<T, decltype((void)T::nx, 0)> : std::true_type {}; template <typename T, typename = int> struct HasUV : std::false_type {}; template <typename T> struct HasUV<T, decltype((void)T::ux, 0)> : std::true_type {}; template <typename T, typename = int> struct HasColor : std::false_type {}; template <typename T> struct HasColor<T, decltype((void)T::color, 0)> : std::true_type {}; template <typename VertexType> pair<vector<VertexType>, vector<uint32_t>> gltfParseMesh( const GLTFScene &scene, uint32_t mesh_idx) { vector<VertexType> vertices; vector<uint32_t> indices; const GLTFMesh &mesh = scene.meshes[mesh_idx]; optional<StridedSpan<const glm::vec3>> position_accessor; optional<StridedSpan<const glm::vec3>> normal_accessor; optional<StridedSpan<const glm::vec2>> uv_accessor; optional<StridedSpan<const glm::u8vec3>> color_accessor; constexpr bool has_position = HasPosition<VertexType>::value; constexpr bool has_normal = HasNormal<VertexType>::value; constexpr bool has_uv = HasUV<VertexType>::value; constexpr bool has_color = HasColor<VertexType>::value; if constexpr (has_position) { position_accessor = getGLTFAccessorView<const glm::vec3>( scene, mesh.positionIdx.value()); } if constexpr (has_normal) { if (mesh.normalIdx.has_value()) { normal_accessor = getGLTFAccessorView<const glm::vec3>( scene, mesh.normalIdx.value()); } } if constexpr (has_uv) { if (mesh.uvIdx.has_value()) { uv_accessor = getGLTFAccessorView<const glm::vec2>( scene, mesh.uvIdx.value()); } } if constexpr (has_color) { if (mesh.colorIdx.has_value()) { color_accessor = getGLTFAccessorView<const glm::u8vec3>( scene, mesh.colorIdx.value()); } } uint32_t max_idx = 0; auto index_type = scene.accessors[mesh.indicesIdx].type; if (index_type == GLTFComponentType::UINT32) { auto idx_accessor = getGLTFAccessorView<const uint32_t>(scene, mesh.indicesIdx); indices.reserve(idx_accessor.size()); for (uint32_t idx : idx_accessor) { if (idx > max_idx) { max_idx = idx; } indices.push_back(idx); } } else if (index_type == GLTFComponentType::UINT16) { auto idx_accessor = getGLTFAccessorView<const uint16_t>(scene, mesh.indicesIdx); indices.reserve(idx_accessor.size()); for (uint16_t idx : idx_accessor) { if (idx > max_idx) { max_idx = idx; } indices.push_back(idx); } } else { cerr << "GLTF loading failed: unsupported index type" << endl; abort(); } assert(max_idx < position_accessor->size()); vertices.reserve(max_idx + 1); for (uint32_t vert_idx = 0; vert_idx <= max_idx; vert_idx++) { VertexType vert {}; if constexpr (has_position) { const auto &pos = (*position_accessor)[vert_idx]; vert.px = pos.x; vert.py = pos.y; vert.pz = pos.z; } if constexpr (has_normal) { if (normal_accessor.has_value()) { const auto &normal = (*normal_accessor)[vert_idx]; vert.nx = normal.x; vert.ny = normal.y; vert.nz = normal.y; } } if constexpr (has_uv) { if (uv_accessor.has_value()) { const auto &uv = (*uv_accessor)[vert_idx]; vert.ux = uv.x; vert.uy = uv.y; } } if constexpr (has_color) { if (color_accessor.has_value()) { vert.color = glm::u8vec4((*color_accessor)[vert_idx], 255); } } vertices.push_back(vert); } return {move(vertices), move(indices)}; } std::vector<InstanceProperties> gltfParseInstances( const GLTFScene &scene, const glm::mat4 &coordinate_txfm) { vector<pair<uint32_t, glm::mat4>> node_stack; for (uint32_t root_node : scene.rootNodes) { node_stack.emplace_back(root_node, coordinate_txfm); } vector<InstanceProperties> instances; while (!node_stack.empty()) { auto [node_idx, parent_txfm] = node_stack.back(); node_stack.pop_back(); const GLTFNode &cur_node = scene.nodes[node_idx]; glm::mat4 cur_txfm = parent_txfm * cur_node.transform; for (const uint32_t child_idx : cur_node.children) { node_stack.emplace_back(child_idx, cur_txfm); } if (cur_node.meshIdx < scene.meshes.size()) { instances.push_back({ cur_node.meshIdx, scene.meshes[cur_node.meshIdx].materialIdx, cur_txfm, }); } } return instances; } template <typename VertexType, typename MaterialType> SceneDescription<VertexType, MaterialType> parseGLTF( filesystem::path scene_path, const glm::mat4 &base_txfm, optional<string_view> texture_dir) { auto raw_scene = gltfLoad(scene_path); vector<MaterialType> materials = gltfParseMaterials<MaterialType>(raw_scene, texture_dir); vector<Mesh<VertexType>> geometry; for (uint32_t mesh_idx = 0; mesh_idx < raw_scene.meshes.size(); mesh_idx++) { auto [vertices, indices] = gltfParseMesh<VertexType>(raw_scene, mesh_idx); geometry.push_back({ move(vertices), move(indices), }); } vector<InstanceProperties> instances = gltfParseInstances(raw_scene, base_txfm); return SceneDescription<VertexType, MaterialType> { move(geometry), move(materials), move(instances), {}, }; } } }
6cb885e29a0940ac3e18970dc851aa90e44685a8
202b96b76fc7e3270b7a4eec77d6e1fd7d080b12
/modules/libcrypto/src/OpEncryptedFile.cpp
c910231f6c02108d07ef3bc6c4a11ad023a164af
[]
no_license
prestocore/browser
4a28dc7521137475a1be72a6fbb19bbe15ca9763
8c5977d18f4ed8aea10547829127d52bc612a725
refs/heads/master
2016-08-09T12:55:21.058966
1995-06-22T00:00:00
1995-06-22T00:00:00
51,481,663
98
66
null
null
null
null
UTF-8
C++
false
false
16,427
cpp
OpEncryptedFile.cpp
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 2011-2012 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * */ #include "core/pch.h" #if defined(CRYPTO_ENCRYPTED_FILE_SUPPORT) #include "modules/libcrypto/include/OpEncryptedFile.h" #include "modules/libcrypto/include/CryptoHash.h" #include "modules/libcrypto/include/CryptoStreamEncryptionCFB.h" #include "modules/libcrypto/include/CryptoSymmetricAlgorithm.h" #include "modules/util/opfile/opfile.h" #include "modules/stdlib/util/opdate.h" #define CORRECT_KEY_CHECK "CORRECTKEYCHECK:" /* Encryption format * * Since we use AES in CFB mode, the file encryption needs an Initialization vector IV. * * The IV is stored in the first n bytes as plain text, where n is the block size of the cipher. The next n bytes is an encryption of CORRECT_KEY_CHECK defined above. The rest of * the file is normal encrypted text. * * Formally: * * Let IV=[iv_0, ..., iv_(n-1)] be the IV vector, P=[p_0,p_1...p_(l-1)] be the plain text, and Let C=[ c_0, c_1, ...,c_(l+(n*2-1))] be the resulting cipher text, * where iv_i, p_i and c_i are bytes. * * E_k is the AES encryption algorithm, and k is the key. * * C = [iv_0,iv_1,...,iv_(n-1), E_k(CORRECT_KEY_CHECK), E_k(p_0,p_1,....,p_(l-1)) ] * */ OpEncryptedFile::OpEncryptedFile() : m_file(NULL) , m_stream_cipher(NULL) , m_key(NULL) , m_internal_buffer(NULL) , m_internal_buffer_size(0) , m_iv_buf(NULL) , m_temp_buf(NULL) , m_first_append(FALSE) , m_first_append_block_ptr(0) , m_serialized(FALSE) , m_file_position_changed(FALSE) { } OpEncryptedFile::~OpEncryptedFile() { op_memset(m_key, 0, m_stream_cipher->GetKeySize()); /* for security */ OP_DELETE(m_file); OP_DELETE(m_stream_cipher); OP_DELETEA(m_internal_buffer); OP_DELETEA(m_key); OP_DELETEA(m_temp_buf); OP_DELETEA(m_iv_buf); } /* static */ OP_STATUS OpEncryptedFile::Create(OpLowLevelFile** new_file, const uni_char* path, const UINT8 *key, int key_length, BOOL serialized) { if (!new_file || !path || !key || key_length <= 0) return OpStatus::ERR_OUT_OF_RANGE; *new_file = NULL; OpStackAutoPtr<OpEncryptedFile> temp_file(OP_NEW(OpEncryptedFile, ())); if (!temp_file.get()) return OpStatus::ERR_NO_MEMORY; RETURN_IF_ERROR(OpLowLevelFile::Create(&temp_file->m_file, path, serialized)); CryptoSymmetricAlgorithm *alg = CryptoSymmetricAlgorithm::CreateAES(key_length); if (!alg || !(temp_file->m_stream_cipher = CryptoStreamEncryptionCFB::Create(alg))) { OP_DELETE(alg); return OpStatus::ERR_NO_MEMORY; } temp_file->m_key = OP_NEWA(byte, key_length); if (temp_file->m_key == NULL) return OpStatus::ERR_NO_MEMORY; op_memcpy(temp_file->m_key, key, key_length); temp_file->m_stream_cipher->SetKey(key); if ((temp_file->m_iv_buf = OP_NEWA(byte, temp_file->m_stream_cipher->GetBlockSize())) == NULL) return OpStatus::ERR_NO_MEMORY; temp_file->m_serialized = serialized; *new_file = temp_file.release(); return OpStatus::OK; } /* virtual */OP_STATUS OpEncryptedFile::GetFileInfo(OpFileInfo* info) { return m_file->GetFileInfo(info); } /* virtual */OP_STATUS OpEncryptedFile::Open(int mode) { if ( (mode & (OPFILE_WRITE | OPFILE_READ)) == (OPFILE_WRITE | OPFILE_READ) || (mode & (OPFILE_APPEND | OPFILE_READ)) == (OPFILE_APPEND | OPFILE_READ) ) { OP_ASSERT(!"Encrypted files cannot be read and written at the same time"); // FixMe return OpStatus::ERR; } mode &= ~OPFILE_TEXT; // OPFILE_TEXT mode does not work with encryption RETURN_IF_ERROR(m_file->Open(mode)); OP_STATUS stat = OpenEncryptedFile2ndPhase(mode); if (OpStatus::IsError(stat)) m_file->Close(); // never keep the file open when returning an error return stat; } OP_STATUS OpEncryptedFile::OpenEncryptedFile2ndPhase(int mode) { unsigned int block_size = static_cast<unsigned int>(m_stream_cipher->GetBlockSize()); BOOL exists = FALSE; RETURN_IF_ERROR(OpStatus::IsSuccess(m_file->Exists(&exists))); if (mode & OPFILE_READ) { if (exists == FALSE) return OpStatus::OK; OpFileLength length; RETURN_IF_ERROR(m_file->GetFileLength(&length)); if (length < 2 * block_size) return OpStatus::ERR; OpFileLength length_read; /* Read up the iv (iv is not encrypted)*/ RETURN_IF_ERROR(m_file->Read(m_iv_buf, block_size, &length_read)); if (length_read != block_size) return OpStatus::ERR; m_stream_cipher->SetIV(m_iv_buf); } if ((mode & OPFILE_APPEND) && exists) { OpFile get_iv_file; RETURN_IF_ERROR(get_iv_file.Construct(m_file->GetFullPath())); RETURN_IF_ERROR(get_iv_file.Open(OPFILE_READ)); OpFileLength length; RETURN_IF_ERROR(get_iv_file.GetFileLength(length)); if (length < 2*block_size) return OpStatus::ERR; length -= block_size; RETURN_IF_ERROR(EnsureBufferSize(2 * block_size)); OpFileLength mult_pos = (length/block_size) * block_size; if ((m_temp_buf = OP_NEWA(byte, block_size)) == NULL) return OpStatus::ERR_NO_MEMORY; op_memset(m_temp_buf, 0, block_size); OpFileLength read; /* Read up the first previous full cipher text, and use that as IV state */ if (mult_pos >= block_size) { m_first_append = TRUE; m_first_append_block_ptr = length - mult_pos; RETURN_IF_ERROR(get_iv_file.SetFilePos(mult_pos /* - block_size */, SEEK_FROM_START)); RETURN_IF_ERROR(get_iv_file.Read(m_iv_buf, block_size, &read)); OP_ASSERT(read == block_size); m_stream_cipher->SetIV(m_iv_buf); RETURN_IF_ERROR(get_iv_file.Read(m_temp_buf, length - mult_pos, &read)); } else { m_first_append = TRUE; m_first_append_block_ptr = length % block_size; RETURN_IF_ERROR(get_iv_file.Read(m_iv_buf, block_size, &read)); /* The IV is the first block_size bytes in the file */ m_stream_cipher->SetIV(m_iv_buf); RETURN_IF_ERROR(get_iv_file.Read(m_temp_buf, length % block_size, &read)); } m_stream_cipher->SetKey(m_key); RETURN_IF_ERROR(get_iv_file.Close()); } const char *encrypted_check = CORRECT_KEY_CHECK; if (mode & (OPFILE_READ)) { char *check_str = OP_NEWA(char, op_strlen(encrypted_check)); if (check_str == NULL) return OpStatus::ERR_NO_MEMORY; ANCHOR_ARRAY(char, check_str); OpFileLength length_read; RETURN_IF_ERROR(Read(check_str, op_strlen(encrypted_check), &length_read)); if (length_read != (OpFileLength)op_strlen(encrypted_check)) return OpStatus::ERR; if (op_strncmp(check_str, encrypted_check, op_strlen(encrypted_check))) return OpStatus::ERR_NO_ACCESS; } if ( (mode & ( OPFILE_WRITE)) || ((mode | OPFILE_APPEND) && exists == FALSE) ) { // Calculate an IV (Doesn't have to be very random) CryptoHash *hasher; hasher = CryptoHash::CreateSHA1(); if (hasher == NULL) return OpStatus::ERR_NO_MEMORY; unsigned char hash_buffer[20]; /* ARRAY OK 2008-11-10 haavardm */ OP_ASSERT(hasher->Size() == 20); OP_ASSERT(sizeof(hash_buffer) == hasher->Size() && static_cast<unsigned int>(hasher->Size()) >= block_size); const uni_char *path = m_file->GetFullPath(); hasher->InitHash(); hasher->CalculateHash(reinterpret_cast<const UINT8 *>(path), sizeof(uni_char)*uni_strlen(path)); hasher->CalculateHash(reinterpret_cast<const UINT8 *>(this), sizeof(this)); double gmt_unix_time = OpDate::GetCurrentUTCTime(); hasher->CalculateHash(reinterpret_cast<const UINT8 *>(&gmt_unix_time), sizeof(double)); hasher->ExtractHash(hash_buffer); OP_DELETE(hasher); op_memcpy(m_iv_buf, hash_buffer, block_size); // Write IV as plain text, only use the first block_size bytes of the hash_buffer. RETURN_IF_ERROR(m_file->Write(hash_buffer, block_size)); m_stream_cipher->SetIV(m_iv_buf); RETURN_IF_ERROR(Write(encrypted_check, op_strlen(encrypted_check))); } return OpStatus::OK; } /* virtual */ OP_STATUS OpEncryptedFile::GetFilePos(OpFileLength* pos) const { if (!pos) return OpStatus::ERR_OUT_OF_RANGE; OpFileLength real_length; RETURN_IF_ERROR(m_file->GetFilePos(&real_length)); OpFileLength checklen = static_cast<OpFileLength>(op_strlen(CORRECT_KEY_CHECK) + m_stream_cipher->GetBlockSize()); if (real_length < checklen) { return OpStatus::ERR; } *pos = real_length - checklen; return OpStatus::OK; } /* virtual */OP_STATUS OpEncryptedFile::SetFilePos(OpFileLength pos, OpSeekMode seek_mode) { OpFileLength current_pos; RETURN_IF_ERROR(GetFilePos(&current_pos)); if (current_pos == pos) return OpStatus::OK; OpFileLength file_length; RETURN_IF_ERROR(GetFileLength(&file_length)); if (file_length < pos) return OpStatus::ERR; OpFileLength block_size = m_stream_cipher->GetBlockSize(); OpFileLength block_position = (pos/block_size) * block_size; RETURN_IF_ERROR(m_file->SetFilePos(op_strlen(CORRECT_KEY_CHECK) + block_position, seek_mode)); m_file_position_changed = TRUE; OpFileLength length; RETURN_IF_ERROR(m_file->GetFileLength(&length)); if (length - pos < block_size) return OpStatus::ERR; OpFileLength length_read; /* Read up the iv (iv is the previous encrypted block) */ RETURN_IF_ERROR(m_file->Read(m_iv_buf, block_size, &length_read)); if (length_read != block_size) return OpStatus::ERR; m_stream_cipher->SetIV(m_iv_buf); /* Skip the first pos - block_position bytes */ OP_ASSERT(block_size <= CRYPTO_MAX_CIPHER_BLOCK_SIZE); UINT8 temp_buf2[CRYPTO_MAX_CIPHER_BLOCK_SIZE]; return Read(temp_buf2, pos - block_position, &length_read); } /* virtual */OP_STATUS OpEncryptedFile::GetFileLength(OpFileLength* len) const { if (!len) return OpStatus::ERR_OUT_OF_RANGE; OpFileLength real_length; RETURN_IF_ERROR(m_file->GetFileLength(&real_length)); OpFileLength checklen = static_cast<OpFileLength>(op_strlen(CORRECT_KEY_CHECK) + m_stream_cipher->GetBlockSize()); if (real_length < checklen) { return OpStatus::ERR; } *len = real_length - checklen; return OpStatus::OK; } /* virtual */OP_STATUS OpEncryptedFile::SetFileLength(OpFileLength len) { OP_ASSERT(!"Dont use"); return m_file->SetFileLength(len + static_cast<OpFileLength>(op_strlen(CORRECT_KEY_CHECK) + m_stream_cipher->GetBlockSize())); } /* virtual */OP_STATUS OpEncryptedFile::Write(const void* data, OpFileLength len) { if (m_file_position_changed) { OP_ASSERT(!"SetFilePos cannot be used when writing files, file will be destroyed, and will cause security problems"); return OpStatus::ERR; } if (len == 0) return OpStatus::OK; if (!data || len <= 0) return OpStatus::ERR_OUT_OF_RANGE; unsigned int block_size = m_stream_cipher->GetBlockSize(); RETURN_IF_ERROR(EnsureBufferSize(len + block_size)); if (m_first_append) { OP_ASSERT(m_temp_buf != NULL); OP_ASSERT(m_first_append_block_ptr <= block_size); if (m_first_append_block_ptr > block_size) return OpStatus::ERR; /* calculate correct state from cipher text on last block in file, and the data written */ OpFileLength rest_block_len = block_size - m_first_append_block_ptr; OpFileLength rest_data_len = len > rest_block_len ? len - rest_block_len : 0; OP_ASSERT(block_size <= CRYPTO_MAX_CIPHER_BLOCK_SIZE); UINT8 temp_buf2[CRYPTO_MAX_CIPHER_BLOCK_SIZE]; op_memset(temp_buf2, 0, block_size); op_memcpy(temp_buf2 + m_first_append_block_ptr, data, (size_t) MIN(rest_block_len, len)); OpFileLength encrypt_length = len < rest_block_len ? m_first_append_block_ptr + len : block_size; m_stream_cipher->Encrypt(temp_buf2, m_internal_buffer, (int) encrypt_length); op_memmove(m_internal_buffer, m_internal_buffer + m_first_append_block_ptr, (size_t) MIN(rest_block_len, len)); op_memcpy(m_temp_buf + m_first_append_block_ptr, m_internal_buffer, (size_t) MIN(rest_block_len, len)); if (rest_data_len > 0) { m_stream_cipher->SetIV(m_temp_buf); m_first_append = FALSE; m_stream_cipher->Encrypt(static_cast<const byte*>(data) + rest_block_len, m_internal_buffer + rest_block_len, (int) rest_data_len); } else { m_stream_cipher->SetIV(m_iv_buf); m_first_append_block_ptr += len; } } else m_stream_cipher->Encrypt(static_cast<const byte*>(data), m_internal_buffer, (int) len); return m_file->Write(m_internal_buffer, len); } /* virtual */OP_STATUS OpEncryptedFile::Read(void* data, OpFileLength len, OpFileLength* bytes_read) { if (len == 0) return OpStatus::OK; if (!data || len <= 0) return OpStatus::ERR_OUT_OF_RANGE; if (!bytes_read) return OpStatus::ERR_NULL_POINTER; RETURN_IF_ERROR(EnsureBufferSize(len + m_stream_cipher->GetBlockSize())); RETURN_IF_ERROR(m_file->Read(m_internal_buffer, len, bytes_read)); m_stream_cipher->Decrypt(m_internal_buffer, static_cast<byte*>(data), (int) *bytes_read); return OpStatus::OK; } /* virtual */OP_STATUS OpEncryptedFile::ReadLine(char** data) { OP_ASSERT(!"Current version does not support reading line"); return OpStatus::ERR; } OpLowLevelFile* OpEncryptedFile::CreateCopy() { OpStackAutoPtr<OpEncryptedFile> temp_file(OP_NEW(OpEncryptedFile, ())); if (!temp_file.get()) return NULL; const uni_char *path = m_file->GetFullPath(); if (OpStatus::IsError(OpLowLevelFile::Create(&temp_file->m_file, path, m_serialized))) return NULL; CryptoSymmetricAlgorithm *alg = CryptoSymmetricAlgorithm::CreateAES(m_stream_cipher->GetKeySize()); if (!alg || !(temp_file->m_stream_cipher = CryptoStreamEncryptionCFB::Create(alg))) { OP_DELETE(alg); return NULL; } if ((temp_file->m_key = OP_NEWA(byte, m_stream_cipher->GetKeySize())) == NULL) return NULL; op_memcpy(temp_file->m_key, m_key, m_stream_cipher->GetKeySize()); temp_file->m_stream_cipher->SetKey(m_key); unsigned int block_size = temp_file->m_stream_cipher->GetBlockSize(); if ((temp_file->m_iv_buf = OP_NEWA(byte, block_size)) == NULL) return NULL; CryptoHash *hasher; if ((hasher = CryptoHash::CreateSHA1()) == NULL) return NULL; unsigned char hash_buffer[20]; /* ARRAY OK 2009-06-18 alexeik */ OP_ASSERT(hasher->Size() == 20); OP_ASSERT(sizeof(hash_buffer) == hasher->Size() && static_cast<unsigned int>(hasher->Size()) >= block_size); hasher->InitHash(); hasher->CalculateHash(reinterpret_cast<const UINT8 *>(path), sizeof(uni_char)*uni_strlen(path)); hasher->CalculateHash(reinterpret_cast<const UINT8 *>(this), sizeof(this)); double gmt_unix_time = OpDate::GetCurrentUTCTime(); hasher->CalculateHash(reinterpret_cast<const UINT8 *>(&gmt_unix_time), sizeof(double)); hasher->ExtractHash(hash_buffer); op_memcpy(temp_file->m_iv_buf, hash_buffer, block_size); OP_DELETE(hasher); temp_file->m_stream_cipher->SetIV(temp_file->m_iv_buf); temp_file->m_internal_buffer_size = m_internal_buffer_size; if (m_internal_buffer && (temp_file->m_internal_buffer = OP_NEWA(byte, (size_t) m_internal_buffer_size)) == NULL) return NULL; if (m_temp_buf && (temp_file->m_temp_buf = OP_NEWA(byte, block_size)) == NULL) return NULL; if (temp_file->m_internal_buffer) op_memcpy(temp_file->m_internal_buffer, m_internal_buffer, (size_t) m_internal_buffer_size); if (temp_file->m_iv_buf) op_memcpy(temp_file->m_iv_buf, m_iv_buf, block_size); if (temp_file->m_temp_buf) op_memcpy(temp_file->m_temp_buf, m_temp_buf, block_size); temp_file->m_first_append = m_first_append; temp_file->m_first_append_block_ptr = m_first_append_block_ptr; temp_file->m_serialized = m_serialized; return temp_file.release(); } OpLowLevelFile* OpEncryptedFile::CreateTempFile(const uni_char* prefix) { if (!prefix) return NULL; OpLowLevelFile *new_file; OpLowLevelFile *child_file = m_file->CreateTempFile(prefix); if (child_file == NULL) return NULL; if (OpStatus::IsError(OpEncryptedFile::Create(&new_file, child_file->GetFullPath(), m_key, m_stream_cipher->GetKeySize(), m_serialized))) { OP_DELETE(child_file); return NULL; } OP_DELETE(static_cast<OpEncryptedFile*>(new_file)->m_file); static_cast<OpEncryptedFile*>(new_file)->m_file = child_file; return new_file; } OP_STATUS OpEncryptedFile::EnsureBufferSize(OpFileLength size) { if (m_internal_buffer_size < size) { OP_DELETEA(m_internal_buffer); m_internal_buffer = OP_NEWA(byte, (size_t) size); if (m_internal_buffer == NULL) { m_internal_buffer_size = 0; return OpStatus::ERR_NO_MEMORY; } else { m_internal_buffer_size = size; } } return OpStatus::OK; } #endif // CRYPTO_ENCRYPTED_FILE_SUPPORT
48e6616e8634dcbfb3cf3674204e48608e7a32e6
b6ba0ed8b22843f0bbcbea073b2852be20888c62
/ShiYan_04/LowerMatrix.h
c6f2dbe297f8086717d27557c95fa639ab3a1da3
[]
no_license
yushulinfeng/DataStructure
d215af62b19e51e87f10a549c92205cf06a0ee48
6bb50b56bfbc86622a2509d2a58cf6c422eafff1
refs/heads/master
2021-01-10T01:10:49.322780
2016-01-03T08:18:00
2016-01-03T08:18:00
48,938,772
0
0
null
null
null
null
GB18030
C++
false
false
378
h
LowerMatrix.h
#include "stdafx.h" /*下三角矩阵类*/ template<class T> class LowerMatrix { public: LowerMatrix(int size = 5){ n = size; t = new T[n*(n + 1) / 2]; } ~LowerMatrix(){ delete[]t; } LowerMatrix<T>& Store(const T& x, int i, int j); T Retrieve(int i, int j)const; void Output(ostream& out)const; private: int n;//矩阵维数 T *t;//储存矩阵的一维数组 };
0c10aadf08f94a69f150a064b3c584b3d95c2d37
f2f8bf9a304d8f390b800b25cc81da5175ecd289
/runa/foundation/font/font_view_impl.h
cda9641f3ad4df28f711743385b5d5fb7fe9643a
[ "BSL-1.0" ]
permissive
walkinsky8/nana-runner
dbc46227a083b99bf5dfd909ca5c48543ceac106
9cd8f9a0ec3ef50c858a89656435d87ca14cdb0f
refs/heads/master
2023-03-03T08:17:19.169671
2023-02-26T14:57:17
2023-02-26T14:57:17
79,042,119
5
1
null
null
null
null
UTF-8
C++
false
false
959
h
font_view_impl.h
/** * Runa C++ Library * Copyright (c) 2017-2019 walkinsky:lyh6188(at)hotmail(dot)com * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ // Created on 2019/01/22 #pragma once #include <runa/foundation/font/font_view.h> #include <runa/foundation/font/font_model.h> namespace runa { class font_view_impl : public font_view { NAR_DEFINE_VIEW_IMPL(font); model_proxy<font_model> model_; public: font_view_impl(widget_cfg& _cfg, window _parent) : super{ _cfg, _parent } { init(); } void set_model_proxy(model_proxy<font_model> const& _proxy); private: void init(); void on_ok(); void on_cancel(); void load_model(); void save_model(); void on_model_updated(); font get_font_value() const; }; }
1f9778cedb5c6052f81c0fbad06957bac6c0d1bc
b1f773739fc97ae550baa13df512822dc11a6d5d
/convert.cc
ea3b20e6f206201bf10640c86d4e169ea4bc4633
[]
no_license
amluto/tpmkey
376d3e72777cc29940bbce6d427ce6e4c16a443c
77a904283445e4e5bcc67c39039260828b84167d
refs/heads/master
2021-01-10T13:45:01.947762
2013-09-11T03:07:24
2013-09-11T03:07:24
45,418,325
0
0
null
null
null
null
UTF-8
C++
false
false
6,461
cc
convert.cc
/* -*- mode: c++; c-file-style: "bsd" -*- TPMKey conversion commands Copyright (c) 2011 Andrew Lutomirski. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY ANDREW LUTOMIRSKI ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ANDREW LUTOMIRSKI OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "cli.h" #include "tspi_helpers.h" #include <stdio.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <string.h> #include <malloc.h> #include <limits> #include "utils.h" #include "tpmkey_files.h" #include "keyfile.h" #include <arpa/inet.h> extern "C" { #include <gnutls/gnutls.h> #include <gnutls/abstract.h> } namespace TPMKey { int cmd_raw_convert_pubkey(struct global_args &args) { gnutls_global_init(); TPMBuffer::Ptr blob = ReadFile(AT_FDCWD, args.sub_argv[1], 4096); if (blob->len < sizeof(TPMKey_private_key)) throw std::runtime_error("File is too short"); const TPMKey_private_key *key = reinterpret_cast<TPMKey_private_key*>(blob->data); if (memcmp(key->magic, TPMKey_private_key_magic, sizeof(key->magic))) throw std::runtime_error("File is not a TPMKey private key"); // Find the TPM_KEY structure size_t tpm_key_size = blob->len - sizeof(TPMKey_private_key); if (tpm_key_size > std::numeric_limits<uint32_t>::max() - 16) throw std::runtime_error("File is too large"); const void *enc_tpm_key = key + 1; // Use TSPI to parse it. No need to decrypt first -- we won't // try to load the key TPMContext::Ptr context(new TPMContext); TPMRsaKey::Ptr rsakey = TPMRsaKey::Create(context, 0); rsakey->SetAttribData(TSS_TSPATTRIB_KEY_BLOB, TSS_TSPATTRIB_KEYBLOB_BLOB, enc_tpm_key, tpm_key_size); // Start writing the results printf("TPMKey keypair\n"); // Read out flags uint32_t flags = ntohl(key->flags); printf(" Extra privkey encryption:"); bool need_and = false; if (flags & TPMKey_PRIVATE_KEY_SCRYPT) { printf(" password (scrypt)"); need_and = true; } if (flags & TPMKey_PRIVATE_KEY_PARENT_SECRET) { if (need_and) printf(" and"); printf(" parent key symmetric secret"); need_and = true; } if (!need_and) { printf(" not encrypted"); } printf("\n"); // Read out basic attributes UINT32 keysize = rsakey->GetAttribUint32(TSS_TSPATTRIB_RSAKEY_INFO, TSS_TSPATTRIB_KEYINFO_RSA_KEYSIZE); printf(" Size: %lu\n", (long)keysize); UINT32 usage = rsakey->GetAttribUint32(TSS_TSPATTRIB_KEY_INFO, TSS_TSPATTRIB_KEYINFO_USAGE); printf(" Usage: %s\n", keyinfo_usage_to_string(usage)); UINT32 keyflags = rsakey->GetAttribUint32(TSS_TSPATTRIB_KEY_INFO, TSS_TSPATTRIB_KEYINFO_KEYFLAGS); printf(" Migratable: %s\n", (keyflags & TSS_KEYFLAG_MIGRATABLE) ? "yes" : "no (key known only to TPM)"); UINT32 ss = rsakey->GetAttribUint32(TSS_TSPATTRIB_KEY_INFO, TSS_TSPATTRIB_KEYINFO_SIGSCHEME); if (ss == TSS_SS_NONE) printf(" Signature scheme: none\n"); else if (ss == TSS_SS_RSASSAPKCS1V15_SHA1) printf(" Signature scheme: PKCS#1 v1.5 SHA1\n"); else if (ss == TSS_SS_RSASSAPKCS1V15_DER) printf(" Signature scheme: PKCS#1 v1.5 unrestricted (TSS DER)\n"); else if (ss == TSS_SS_RSASSAPKCS1V15_INFO) printf(" Signature scheme: PKCS#1 v1.5 TPM_SIGN_INFO\n"); else printf(" Signature scheme: unknown (0x%X)\n", (unsigned int)ss); UINT32 es = rsakey->GetAttribUint32(TSS_TSPATTRIB_KEY_INFO, TSS_TSPATTRIB_KEYINFO_ENCSCHEME); if (es == TSS_ES_NONE) printf(" Encryption scheme: none\n"); else if (es == TSS_ES_RSAESPKCSV15) printf(" Encryption scheme: PKCS#1 v1.5\n"); else if (es == TSS_ES_RSAESOAEP_SHA1_MGF1) printf(" Encryption scheme: PKCS#1 v2.0 OAEP P=TCPA\n"); else printf(" Encryption scheme: unknown (0x%X)\n", (unsigned int)es); // Read out authDataUsage. We have to do this manually -- I don't // know how to get it from TSPI if (tpm_key_size >= sizeof(TPM_KEY_header)) { const TPM_KEY_header *header = reinterpret_cast<const TPM_KEY_header *>(enc_tpm_key); if (header->authDataUsage == TPM_AUTH_NEVER) printf(" TPM auth usage required: never [dangerous]\n"); else if (header->authDataUsage == TPM_AUTH_ALWAYS) printf(" TPM auth usage required: always\n"); else if (header->authDataUsage == TPM_AUTH_PRIV_USE_ONLY) printf(" TPM auth usage required: private use only\n"); else printf(" TPM auth usage required: unknown value 0x%02x\n", (unsigned int)header->authDataUsage); } // Read out the RSA parameters TPMBuffer::Ptr e = rsakey->GetAttribData(TSS_TSPATTRIB_RSAKEY_INFO, TSS_TSPATTRIB_KEYINFO_RSA_EXPONENT); TPMBuffer::Ptr n = rsakey->GetAttribData(TSS_TSPATTRIB_RSAKEY_INFO, TSS_TSPATTRIB_KEYINFO_RSA_MODULUS); gnutls_pubkey_t gtls_pubkey; if (gnutls_pubkey_init(&gtls_pubkey) != 0) { fprintf(stderr, "gnutls failure\n"); return 1; } gnutls_datum_t gtls_n = {(unsigned char *)n->data, n->len}; gnutls_datum_t gtls_e = {(unsigned char *)e->data, e->len}; if (gnutls_pubkey_import_rsa_raw(gtls_pubkey, &gtls_n, &gtls_e) != 0) { fprintf(stderr, "gnutls import failure\n"); return 1; } TPMBuffer outbuf(8192); size_t outsize = outbuf.alloc_len; if (int err = gnutls_pubkey_export(gtls_pubkey, GNUTLS_X509_FMT_PEM, outbuf.data, &outsize)) { fprintf(stderr, "Conversion failed: %d\n", err); return 1; } gnutls_pubkey_deinit(gtls_pubkey); fwrite(outbuf.data, outsize, 1, stdout); gnutls_global_deinit(); return 0; } }
097bb47364af2f3d3e12a7baadc8152bae11ace1
ca5fdca4ad31f2bf6297ee28aa2a7c5ceeb5ca8f
/source/Irrlicht/MacOSX/examples/CTBulletHelper.h
b02cc5f904eb442e40dac732d726c48927f90009
[]
no_license
EEmmanuel7/leapmotion-irrlicht
301687843e18afcd69ee21c0d35185e15487ee70
e2403b87cd37620558b37b7936a92d1006f45efe
refs/heads/master
2021-01-15T09:51:44.884672
2013-03-06T11:02:47
2013-03-06T11:02:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
994
h
CTBulletHelper.h
// // CTBulletHelper.h // MacOSX // // Created by James Zaghini on 9/02/13. // // #ifndef __MacOSX__CTBulletHelper__ #define __MacOSX__CTBulletHelper__ #include <iostream> #include "irrlicht.h" #include <BulletDynamics/btBulletDynamicsCommon.h> using namespace irr; using namespace video; using namespace scene; using namespace core; class CTBulletHelper { public: CTBulletHelper(); CTBulletHelper(IVideoDriver *driver, ISceneManager *smgr); void UpdatePhysics(u32 TDeltaTime); private: void CreateBox(const btVector3 &TPosition, const core::vector3df &TScale, btScalar TMass, std::string textureFile); void CreateSphere(const btVector3 &TPosition, btScalar TRadius, btScalar TMass); void QuaternionToEuler(const btQuaternion &TQuat, btVector3 &TEuler); btDiscreteDynamicsWorld *World; core::list<btRigidBody *> Objects; int GetRandInt(int TMax) { return rand() % TMax; } IVideoDriver *driver; ISceneManager *smgr; }; #endif /* defined(__MacOSX__CTBulletHelper__) */
81558589d09effa47d1736156d9ee2b563264f47
50c45ad94d56884b110bcce03efc555c7762e5da
/Object_Oriented_Design/test2.cpp
97992bd1a08b42a30e4254ddb326f3295c44642f
[]
no_license
LaserCakes/School
29977dde72479c3ab9b822a86a69080bd67a28b5
00fcdc449eeaca3e34de94a0d181b5b0d3472d4f
refs/heads/master
2020-04-11T05:38:33.287078
2018-07-30T20:47:43
2018-07-30T20:47:43
68,175,318
0
0
null
null
null
null
UTF-8
C++
false
false
897
cpp
test2.cpp
#include <iostream> #include <string> using namespace std; class Dog //Creates a class named Dog { public: //Acces set to public. Needs to end with a colon : void dogName(string name) //Function takes a string type variable called name { //name listed below is the variable that will be passed to the function cout << "Your new dog " << name << " is ready for pickup!" << endl; } }; //Always end all classes with a semicolon int main(void) { string name; //Create a variable called name, different than the one in Dog class Dog newDog; //Creates a new Object of class Dog called newDog cout << "Please enter your dog's name: "; getline(cin, name); //Function from string library (up top) that takes the stream and a variable as arguments cout << endl; newDog.dogName(name); //Call the fuction inside my new object and pass it the new string created return 0; }
d75b7ddb076829e5244b943b8254b5920f190352
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_new_log_5069.cpp
73bb7eb271b2d7094fa0fc6fc638cc9cb75ac277
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
176
cpp
httpd_new_log_5069.cpp
ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(00493) AP_SIG_GRACEFUL_STRING " received. Doing graceful restart");
722a6c9ac12b573ed401ff87cc97191e445aeed6
40662e477e03bf8757973cec33ada3643a28cb49
/201802/0203/BZOJ4065/BZOJ4065.cpp
4392e825d0bcaa407c8d4d6c383ebbeb329ed2f9
[]
no_license
DreamLolita/BZOJ
389f7ab12c288b9f043818b259bc4bd924dd7f21
a68e8530603d75f65feed3e621af30cbeccc56fe
refs/heads/master
2021-09-15T19:21:56.356204
2018-06-09T05:54:38
2018-06-09T05:54:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,377
cpp
BZOJ4065.cpp
#include<bits/stdc++.h> #define L 16 using namespace std; const int N=1024; const int M=8192; int T,n,m,k,tot,ans; int head[M],q[M]; bool lef[M],vis[M]; char ret[L]; struct Tway { int v,nex,f; }; Tway e[M<<1]; void init() { tot=ans=0; memset(vis,0,sizeof(vis)); memset(head,-1,sizeof(head)); memset(lef,0,sizeof(lef)); } int idx(char *s) { int x; if(sscanf(s+2,"%d",&x)==EOF) return -1; if(!strncmp(s,"AP",2)) return x; if(!strncmp(s,"AS",2)) return x+n; if(!strncmp(s,"BP",2)) return x+n+k; if(!strncmp(s,"BS",2)) return x+n+k+m; return -1; } void idx_ans(int x) { // if(x<= 0) // sprintf(out,"error! index < 0!"); // else if(x<=n) sprintf(ret,"AP%d",x); else if(x<=n+k) sprintf(ret,"AS%d",x-n); else if(x<=n+k+m) sprintf(ret,"BP%d",x-n-k); else if(x<=n+k+m+k) sprintf(ret,"BS%d",x-n-k-m); // else // sprintf(out, "error! index > n + k + m + k"); } void add(int u,int v) { // printf("u:%d v:%d %d\n",u,v,tot); e[tot]=(Tway){v,head[u],0}; head[u]=tot++; e[tot]=(Tway){u,head[v],0}; head[v]=tot++; } bool dfs(int u,int p) { // printf("%d %d\n",u,p); int cnt=0; for(int i=head[u];~i;i=e[i].nex) { // printf("%d %d i:%d %d %d\n",u,p,i,e[i].nex,e[i].f); if(i==(p^1)) continue; int v=e[i].v; if(!dfs(v,i)) return 0; cnt+=(!e[i].f); } if(cnt==2 && p!=-1) e[p].f=e[p^1].f=1; // printf("%d!!! %d\n",cnt,lef[u]); return lef[u] || cnt==1 || cnt==2; } bool pfs(int u) { vis[u]=1;q[ans++]=u; int cnt=0; for(int i=head[u];~i;i=e[i].nex) { int v=e[i].v; if(e[i].f) continue; ++cnt; if(!vis[v] && !pfs(v)) return 0; } return cnt==2; } void solve() { bool flag=1; char u[L],v[L]; scanf("%d%d%d",&k,&n,&m); for(int i=1;i<=k;++i) lef[n+i]=lef[n+k+m+i]=1; for(int i=1;i<n+k;++i) { scanf("%s%s",u,v); add(idx(u),idx(v)); } flag&=dfs(1,-1); for(int i=1;i<m+k;++i) { scanf("%s%s",u,v); add(idx(u),idx(v)); } if(flag) flag&=dfs(n+k+1,-1); for(int i=0;i<k;++i) { scanf("%s%s",u,v); add(idx(u),idx(v)); } if(flag) flag&=pfs(1); if(flag && ans==n+k+m+k) { printf("YES"); for(int i=0;i<ans;++i) { idx_ans(q[i]); printf(" %s",ret); } printf("\n"); } else puts("NO"); } int main() { // freopen("BZOJ4065.in","r",stdin); // freopen("BZOJ4065.out","w",stdout); scanf("%d",&T); while(T--) { init(); solve(); } return 0; }
016cd839cf07a700926ed00889119567161ec734
35a0a383b079978992647555645ac30e52ebec3f
/lib/StaticAnalyzer/Core/DynamicType.cpp
a78e0e05e903b63d55fd47653751aa0905f176c2
[ "Apache-2.0", "LLVM-exception", "NCSA" ]
permissive
Codeon-GmbH/mulle-clang
f050d6d8fb64689a1e4b039c4a6513823de9b430
214e526a2b6afeb9508cac5f88c5a4c28e98982f
refs/heads/mulle_objclang_100
2021-07-18T07:45:29.083064
2021-02-16T17:21:51
2021-02-16T17:21:51
72,544,381
29
5
Apache-2.0
2020-04-30T11:36:08
2016-11-01T14:32:02
C++
UTF-8
C++
false
false
7,624
cpp
DynamicType.cpp
//===- DynamicType.cpp - Dynamic type related APIs --------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines APIs that track and query dynamic type information. This // information can be used to devirtualize calls during the symbolic execution // or do type checking. // //===----------------------------------------------------------------------===// #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h" #include "clang/Basic/JsonSupport.h" #include "clang/Basic/LLVM.h" #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" #include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h" #include "llvm/Support/Casting.h" #include "llvm/Support/raw_ostream.h" #include <cassert> /// The GDM component containing the dynamic type info. This is a map from a /// symbol to its most likely type. REGISTER_MAP_WITH_PROGRAMSTATE(DynamicTypeMap, const clang::ento::MemRegion *, clang::ento::DynamicTypeInfo) /// A set factory of dynamic cast informations. REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(CastSet, clang::ento::DynamicCastInfo) /// A map from symbols to cast informations. REGISTER_MAP_WITH_PROGRAMSTATE(DynamicCastMap, const clang::ento::MemRegion *, CastSet) namespace clang { namespace ento { DynamicTypeInfo getDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR) { MR = MR->StripCasts(); // Look up the dynamic type in the GDM. if (const DynamicTypeInfo *DTI = State->get<DynamicTypeMap>(MR)) return *DTI; // Otherwise, fall back to what we know about the region. if (const auto *TR = dyn_cast<TypedRegion>(MR)) return DynamicTypeInfo(TR->getLocationType(), /*CanBeSub=*/false); if (const auto *SR = dyn_cast<SymbolicRegion>(MR)) { SymbolRef Sym = SR->getSymbol(); return DynamicTypeInfo(Sym->getType()); } return {}; } const DynamicTypeInfo *getRawDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR) { return State->get<DynamicTypeMap>(MR); } const DynamicCastInfo *getDynamicCastInfo(ProgramStateRef State, const MemRegion *MR, QualType CastFromTy, QualType CastToTy) { const auto *Lookup = State->get<DynamicCastMap>().lookup(MR); if (!Lookup) return nullptr; for (const DynamicCastInfo &Cast : *Lookup) if (Cast.equals(CastFromTy, CastToTy)) return &Cast; return nullptr; } ProgramStateRef setDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR, DynamicTypeInfo NewTy) { State = State->set<DynamicTypeMap>(MR->StripCasts(), NewTy); assert(State); return State; } ProgramStateRef setDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR, QualType NewTy, bool CanBeSubClassed) { return setDynamicTypeInfo(State, MR, DynamicTypeInfo(NewTy, CanBeSubClassed)); } ProgramStateRef setDynamicTypeAndCastInfo(ProgramStateRef State, const MemRegion *MR, QualType CastFromTy, QualType CastToTy, bool CastSucceeds) { if (!MR) return State; if (CastSucceeds) { assert((CastToTy->isAnyPointerType() || CastToTy->isReferenceType()) && "DynamicTypeInfo should always be a pointer."); State = State->set<DynamicTypeMap>(MR, CastToTy); } DynamicCastInfo::CastResult ResultKind = CastSucceeds ? DynamicCastInfo::CastResult::Success : DynamicCastInfo::CastResult::Failure; CastSet::Factory &F = State->get_context<CastSet>(); const CastSet *TempSet = State->get<DynamicCastMap>(MR); CastSet Set = TempSet ? *TempSet : F.getEmptySet(); Set = F.add(Set, {CastFromTy, CastToTy, ResultKind}); State = State->set<DynamicCastMap>(MR, Set); assert(State); return State; } template <typename MapTy> ProgramStateRef removeDead(ProgramStateRef State, const MapTy &Map, SymbolReaper &SR) { for (const auto &Elem : Map) if (!SR.isLiveRegion(Elem.first)) State = State->remove<DynamicCastMap>(Elem.first); return State; } ProgramStateRef removeDeadTypes(ProgramStateRef State, SymbolReaper &SR) { return removeDead(State, State->get<DynamicTypeMap>(), SR); } ProgramStateRef removeDeadCasts(ProgramStateRef State, SymbolReaper &SR) { return removeDead(State, State->get<DynamicCastMap>(), SR); } static void printDynamicTypesJson(raw_ostream &Out, ProgramStateRef State, const char *NL, unsigned int Space, bool IsDot) { Indent(Out, Space, IsDot) << "\"dynamic_types\": "; const DynamicTypeMapTy &Map = State->get<DynamicTypeMap>(); if (Map.isEmpty()) { Out << "null," << NL; return; } ++Space; Out << '[' << NL; for (DynamicTypeMapTy::iterator I = Map.begin(); I != Map.end(); ++I) { const MemRegion *MR = I->first; const DynamicTypeInfo &DTI = I->second; Indent(Out, Space, IsDot) << "{ \"region\": \"" << MR << "\", \"dyn_type\": "; if (!DTI.isValid()) { Out << "null"; } else { Out << '\"' << DTI.getType()->getPointeeType().getAsString() << "\", \"sub_classable\": " << (DTI.canBeASubClass() ? "true" : "false"); } Out << " }"; if (std::next(I) != Map.end()) Out << ','; Out << NL; } --Space; Indent(Out, Space, IsDot) << "]," << NL; } static void printDynamicCastsJson(raw_ostream &Out, ProgramStateRef State, const char *NL, unsigned int Space, bool IsDot) { Indent(Out, Space, IsDot) << "\"dynamic_casts\": "; const DynamicCastMapTy &Map = State->get<DynamicCastMap>(); if (Map.isEmpty()) { Out << "null," << NL; return; } ++Space; Out << '[' << NL; for (DynamicCastMapTy::iterator I = Map.begin(); I != Map.end(); ++I) { const MemRegion *MR = I->first; const CastSet &Set = I->second; Indent(Out, Space, IsDot) << "{ \"region\": \"" << MR << "\", \"casts\": "; if (Set.isEmpty()) { Out << "null "; } else { ++Space; Out << '[' << NL; for (CastSet::iterator SI = Set.begin(); SI != Set.end(); ++SI) { Indent(Out, Space, IsDot) << "{ \"from\": \"" << SI->from().getAsString() << "\", \"to\": \"" << SI->to().getAsString() << "\", \"kind\": \"" << (SI->succeeds() ? "success" : "fail") << "\" }"; if (std::next(SI) != Set.end()) Out << ','; Out << NL; } --Space; Indent(Out, Space, IsDot) << ']'; } Out << '}'; if (std::next(I) != Map.end()) Out << ','; Out << NL; } --Space; Indent(Out, Space, IsDot) << "]," << NL; } void printDynamicTypeInfoJson(raw_ostream &Out, ProgramStateRef State, const char *NL, unsigned int Space, bool IsDot) { printDynamicTypesJson(Out, State, NL, Space, IsDot); printDynamicCastsJson(Out, State, NL, Space, IsDot); } } // namespace ento } // namespace clang
424a7af3e5393b082f6782f7a19663e529cbbe7a
337ce318df64cf38c6c8caa265e7280748f992a2
/inheritance/derived.hpp
ee37badf7e44c6dff090e69c1d09c4684461b23f
[]
no_license
cristobalmedinalopez/boost-python-examples
f724ba459ae9959287ce661248fb8e1ae6f743d6
d9beed420ebac32bc6b6d327dbc6b4b972f35037
refs/heads/master
2021-01-10T12:41:36.339808
2016-04-13T08:24:26
2016-04-13T08:24:26
55,055,523
1
0
null
null
null
null
UTF-8
C++
false
false
128
hpp
derived.hpp
#include "base.hpp" class Derived : public Base { public: char const* hello() { return "hello from Derived"; } };
b085aef8e9975515433259de04b7914c4cb5f58c
1cb532b563489ab995ac76cce0e31f3591947c33
/ESCOM/pc/SistemasDistribuidos/general/dist2/Pack Manzano/Proyecto1/6/1.cpp
30257f098ce46ceb5ed2f3b939e48c2145b3e817
[]
no_license
MasterAdminAlex21/sistemas-distribuidos
ceee60bc386e3381db57153f7374e5e18c510234
af51f7e4d49718b2bed75b58f78fdde0b5c8bf5c
refs/heads/master
2022-10-22T04:06:23.635122
2018-12-10T03:39:43
2018-12-10T03:39:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
725
cpp
1.cpp
#include <iostream> #include <vector> #include "Par.h" using namespace std; int main(){ int N = 1000000; vector < Par > criba( N + 1 ); criba[1].setIsPrimo(false); for( int i = 2; i <= N; i++ ){ criba[i].setNumero(i); } for(int i = 2; i*i <= N; ++i) { if(criba[i].isPrimo()) { for(int h = 2; i*h <= N; ++h) criba[i*h].setIsPrimo(false); } } cout << ( criba[1000000].isPrimo() ? "Es primo" : "No es primo" ) << "\n"; cout << ( criba[7919].isPrimo() ? "Es primo" : "No es primo" ) << "\n"; cout << ( criba[2].isPrimo() ? "Es primo" : "No es primo" ) << "\n"; cout << ( criba[999983].isPrimo() ? "Es primo" : "No es primo" ) << "\n"; return 0; }
03028819f469e7fe994aa84af092bdcf46ecc17a
c4b88f63e73271c343660abc0fceaf6aa84ca0bb
/3/ex_3_42.cpp
474455888c2e680e1fce7f36ce41849150a39544
[]
no_license
drliebe/cpp_primer_5th_ed
2275ba0236eb9b27d9842a3c9df86fcd04982bee
a1de6bc40984827957ef12a783969a6ff2557dc9
refs/heads/master
2023-04-04T10:12:00.504841
2021-04-22T22:49:33
2021-04-22T22:49:33
360,699,360
0
0
null
null
null
null
UTF-8
C++
false
false
251
cpp
ex_3_42.cpp
#include <iostream> #include <vector> using std::vector; int main() { vector<int> vec1 = {1,2,3,4,5}; int array1[5]; for(int i=0; i<5; ++i) { array1[i] = vec1[i]; } for(auto i : array1) { std::cout << i << std::endl; } return 0; }
34f40affaf0f491720a1eb9b8030f3efa52c30a2
9694aa3b1dfe0eb9c8690c455490e0a5aa6550df
/src/hvpp/hvpp/vmexit/vmexit_c_wrapper.cpp
a62dd3f907748ba4ffdb28b81dbe56c6aae2715a
[ "MIT", "BSD-2-Clause", "LicenseRef-scancode-free-unknown" ]
permissive
killvxk/hvpp
2d05d9db9c756aea59038c05dca80cda28cc8fdd
2532c76618978ed04e5767b6df8ae1bfe3126a54
refs/heads/master
2020-03-31T11:37:25.749411
2019-02-27T05:25:55
2019-02-27T05:25:55
152,184,218
1
0
MIT
2019-02-27T05:25:56
2018-10-09T03:47:47
C++
UTF-8
C++
false
false
1,899
cpp
vmexit_c_wrapper.cpp
#include "vmexit_c_wrapper.h" #include "hvpp/vcpu.h" namespace hvpp { auto vmexit_c_wrapper_handler::initialize(const c_handler_array_t& c_handlers, void* context) noexcept -> error_code_t { // // Make local copy of the C-handlers. // c_handlers_ = c_handlers; context_ = context; return error_code_t{}; } void vmexit_c_wrapper_handler::destroy() noexcept { } void vmexit_c_wrapper_handler::setup(vcpu_t& vp) noexcept { base_type::setup(vp); // // Enable only 1 EPT table in C-wrapper for now. // The option of having multiple EPTs should be considered // in the future. // vp.ept_enable(); vp.ept().map_identity(); } void vmexit_c_wrapper_handler::handle(vcpu_t& vp) noexcept { auto exit_reason = vp.exit_reason(); auto exit_reason_index = static_cast<int>(exit_reason); auto cpp_handler = handlers_[exit_reason_index]; auto c_handler = c_handlers_[exit_reason_index]; if (c_handler) { // // C-handler has been defined - call that routine. // passthrough_context context; context.passthrough_routine = (passthrough_fn_t)&vmexit_c_wrapper_handler::handle_passthrough; context.context = context_; context.handler_instance = this; context.handler_method = cpp_handler; context.vcpu = &vp; c_handler(&vp, &context); } else { // // C-handler has not been defined - call the pass-through handler. // (this->*cpp_handler)(vp); } } void vmexit_c_wrapper_handler::handle_passthrough(passthrough_context* context) noexcept { // // Fetch the handler instance, method and vcpu_t reference // from the pass-trough context and call that method. // auto handler_instance = context->handler_instance; auto handler_method = context->handler_method; auto& vp = *context->vcpu; (handler_instance->*handler_method)(vp); } }
a43356215a2d0a069f7144799add513266f49d52
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/base/fs/utils/fmifs/src/extend.cxx
172e34b5bc712a5d6d72b5ba888e1e31fe54e1fd
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
2,835
cxx
extend.cxx
#define _NTAPI_ULIB_ #include "ulib.hxx" extern "C" { #include "fmifs.h" }; #include "fmifsmsg.hxx" #include "ifssys.hxx" #include "wstring.hxx" #include "ifsentry.hxx" #include "system.hxx" #include "drive.hxx" VOID Extend( IN PWSTR DriveName, IN BOOLEAN Verify, IN FMIFS_CALLBACK Callback ) /*++ Routine Description: This routine loads and calls the correct DLL to extend the given volume. Currently only NTFS can do this. This is is for either GUI or text mode. Arguments: DriveName - Supplies the DOS style drive name. Verify - Whether or not to verify the extended space Callback - Supplies the necessary call back for communication with the client Return Value: None. --*/ { FMIFS_MESSAGE message; DSTRING extend_string; DSTRING library_name; DSTRING file_system_name; EXTEND_FN extend_function; HANDLE dll_handle; DSTRING ntdrivename; BOOLEAN result; DSTRING dosdrivename; FMIFS_FINISHED_INFORMATION finished_info; DWORD OldErrorMode; // Initialize the message object with the callback function. // Load the file system DLL. // Compute the NT style drive name. if (!message.Initialize(Callback) || !extend_string.Initialize("Extend") || !library_name.Initialize("U") || !file_system_name.Initialize("NTFS") || !library_name.Strcat(&file_system_name) || !(extend_function = (EXTEND_FN) SYSTEM::QueryLibraryEntryPoint(&library_name, &extend_string, &dll_handle)) || !dosdrivename.Initialize(DriveName) || !IFS_SYSTEM::DosDriveNameToNtDriveName(&dosdrivename, &ntdrivename)) { finished_info.Success = FALSE; Callback(FmIfsFinished, sizeof(FMIFS_FINISHED_INFORMATION), &finished_info); return; } // Disable hard-error popups. OldErrorMode = SetErrorMode( SEM_FAILCRITICALERRORS ); // Call chkdsk. result = extend_function(&ntdrivename, &message, Verify ); // Enable hard-error popups. SetErrorMode( OldErrorMode ); SYSTEM::FreeLibraryHandle(dll_handle); finished_info.Success = result; Callback(FmIfsFinished, sizeof(FMIFS_FINISHED_INFORMATION), &finished_info); }
0ba47cad3b89ecd236f2d60fd57ef69efcf51626
b4b4e324cbc6159a02597aa66f52cb8e1bc43bc1
/C++ code/Uva Online Judge/Q10462.cpp
edf2310db2324f248f2b5c280c04255118ba8ef7
[]
no_license
fsps60312/old-C-code
5d0ffa0796dde5ab04c839e1dc786267b67de902
b4be562c873afe9eacb45ab14f61c15b7115fc07
refs/heads/master
2022-11-30T10:55:25.587197
2017-06-03T16:23:03
2017-06-03T16:23:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,107
cpp
Q10462.cpp
#include<cstdio> #include<cstdlib> #include<vector> using namespace std; struct pairtype { int x,y,z; }; pairtype S[200],tmp[200]; void rangeS(int a,int b) { if(a==b) return; int mid=(a+b)/2; rangeS(a,mid); rangeS(mid+1,b); int c=a,d=mid+1; for(int i=a;i<=b;i++) { if(d>b||(c<=mid&&S[c].z<S[d].z)) tmp[i]=S[c++]; else tmp[i]=S[d++]; } for(int i=a;i<=b;i++) S[i]=tmp[i]; } int T,v,e; vector<int> side[100]; vector<int> onloop; int anc[100]; bool vis[100]; int fin(int a) { if(anc[a]==a) return a; return anc[a]=fin(anc[a]); } bool connect(int a,int b) { return fin(a)==fin(b); } void build(int a) { side[S[a].x].push_back(S[a].y); side[S[a].x].push_back(S[a].z); side[S[a].y].push_back(S[a].x); side[S[a].y].push_back(S[a].z); anc[fin(S[a].x)]=fin(S[a].y); } int countcost() { int ans=0; for(int i=0;i<v;i++) { for(int j=1;j<side[i].size();j+=2) { ans+=side[i][j]; } } return ans/2; } int largest() { int ans=0; for(int i=0;i<onloop.size();i++) { if(onloop[i]>ans) ans=onloop[i]; } return ans; } bool dfs(int a,int b) { //printf(" %d %d\n",a,b); if(vis[a]) return false; vis[a]=true; if(a==b) { //printf("find\n"); return true; } for(int i=0;i<side[a].size();i+=2) { bool j=dfs(side[a][i],b); if(j) { //printf("%d\n",side[a][i+1]); onloop.push_back(side[a][i+1]); return true; } } return false; } int main() { freopen("in.txt","r",stdin); scanf("%d",&T); for(int kase=1;kase<=T;kase++) { scanf("%d%d",&v,&e); printf("%d %d\n",v,e); for(int i=0;i<v;i++) { side[i].clear(); anc[i]=i; vis[i]=false; } onloop.clear(); for(int i=0;i<e;i++) { scanf("%d%d%d",&S[i].x,&S[i].y,&S[i].z); S[i].x--,S[i].y--; } if(e) rangeS(0,e-1); int now=0,i; for(i=0;i<e&&now!=v-1;i++) { if(!connect(S[i].x,S[i].y)) { build(i); now++; } } if(now<v-1) printf("Case #%d : No way\n",kase); else if(i==e) printf("Case #%d : No second way\n",kase); else { //printf("pass\n"); dfs(S[i].x,S[i].y); printf("Case #%d : %d\n",kase,countcost()+S[i].z-largest()); } } return 0; }
5002794dfccf8f1078137e934b3c4b2a27e388ac
9d913e74d1eca141be73cad3e039c80e88d49ba4
/2IO/3Visual/Code/LED/LED.ino
739bc6c27bc25227a52e9c1a9fd947ee81af9957
[ "Apache-2.0" ]
permissive
trombonehero/grove-examples
f05caf60a91bf7364bd4cb23e9fa0202d9607e4d
534f6246cb56ae3003b6098f61f82e0a44d4eba8
refs/heads/master
2020-01-19T21:23:53.285275
2017-05-10T01:31:28
2017-05-10T01:31:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
619
ino
LED.ino
int sensor = A0; int led = 5; void setup() { pinMode(sensor, INPUT); //Setup sensor pinMode(led, OUTPUT); //Setup LED Serial.begin(9600); //Set computer serial output to 9600 bits per second(make sure manager is the same) } void loop() { int brightness = analogRead(sensor); //Get reading Serial.println(brightness); int reverse = (1023-brightness); //For Grove, 1023 = 780. More light = higher reading, therefore need reverse int range = map(reverse, 0, 1023, 0, 255); //For Grove, 1023 = 780. Changes the range of the readings to work with an LED analogWrite(led, range); }
ac13d1be0d9487a72b01f9ea338a3f65143ce2cb
54f352a242a8ad6ff5516703e91da61e08d9a9e6
/Source Codes/AtCoder/arc096/B/2394871.cpp
4854dee245b0a4934fcb7ac2c5b3e71ac7327b0b
[]
no_license
Kawser-nerd/CLCDSA
5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb
aee32551795763b54acb26856ab239370cac4e75
refs/heads/master
2022-02-09T11:08:56.588303
2022-01-26T18:53:40
2022-01-26T18:53:40
211,783,197
23
9
null
null
null
null
UTF-8
C++
false
false
1,144
cpp
2394871.cpp
#include <cstdio> #include <algorithm> using namespace std; #define ll long long #define N 200100 struct node { ll num; int id; bool operator < (const node& x) const { return x.num<num; } }g[N]; ll c,ans,now; ll f[N],x[N]; int n,v[N]; /*ll read() { int c=getchar(); ll x=0; while (c<'0' || c>'9') c=getchar(); while (c>='0' && c<='9') x=x*10+c-'0',c=getchar(); return x; }*/ int main() { scanf("%d%lld",&n,&c); for (int i=1;i<=n;i++) scanf("%lld%d",&x[i],&v[i]); x[n+1]=c; for (int i=n;i;i--) g[i].num=g[i+1].num+v[i]-(x[i+1]-x[i]),g[i].id=i; //g[n+1].num=0; g[n+1].id=n+1; sort(g+1,g+n+1); int cur=1; ans=max(ans,g[1].num); for (int i=1;i<=n;i++) { while (g[cur].id<=i && cur<=n) cur++; now+=v[i]-2*(x[i]-x[i-1]); ans=max(ans,now+max(0ll,g[cur].num)); } for (int i=1;i<=n;i++) g[i].num=g[i-1].num+v[i]-(x[i]-x[i-1]),g[i].id=i; sort(g+1,g+n+1); cur=1; now=0; ans=max(ans,g[1].num); for (int i=n;i;i--) { while (g[cur].id>=i && cur<=n) cur++; now+=v[i]-2*(x[i+1]-x[i]); ans=max(ans,now+max(0ll,g[cur].num)); } printf("%lld\n",ans); return 0; }
9de031e891e48002a7aaf95bcc5eddc609403fe8
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/third_party/WebKit/public/platform/modules/presentation/WebPresentationConnectionClient.h
5a7d976f5280c3a2f7f4efb145121f7ceac6146b
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
838
h
WebPresentationConnectionClient.h
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef WebPresentationConnectionClient_h #define WebPresentationConnectionClient_h #include "public/platform/WebString.h" #include "public/platform/WebURL.h" namespace blink { enum class WebPresentationConnectionState { Connected = 0, Closed, Terminated, }; enum class WebPresentationConnectionCloseReason { Error = 0, Closed, WentAway }; // The implementation the embedder has to provide for the Presentation API to // work. class WebPresentationConnectionClient { public: virtual ~WebPresentationConnectionClient() {} virtual WebString getId() = 0; virtual WebURL getUrl() = 0; }; } // namespace blink #endif // WebPresentationConnectionClient_h
929f4e463ec1c88659f365ba09b043da16b9e04a
0d9b5d7d3f6cceed12729e57b98db52b8f1d7b8f
/汇编/stack.h
abb5cdee1a29dab6829b41d642bf374648683d5a
[]
no_license
695573425/teach
1d8dc041a130227e31404b602baf01a12f08cd9a
825a4d7ccf562708a02536efb0246aa78041bac9
refs/heads/master
2021-05-14T10:13:52.513262
2018-01-05T05:14:33
2018-01-05T05:14:33
108,815,615
0
0
null
null
null
null
UTF-8
C++
false
false
1,552
h
stack.h
#pragma once #include <algorithm> #include "myTools.h" template <typename T> class stack { public: stack(int initialCapacity = 8); stack(const stack & s) { capacity = s.capacity; arr = new T[capacity]; _top = s._top; copy(s.begin(), s.end(), begin()); } stack(stack && s) { arr = s.arr; capacity = s.capacity; _top = s._top; s.arr = nullptr; } ~stack(); bool empty() const { return _top == 0; } bool full() const { return _top == capacity; } int size() const { return _top; } T & top() { return arr[_top - 1]; } void pop(T & theElement) { theElement = arr[--_top]; arr[_top].~T(); } void pop() { arr[--_top].~T(); } void push(const T& theElement) { if (full()) { arr = change_length_of_1Darray(arr, capacity, 2 * capacity); capacity *= 2; } arr[_top++] = theElement; } T * begin() { return arr; } T * end() { return arr + _top; } stack & operator=(stack && s) { if (this == &s) return *this; delete[] arr; arr = s.arr; capacity = s.capacity; _top = s._top; s.arr = nullptr; return *this; } stack & operator=(const stack & s) { if (this == &s) return *this; delete[] arr; arr = new T[s.capacity]; _top = s._top; capacity = s.capacity; for (int i = 0; i != s._top; i++) arr[i] = s.arr[i]; return *this; } private: T * arr; int _top; int capacity; }; template<typename T> inline stack<T>::stack(int initialCapacity) { capacity = initialCapacity; _top = 0; arr = new T[capacity]; } template<typename T> inline stack<T>::~stack() { delete[] arr; }
74a7d678a755e782d3fad9f976e992a420ab8e76
ba23f7d006377df5c14ce8c9451f066c0b1aba60
/4948.cpp
c1ec6761d381c4f8ace4451fab6ad8f6354d7504
[]
no_license
holicAZ/AlgorithmStudy
89a1ad5b95e85f582e0124c130c1a1e88ac73eb9
8259d60f5ced234d6170b720790e6854a5cc6b63
refs/heads/master
2023-03-23T13:51:11.467640
2021-03-24T14:22:58
2021-03-24T14:22:58
278,343,793
0
0
null
null
null
null
UTF-8
C++
false
false
524
cpp
4948.cpp
#include <iostream> #include <cstring> using namespace std; bool check[123456*2]; int main(void) { int n; while (true) { int cnt = 0; memset(check, false, sizeof(check)); cin >> n; if (n == 0) break; if (n == 1) { cout << 1 << endl; continue; } for (int i = 2; i <= 2 * n; i++) { if (check[i]) continue; for (int j = i * 2; j <= 2 * n; j += i) { check[j] = true; } } for (int i = n+1; i <= 2 * n; i++) { if (!check[i]) cnt++; } cout << cnt << "\n"; } return 0; }
9f5727980b0d6823d8132ece3fa5a1a4b68db228
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
/app/src/main/cpp/dir7941/dir29315/dir29712/dir29713/dir29714/file29852.cpp
253f206c6990c03bfc7d2f1de6f225e972ff8fef
[]
no_license
tgeng/HugeProject
829c3bdfb7cbaf57727c41263212d4a67e3eb93d
4488d3b765e8827636ce5e878baacdf388710ef2
refs/heads/master
2022-08-21T16:58:54.161627
2020-05-28T01:54:03
2020-05-28T01:54:03
267,468,475
0
0
null
null
null
null
UTF-8
C++
false
false
115
cpp
file29852.cpp
#ifndef file29852 #error "macro file29852 must be defined" #endif static const char* file29852String = "file29852";
313a24748193ef4b49e67a7e7555162915dca259
809bbbddf5f4abdf8f85a6591df61fcf11f52ce0
/11_01_resource/src/libs/libplayer/player_component.cpp
80328ced2de29f4c2adf09f5898dd9dc74d79c3b
[ "MIT" ]
permissive
KMUS1997/GameBookServer
542df52ac3f7cb1443584394e3d8033dbb2d29e3
6f32333cf464088a155f0637f188acd452b631b7
refs/heads/master
2023-03-15T18:52:23.253198
2020-06-09T01:58:36
2020-06-09T01:58:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
31
cpp
player_component.cpp
#include "player_component.h"
8dc3084909850a4654b0a3350aa5f2a635574ab7
e7cb043173ea0a5f451bafca0bfcdb08b542b7d7
/source/IO/FloatVolume.cpp
40b416620ccf1349f9dbffe31657cdb4dbc39c50
[]
no_license
VisualIdeation/Toirt-Samhlaigh
aa0201c3762798d4186727ef192cc55855a11fef
6fad5ff0f43cc32c02f2d9a33da1e00f064c8924
refs/heads/master
2021-01-19T05:36:16.037374
2011-10-20T16:47:04
2011-10-20T16:47:04
2,125,754
2
0
null
null
null
null
UTF-8
C++
false
false
2,561
cpp
FloatVolume.cpp
/* * FloatVolume.cpp - Methods for FloatVolume class. * * Author: Patrick O'Leary * Created: October 19, 2007 * Copyright: 2007 */ /* Vrui includes */ #include <Math/Math.h> #include <Misc/File.h> #include <DATA/Volume.h> #include <IO/FloatVolume.h> /* * FloatVolume - Constructor for FloatVolume class. */ FloatVolume::FloatVolume() { } /* * ~FloatVolume - Destructor for FloatVolume class. */ FloatVolume::~FloatVolume() { } /* * readFloatVolume - Read a float volume volume renderering data set (.fvol). * * parameter filename - const char* * parameter volume - Volume */ void FloatVolume::readFloatVolume(const char* filename, Volume* volume) { /* Open the volume file: */ Misc::File floatVolumeFile(filename, "rb", Misc::File::BigEndian); /* Read the volume file header: */ int size[3]; floatVolumeFile.read(size, 3); volume->setSize(size); int borderSize=floatVolumeFile.read<int>(); volume->setBorderSize(borderSize); /* Set the voxel block's position and size, and the slice center to the block's center: */ Point origin=Point::origin; Size extent; Point center; for (int i=0; i<3; ++i) { extent[i]=Scalar(floatVolumeFile.read<float>()); center[i]=origin[i]+extent[i]*Scalar(0.5); } volume->setOrigin(origin); volume->setExtent(extent); volume->setVolumeBox(); volume->setCenter(center); /* Create a voxel array: */ int numberOfVoxels=(size[0]+2*borderSize)*(size[1]+2*borderSize)*(size[2]+2*borderSize); volume->setNumberOfVoxels(numberOfVoxels); FloatVoxel* floatVoxelsBase=new FloatVoxel[numberOfVoxels]; floatVolumeFile.read(floatVoxelsBase, numberOfVoxels); volume->setFloatVoxelsBase(floatVoxelsBase); /* Determine the voxel data's value range: */ float _min, _max; _min=_max=floatVoxelsBase[0]; for (int i=1; i<numberOfVoxels; ++i) { if (_min>floatVoxelsBase[i]) _min=floatVoxelsBase[i]; else if (_max<floatVoxelsBase[i]) _max=floatVoxelsBase[i]; } /* Convert the float data to unsigned char: */ Voxel* voxelsBase=new Voxel[numberOfVoxels]; for (int i=0; i<numberOfVoxels; ++i) voxelsBase[i]=(unsigned char)Math::floor((Scalar(floatVoxelsBase[i])-Scalar(_min))*Scalar(255)/(Scalar(_max)-Scalar(_min)) +Scalar(0.5)); volume->setByteVoxelsBase(voxelsBase); /* Calculate the address of the voxel block: */ Voxel* voxels=voxelsBase+borderSize; int increments[3]; increments[2]=1; for (int i=2; i>0; --i) { increments[i-1]=increments[i]*(size[i]+2*borderSize); voxels+=borderSize*increments[i-1]; } volume->setIncrements(increments); volume->setVoxels(voxels); }
ece116723a3789ebfdf434aac3e95536a0eb6553
95b28b2804574e4d20239db53634a493a495b4d0
/test2/EntityRenderer.h
8bf25e5efcfd8265bd6d09d1d4e0c124ed3498b0
[]
no_license
avitzdaka1/openGL-cpp-graphics
54cfa4223342c3382304c9d98edd6cbd48f258c4
6e09ed15653cedeb3e3f6fad8cb4bda9426b4754
refs/heads/master
2020-05-13T17:17:28.943047
2019-03-27T22:28:41
2019-03-27T22:28:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
411
h
EntityRenderer.h
#pragma once #include "StaticShader.h" #include "Maths.h" class EntityRenderer { private: StaticShader shader; public: EntityRenderer(StaticShader shader, glm::mat4); void render(std::map<TexturedModel, std::vector<Entity>>); void prepareTexturedModel(TexturedModel model); void unbindTexturedModel(); void prepareInstance(Entity); static void enableCulling(); static void disableCulling(); };
8db599a8e4acc09ea38641d4dee12d3d5abcd396
bdc579c89ca1ae028437ce37411434cca6dfb69c
/src/SDLstuff/main.cpp
4185052eed267b32da25f15f9f2aa9306859a191
[]
no_license
portsmouth/the-sentinel-game
2e4ad5ee5a38ffeda8f3928b5755a85c8443a926
16e452f84a2ee701e714e423b5c1789473e525fe
refs/heads/master
2023-08-12T19:30:38.957645
2016-09-07T11:32:59
2016-09-07T11:32:59
36,428,534
5
1
null
null
null
null
UTF-8
C++
false
false
301
cpp
main.cpp
#include "Game.h" #include "SDL/SDL.h" int main(int argc, char *argv[]) { //create Game object, which will instantiate everything else too Game::Instance()->mainLoop(); //exit game SDL_Quit(); return 0; } /************************************************************************/
89497dbd36ad9ad72c8f13bcff801445614ebac9
ee40e669a2d60b757a22d2e97bd443f6f5c86c4b
/flowitem.h
a68db62c54485c089b10809b903080ab81087fb0
[ "MIT" ]
permissive
paule32/RETRO_BuildSet
c8c044c4475f727a52a3a18b5265b55aff563aa2
a38375e871d3e623b388d8e1f247f3980dcb48b8
refs/heads/master
2020-12-10T06:10:09.479044
2020-01-13T05:56:28
2020-01-13T05:56:28
233,521,240
0
0
null
null
null
null
UTF-8
C++
false
false
353
h
flowitem.h
#ifndef FLOWITEM_H #define FLOWITEM_H #include <QWidget> #include <QVariant> #include <QGraphicsItem> #include <QGraphicsPixmapItem> class FlowPixmapItem: public QGraphicsPixmapItem { public: FlowPixmapItem(QGraphicsPixmapItem * parent = nullptr); // itemChange(GraphicsPixmapItemChange change, const QVariant &value); }; #endif // FLOWITEM_H
21bb523331729fe01b2b8e294f42f7baecba29d2
bd73e2da8c721f65ee8658f01b85a30ea52de561
/CSES/Dynamic Programming/Dice_combinations.cpp
d17bd9b28559abd06f86feb43656d041e6fb4c89
[]
no_license
npsnishant/C-DSA
e02e6e450a5bf0d541b3fe40b5b517a7773c67d6
5c91ed8bf8c69bade06126b0b4330660026b81fc
refs/heads/master
2023-08-04T15:12:26.173462
2021-09-17T16:11:23
2021-09-17T16:11:23
407,604,010
0
0
null
null
null
null
UTF-8
C++
false
false
404
cpp
Dice_combinations.cpp
#include <iostream> #include <bits/stdc++.h> #define mod 1000000007 using namespace std; int main(){ long long n; cin>>n; std::vector<int> dp(n+1, 0); //dp[i] = Number of valid ways of throwing the dice such that the sum = i. dp[0] = 1; for(int i=1;i<=n;i++){ for(int x=1; x<=6;x++){ if(x>i){ break; } dp[i] = (dp[i] + dp[i-x]) % mod; } } cout<<dp[n]<<endl; return 0; }
0fb2fea81b29671d52d80cea8a39f37f1274250f
ff5c1d61409b0d462463adce8b9a0889f662d107
/bindings/python/src/OpenSpaceToolkitMathematicsPy/CurveFitting/Interpolator.cpp
54db442e3c39a9cc1282ec2ec4d5d1e5d92342d7
[ "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause", "MPL-2.0" ]
permissive
open-space-collective/open-space-toolkit-mathematics
ff1eb9a1c6baae5f538c434e646e11635f4d773b
c441c8ceb8f9fef3c7bb1981e031a83b68960020
refs/heads/main
2023-09-01T04:59:44.874092
2023-08-31T18:24:41
2023-08-31T18:24:41
136,834,880
10
3
Apache-2.0
2023-09-14T10:07:47
2018-06-10T18:35:03
C++
UTF-8
C++
false
false
948
cpp
Interpolator.cpp
/// Apache License 2.0 #include <OpenSpaceToolkitMathematicsPy/CurveFitting/Interpolator/BarycentricRational.cpp> #include <OpenSpaceToolkitMathematicsPy/CurveFitting/Interpolator/CubicSpline.cpp> #include <OpenSpaceToolkitMathematicsPy/CurveFitting/Interpolator/Linear.cpp> inline void OpenSpaceToolkitMathematicsPy_CurveFitting_Interpolator(pybind11::module& aModule) { // Create "interpolator" python submodule auto interpolator = aModule.def_submodule("interpolator"); // Add __path__ attribute for "interpolator" submodule interpolator.attr("__path__") = "ostk.mathematics.curve_fitting.interpolator"; // Add objects to python "interpolator" submodules OpenSpaceToolkitMathematicsPy_CurveFitting_Interpolator_BarycentricRational(interpolator); OpenSpaceToolkitMathematicsPy_CurveFitting_Interpolator_CubicSpline(interpolator); OpenSpaceToolkitMathematicsPy_CurveFitting_Interpolator_Linear(interpolator); }
7bb1579655a2199eb1e34585b1d8ea165e8ae90f
b3ce8e3d4eb65247020b52e4c384e4b2c34a1dbe
/pthread/productor.cpp
bc82afb48053a9fbe2e7149a1b3de26898739292
[]
no_license
yulongli6/linux
a29bc5164d71ef50a0f345ad81f9780d339cb337
a44c2e49d42cdeb4295a63832e77a0a7d3ee6c05
refs/heads/master
2020-03-31T12:49:39.886033
2019-04-06T12:58:15
2019-04-06T12:58:15
152,231,007
0
0
null
null
null
null
UTF-8
C++
false
false
2,393
cpp
productor.cpp
#include <iostream> #include <queue> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <pthread.h> #define QUEUE_MAX 10 class BlockQueue { private: std::queue<int> _list; int _cap; pthread_mutex_t _mutex; pthread_cond_t _full; pthread_cond_t _empty; public: BlockQueue(int cap = QUEUE_MAX):_cap(cap) { pthread_mutex_init(&_mutex, NULL); pthread_cond_init(&_full, NULL); pthread_cond_init(&_empty, NULL); } ~BlockQueue() { pthread_mutex_destroy(&_mutex); pthread_cond_destroy(&_full); pthread_cond_destroy(&_empty); } bool QueuePush(int data) { pthread_mutex_lock(&_mutex); if(_cap == _list.size()) { printf("-------------------full\n"); pthread_cond_wait(&_full, &_mutex); } _list.push(data); pthread_mutex_unlock(&_mutex); pthread_cond_signal(&_empty); return true; } bool QueuePop(int *data) { pthread_mutex_lock(&_mutex); if(_list.empty()) { printf("-------------------empty\n"); pthread_cond_wait(&_empty, &_mutex); } *data = _list.front(); _list.pop(); pthread_mutex_unlock(&_mutex); pthread_cond_signal(&_full); return true; } }; void *productor(void *arg) { BlockQueue *q = (BlockQueue*)arg; int i = 0; while(1) { sleep(1); printf("put data:%d\n", i); q->QueuePush(i++); } return NULL; } void *consumer(void *arg) { BlockQueue *q = (BlockQueue*)arg; while(1) { sleep(1); int data; q->QueuePop(&data); printf("get data:%d\n", data); } return NULL; } int main() { pthread_t tid1, tid2; BlockQueue q; int ret = pthread_create(&tid1, NULL, productor, (void*)&q); if (ret != 0) { printf("create pthread error\n"); return -1; } ret = pthread_create(&tid2, NULL, consumer, (void*)&q); if (ret != 0) { printf("create pthread error\n"); return -1; } pthread_join(tid1, NULL); pthread_join(tid2, NULL); return 0; } 0x00, 0x40, 0x00, 0x40, 0x78, 0xA0, 0x49, 0x10, 0x4A, 0x08, 0x4C, 0x06, 0x4B, 0xF8, 0x48, 0x00, 0x48, 0x00, 0x4B, 0xF8, 0x7A, 0x08, 0x4A, 0x08, 0x02, 0x08, 0x02, 0x08, 0x03, 0xF8, 0x02, 0x08,
66573985fbc3547ab3353628c9fa36c65d874682
2721933a740591823a84f8d5a969d9408cadb967
/zhaoyun/Classes/GameScene.h
b5ac122e36b93b4d7f128bd896aaf2bcebd69e66
[]
no_license
Iakgun/First-Game
0e3731213b9e26a015e40d0b5b0e47bbf10aac5c
2120042a94b9afaec91d6cefc257a410a647a1cc
refs/heads/master
2020-12-25T12:47:05.969108
2014-08-08T06:48:52
2014-08-08T06:48:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
253
h
GameScene.h
#pragma once #include "GameLayer.h" #include "cocos2d.h" class GameScene : public cocos2d::CCScene { public: GameScene(void); ~GameScene(void); virtual bool init(); CREATE_FUNC(GameScene); CC_SYNTHESIZE(GameLayer*, _gameLayer, GameLayer); };
f1d6f756abc63c86d3e06b76bab7e9b0af50c177
bcde28e271c8435ddc989a9d3af4756a93b850fe
/Playfield.h
c1364f6a8f9f64d619975fb2246e337d482aeccf
[]
no_license
aggrotech/tetris
c1113dc1dc69b88547851d2cba7fc841215d8c29
dc83982521c59c8005fdeb48cb24b2514fe8d8fa
refs/heads/master
2020-05-14T11:12:28.436155
2013-02-21T04:02:52
2013-02-21T04:02:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
835
h
Playfield.h
#pragma once #include <vector> namespace Aggrotech { // Forward decl. class Cell; class Tetrimino; class Playfield { public: static const int DefaultWidth; static const int DefaultHeight; Playfield(unsigned int width, unsigned int height); ~Playfield(); unsigned int GetWidth(); unsigned int GetHeight(); Cell *GetCellAt(unsigned int x, unsigned int y); Cell *SetAndGetPreviousCellAt(unsigned int x, unsigned int y, Cell *cell); void SetCellsFromTetrimino(Tetrimino &tetrimino); bool IsTetriminoInCollision(Tetrimino &tetrimino); int ClearFilledAndReturnAffectedRows(); void DropCells(); private: std::vector< Cell* > cells; unsigned int width; unsigned int height; }; }
cf981f45795e845c50353893bd340df5ceafc4ef
05a00a68121c2cfc0894d50a4f46cc3e89d62a4a
/CastleVania/CastleVania/Whip.cpp
de063b4d718382d42d7344427024d4b33e787809
[]
no_license
sipv1612/CastleVania-Clone
19bc4dbf2161e26778f23686f627a91e2c257b2a
09ef969e215bcbce86e9b9186a6defecc869a089
refs/heads/master
2021-01-22T19:13:59.180178
2017-03-16T09:48:14
2017-03-16T09:48:14
85,176,940
0
0
null
null
null
null
UTF-8
C++
false
false
3,868
cpp
Whip.cpp
#include "Whip.h" Whip*Whip::instance = 0; Whip::Whip() :MovableObject() { _listAction = SpriteManager::GetInstance()->listAnimation[SpriteWhip]; _collType = CollWhip; position.X = 0; position.Y = 0; oldX = 0; oldY = 0; vx = 0; vy = 0; width = 9; height = 24; ay = 0; _direction = RIGHT; _curState = 0; iDamage = 1; _curWhipAction = state1; _curType = Chain_Whip; delayIndexChange = new GameTime(1 / TIME_INDEX_CHANGE); } Whip * Whip::GetInstance() { if (instance == 0) { instance = new Whip(); } return instance; } void Whip::setType(WhipType _type) { _curType = _type; switch (_curType) { case Vampire_Killer: iDamage = 1; break; case Chain_Whip: iDamage = 2; break; case Morning_Star: iDamage = 2; break; default: break; } } void Whip::Run(bool Active, int SimonX, int SimonY, int curFrame, Direction direction) { if (!Active) { alive = false; return; } vy = Gametime * GRAVITY; alive = true; _direction = direction; setPosition(SimonX, SimonY, curFrame); changeType(); MovableObject::Run(); } void Whip::setPosition(int SimonX, int SimonY, int Frame) { if(_direction == RIGHT) { if (Frame == 0) { if (_curType == Vampire_Killer) { _curWhipAction = state1; _curFrame = 0; } if (_curType == Chain_Whip) { _curWhipAction = state1; _curFrame = 1; } if (_curType == Morning_Star) { _curWhipAction = state1; _curFrame = 2; } width = 9; height = 24; position.X = SimonX - 15; position.Y = SimonY + 7; } if (Frame == 1) { if (_curType == Vampire_Killer) { _curWhipAction = state2; _curFrame = 0; } if (_curType == Chain_Whip) { _curWhipAction = state2; _curFrame = 1; } if (_curType == Morning_Star) { _curWhipAction = state2; _curFrame = 2; } width = 16; height = 18; position.X = SimonX - 15; position.Y = SimonY + 3; } if (Frame == 2) { if (_curType == Vampire_Killer) { _curWhipAction = state3_1; _curFrame = 0; width = 25; height = 7; position.X = SimonX + 22; position.Y = SimonY + 7; } if (_curType == Chain_Whip) { _curWhipAction = state3_2; _curFrame = 0; width = 36; height = 6; position.X = SimonX + 17; position.Y = SimonY + 9; } if (_curType == Morning_Star) { _curWhipAction = state3_3; _curFrame = 0; width = 44; height = 6; position.X = SimonX + 17; position.Y = SimonY + 9; } } } else { if (Frame == 0) { if (_curType == Vampire_Killer) { _curWhipAction = state1; _curFrame = 0; } if (_curType == Chain_Whip) { _curWhipAction = state1; _curFrame = 1; } if (_curType == Morning_Star) { _curWhipAction = state1; _curFrame = 2; } width = 9; height = 24; position.X = SimonX + 20; position.Y = SimonY + 7; } if (Frame == 1) { if (_curType == Vampire_Killer) { _curWhipAction = state2; _curFrame = 0; } if (_curType == Chain_Whip) { _curWhipAction = state2; _curFrame = 1; } if (_curType == Morning_Star) { _curWhipAction = state2; _curFrame = 2; } width = 16; height = 18; position.X = SimonX + 15; position.Y = SimonY + 3; } if (Frame == 2) { if (_curType == Vampire_Killer) { _curWhipAction = state3_1; _curFrame = 0; width = 25; height = 7; position.X = SimonX - 32; position.Y = SimonY + 7; } if (_curType == Chain_Whip) { _curWhipAction = state3_2; _curFrame = 0; width = 36; height = 6; position.X = SimonX - 37; position.Y = SimonY + 9; } if (_curType == Morning_Star) { _curWhipAction = state3_3; _curFrame = 0; width = 44; height = 6; position.X = SimonX - 45; position.Y = SimonY + 9; } } } }
994b29e408c607ffc268f83f1f8f778d23ecf0d1
ad4a3300a1720a0c4ad7b97e2b8cbaf670b69146
/codeforces/527_div3/527C.cpp
c77794ebefcc8098793ed64944fbccf5a6d668aa
[]
no_license
arpituppal/competitive-programming-codes
4cf98279ffefb437b40fd412f4cbda3f519d4f3a
ca543259e6e8fd8b1b963ca5a54fccea4083860c
refs/heads/master
2022-12-08T11:23:21.927150
2020-08-29T21:20:19
2020-08-29T21:20:19
104,647,687
0
0
null
null
null
null
UTF-8
C++
false
false
3,953
cpp
527C.cpp
#include <iostream> #include <cstdio> #include <cstdlib> #include <cmath> #include <queue> #include <algorithm> #include <vector> #include <cstring> #include <stack> #include <cctype> #include <utility> #include <map> #include <string> #include <climits> #include <set> #include <sstream> #include <utility> #include <ctime> #include <cassert> #include <fstream> using namespace std; typedef long long LL; #define MS(A) memset(A, 0, sizeof(A)) #define MSV(A,a) memset(A, a, sizeof(A)) #define MAX(a,b) ((a >= b) ? (a) : (b)) #define MIN(a,b) ((a >= b) ? (b) : (a)) #define ABS(a) (((a) > 0) ? (a) : (-a)) #define MP make_pair #define PB push_back #define getcx getchar_unlocked #define INF (int(1e9)) #define INFL (LL(1e18)) #define EPS 1e-12 #define chkbit(s, b) (s & (1<<b)) #define setbit(s, b) (s |= (1<<b)) #define clrbit(s, b) (s &= ~(1<<b)) map<string, char> premap; map<string, char> suffmap; vector<string> vec[100]; vector<string> inpstrings; int validate(string s, int n) { int i; for(i = 1; i <=n - 1; i++) { string s1 = vec[i][0]; string s2 = vec[i][1]; //find if s1 is prefix if(s.substr(0,i).compare(s1) == 0) { premap[s1] = 'P'; //now check if s2 is suffix if(s.substr(n-i).compare(s2) != 0) { return 0; } suffmap[s2] = 'S'; } else if(s.substr(n-i).compare(s1) == 0) { //find if s1 is suffix suffmap[s1] = 'S'; //find if s2 is prefix if(s.substr(0,i).compare(s2) != 0) { return 0; } premap[s2] = 'P'; } else { return 0; } } return 1; } void printtoutput() { int i; for(i = 0 ; i < inpstrings.size(); i++) { if(premap.find(inpstrings[i]) != premap.end()) { printf("P"); premap.erase(premap.find(inpstrings[i])); } else { printf("S"); suffmap.erase(suffmap.find(inpstrings[i])); } //printf("%c", ansmap.find(inpstrings[i])->second); } printf("\n"); } int main() { set<string> possstrings; set<string>::iterator it; string s; int n, i, l, flag = 0; scanf("%d", &n); for(i = 0 ; i < (2*n-2) ;i++) { cin>>s; l = s.length(); vec[l].PB(s); inpstrings.PB(s); } premap[vec[n-1][0]] = 'P'; suffmap[vec[1][0]] = 'S'; suffmap[vec[n-1][1]] = 'S'; premap[vec[1][1]] = 'P'; if(n > 2 && validate(vec[n-1][0] + vec[1][0], n) == 1) { printtoutput(); return 0; } premap.clear(); suffmap.clear(); premap[vec[n-1][0]] = 'P'; suffmap[vec[1][1]] = 'S'; suffmap[vec[n-1][1]] = 'S'; premap[vec[1][0]] = 'P'; if(validate(vec[n-1][0] + vec[1][1], n) == 1) { printtoutput(); return 0; } premap.clear(); suffmap.clear(); premap[vec[n-1][1]] = 'P'; suffmap[vec[1][0]] = 'S'; suffmap[vec[n-1][0]] = 'S'; premap[vec[1][1]] = 'P'; if(validate(vec[n-1][1] + vec[1][0], n) == 1) { printtoutput(); return 0 ; } premap.clear(); suffmap.clear(); premap[vec[n-1][1]] = 'P'; suffmap[vec[1][1]] = 'S'; suffmap[vec[n-1][0]] = 'S'; premap[vec[1][0]] = 'P'; if(n > 2 && validate(vec[n-1][1] + vec[1][1], n) == 1) { printtoutput(); return 0; } premap.clear(); suffmap.clear(); premap[vec[n-1][1]] = 'P'; suffmap[vec[1][1]] = 'S'; suffmap[vec[n-1][0]] = 'S'; premap[vec[1][0]] = 'P'; if(n > 2 && validate(vec[1][0] + vec[n-1][0], n) == 1) { printtoutput(); return 0; } premap.clear(); suffmap.clear(); suffmap[vec[n-1][1]] = 'S'; suffmap[vec[1][1]] = 'S'; premap[vec[n-1][0]] = 'P'; premap[vec[1][0]] = 'P'; if(validate(vec[1][0] + vec[n-1][1], n) == 1) { printtoutput(); return 0; } premap.clear(); suffmap.clear(); premap[vec[n-1][1]] = 'P'; premap[vec[1][1]] = 'P'; suffmap[vec[n-1][0]] = 'S'; suffmap[vec[1][0]] = 'S'; if(validate(vec[1][1] + vec[n-1][0], n) == 1) { printtoutput(); return 0; } premap.clear(); suffmap.clear(); suffmap[vec[n-1][1]] = 'S'; premap[vec[1][1]] = 'P'; premap[vec[n-1][0]] = 'P'; suffmap[vec[1][0]] = 'S'; if(n > 2 && validate(vec[1][1] + vec[n-1][1], n) == 1) { printtoutput(); return 0; } return 0; }
3dcf9636e5c3b99d3d5ee3bf43d81d5868851ecc
ad753cad14f390332abbdde7eaf788320576a3b7
/Semester 2/Computer Programming/Lab/Lab 4/Question1 164305.cpp
86a26e33384f9403775ce31c99d66c9bfc6fbc9a
[]
no_license
Shaheryar-Ali/FAST-NUCES-code
e93770098488a6e8717c8ff1e1fdd993ef4b4395
1cbbd9b188aeeffc31c93d6a3c001cbbaa14daf8
refs/heads/master
2020-06-02T12:58:03.358157
2019-06-27T18:39:55
2019-06-27T18:39:55
191,160,728
0
0
null
null
null
null
UTF-8
C++
false
false
787
cpp
Question1 164305.cpp
#include<iostream> using namespace std; void RowWiseInput( int *row, int size); void AddColumns(int *&col, int size); void RowWisePrint(int **arr, int size); void main() { int n,size; int **triangle; cout<<"Enter the no. of rows"; cin>>n; triangle = new int *[n]; for(int x = 0; x < n; x++) { size = x + 1; AddColumns(triangle[x],size); RowWiseInput(triangle[x],x); } RowWisePrint(triangle, n); } void RowWiseInput( int *row, int size) { int temp; for(int i = 0; i <=size; i++) { cout<<"Enter a no."; cin>>temp; row[i] = temp; } } void AddColumns(int *&col, int size) { col = new int [size]; } void RowWisePrint(int **arr, int size) { for (int i = 0; i < size; i++) { for (int j = 0; j <= i; j++) { cout<<arr[i][j]<<" "; } cout<< endl; } }
e69f9963894d3992b36c19a18f933431aed93c12
14984558fb1596174358ec412fd72928bc48af66
/CFLCommImpl/CommSrc/buildinshaders/GameImage_Atlas_TinyColor.h
8316977cadbe430b23691030fb251cff08f5bf99
[]
no_license
asheigithub/CFL
81cb9f95675b15fcb8c093b9cb932f57dd612203
c6b81a84d8e1d49773bdcb3657a14efba2e5a570
refs/heads/master
2016-09-14T21:28:07.077343
2016-03-05T12:21:35
2016-03-05T12:21:35
48,234,683
0
0
null
null
null
null
UTF-8
C++
false
false
1,206
h
GameImage_Atlas_TinyColor.h
#ifndef GameImageAtlasTinyColor_H #define GameImageAtlasTinyColor_H #define STRINGIFY(A) #A namespace cfl { namespace graphic { static const char* gameimage_atlas_tinycolor_vert = "#version 100\n" STRINGIFY( uniform mat4 vp_matrix; attribute vec4 vPosition; attribute vec4 color; attribute vec2 uv; varying vec4 tiny_color; varying vec2 to_uv; varying vec2 to_auv; void main() { gl_Position = (vp_matrix * vPosition); tiny_color = color; vec2 tmpvar_1; tmpvar_1.x = uv.x; float tmpvar_2; tmpvar_2 = (uv.y * 0.5); tmpvar_1.y = tmpvar_2; to_uv = tmpvar_1; vec2 tmpvar_3; tmpvar_3.x = uv.x; tmpvar_3.y = (tmpvar_2 + 0.5); to_auv = tmpvar_3; } ); static const char* gameimage_atlas_tinycolor_frag = STRINGIFY( precision mediump float; uniform sampler2D s_texture; varying vec4 tiny_color; varying vec2 to_uv; varying vec2 to_auv; void main() { lowp vec4 texcolor_1; texcolor_1.xyz = texture2D(s_texture, to_uv).xyz; texcolor_1.w = texture2D(s_texture, to_auv).x; gl_FragColor = (texcolor_1 * tiny_color); } ); } } #undef STRINGIFY #endif // !GameImageAtlasTinyColor_H
7597a4e1eccde4eda0e0a35d0e6abbebdf8adc62
0b704bbfcbb77816b99621f783336b947b7a65c7
/BattleTank/Source/BattleTank/Private/Tank.cpp
252b78f3de1c296647a46e8f99af169eb740267b
[]
no_license
jzg-unrealengine/BattleTank
fbb3763a3c547a2144f176aa425ac4c62f35763d
7d04368472fb486498679daca7be7a0dbab78fd9
refs/heads/master
2021-08-19T14:16:23.474020
2017-11-26T15:28:49
2017-11-26T15:28:49
109,190,983
0
0
null
null
null
null
UTF-8
C++
false
false
1,038
cpp
Tank.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "Tank.h" // Sets default values ATank::ATank() { // Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = false; } void ATank::BeginPlay() { Super::BeginPlay(); CurrentHealth = TankMaxHealth; } float ATank::TakeDamage(float DamageAmount, struct FDamageEvent const & DamageEvent, class AController * EventInstigator, AActor * DamageCauser) { int32 DamagePoints = FPlatformMath::RoundToInt(Super::TakeDamage(DamageAmount, DamageEvent, EventInstigator, DamageCauser)); int32 DamageToApply = FMath::Clamp<int32>(DamagePoints, 0, CurrentHealth); CurrentHealth -= DamageToApply; if (CurrentHealth <= 0) { OnTankDeath.Broadcast(); } //UE_LOG(LogTemp, Warning, TEXT("Health: %i, Damage dealt: %i"), CurrentHealth, DamageToApply) return DamageToApply; } float ATank::GetHealthPct() const { return (float)CurrentHealth / (float)TankMaxHealth; }
12c7ecfae65a6a86ee6b4c8670b6567f118b39fe
1a4363e3074a02fccdd05068c2974c6bd06c272e
/test/chunksa.cpp
a1f6ea7a6790a27a0e2e2e73c98d00a3111446cf
[ "ISC" ]
permissive
lluchs/sparsearray
3906f6850b502ca0ffc51a6e5f8bb8ab0e444777
aed1cbe9c85fcce3bd159b6b35adaff29df2076c
refs/heads/master
2021-01-11T16:49:41.665349
2017-01-29T11:11:20
2017-01-29T11:11:20
79,678,845
3
2
null
null
null
null
UTF-8
C++
false
false
329
cpp
chunksa.cpp
#include "catch.hpp" #include "../sparsearray.h" TEST_CASE("ChunkSA: Basic actions", "[ChunkSA]") { constexpr int N = 10; ChunkSA<int, N, 2> array; #include "common.h" } TEST_CASE("StaticChunkSA: Basic actions", "[StaticChunkSA]") { constexpr int N = 10; StaticChunkSA<int, N, 2> array; #include "common.h" }
8189b2f0a402c67cd3786b2faf8ee3b27a89cceb
ce9500f5ee0458b2101deb1433e7b937843d035b
/src/FrameState.cpp
40b1e48163f3bb9067ab85cbae9c5f6acafb274e
[]
no_license
Adam-van-der-Voorn/Fractals
4ef5823d3920acd642d6ce124bcfc62445ca104f
bb4d1b2ee46a67085263b27449c60e52ef574f70
refs/heads/master
2023-07-19T10:46:51.126273
2021-09-08T00:22:12
2021-09-08T00:22:12
293,015,707
1
0
null
null
null
null
UTF-8
C++
false
false
1,995
cpp
FrameState.cpp
#include "FrameState.h" #include <unordered_map> #include "EditableLine.h" #include "EditableLineNode.h" #include <vector> #include "NodeID.h" int getID() { static int i = 0; return i++; } FrameState::FrameState(const AbsLine& base_line_dimensions) : base_line(EditableLine(getID(), base_line_dimensions)) { } void FrameState::addLine(const AbsLine& line_dimensions) { const int line_id = getID(); lines.emplace(line_id, EditableLine(line_id, line_dimensions)); nodes.emplace(NodeID(line_id, true), lines.at(line_id).getNode(true)); nodes.emplace(NodeID(line_id, false), lines.at(line_id).getNode(false)); } void FrameState::removeLine(int id) { nodes.erase({id, true}); nodes.erase({id, false}); lines.erase(id); } void FrameState::setNodePos(NodeID node_id, Vec2 position) { EditableLine& line = lines.at(node_id.lineID()); line.setNodePos(node_id.isFront(), position); } void FrameState::setLineRecursiveness(int id, bool isRecursive) { lines.at(id).setRecursive(isRecursive); } void FrameState::setFractal(const std::vector<AbsLine>& fractal) { this->fractal = fractal; } void FrameState::clearSelection() { selected_nodes.clear(); } void FrameState::selectNode(NodeID node_id) { selected_nodes.insert(node_id); } const EditableLineNode* FrameState::getNode(NodeID node_id) const { return lines.at(node_id.lineID()).getNode(node_id.isFront()); } const std::unordered_map<NodeID, const EditableLineNode*>& FrameState::getNodes() const { return nodes; } const EditableLine& FrameState::getLine(int line_id) const { return lines.at(line_id); } const std::unordered_map<int, EditableLine>& FrameState::getLines() const { return lines; } const EditableLine& FrameState::getBaseLine() const { return base_line; } const std::unordered_set<NodeID>& FrameState::getSelectedNodes() const { return selected_nodes; } const std::vector<AbsLine>& FrameState::getFractal() const { return fractal; }
53b8099c6fc506867c50e0d4e733052a32026c6a
e5e6bdbf405a918ca604f68e70dcc7f1cc6970ce
/src/Core/Models/Transaction.cpp
f86fe61674e09b5f14d33a05475e683ce1d29dfd
[ "MIT" ]
permissive
GrinPlusPlus/GrinPlusPlus
a86d39fdf31bcd26d13e7dec646a0ecc0b125336
fa3705f5558f0372410aa4222f5f1d97a0ab2247
refs/heads/master
2023-06-21T21:28:08.086560
2023-03-01T16:20:42
2023-03-01T16:20:42
162,051,905
153
50
MIT
2023-05-19T16:56:56
2018-12-16T23:53:01
C++
UTF-8
C++
false
false
2,597
cpp
Transaction.cpp
#include <Core/Models/Transaction.h> #include <Consensus.h> #include <Crypto/Hasher.h> #include <Core/Global.h> #include <Core/Serialization/Serializer.h> #include <Core/Util/JsonUtil.h> #include <Core/Config.h> Transaction::Transaction(BlindingFactor&& offset, TransactionBody&& transactionBody) : m_offset(std::move(offset)), m_transactionBody(std::move(transactionBody)) { } Transaction::Transaction(const Transaction& tx) : m_offset(tx.m_offset), m_transactionBody(tx.m_transactionBody), m_hash(tx.GetHash()) { } Transaction::Transaction(Transaction&& tx) noexcept : m_offset(std::move(tx.m_offset)), m_transactionBody(std::move(tx.m_transactionBody)), m_hash(std::move(tx.m_hash)) { } Transaction& Transaction::operator=(const Transaction& tx) { m_offset = tx.m_offset; m_transactionBody = tx.m_transactionBody; m_hash = tx.GetHash(); return *this; } void Transaction::Serialize(Serializer& serializer) const { // Serialize BlindingFactor/Offset const CBigInteger<32>& offsetBytes = m_offset.GetBytes(); serializer.AppendBigInteger(offsetBytes); // Serialize Transaction Body m_transactionBody.Serialize(serializer); } Transaction Transaction::Deserialize(ByteBuffer& byteBuffer) { // Read BlindingFactor/Offset (32 bytes) BlindingFactor offset = BlindingFactor::Deserialize(byteBuffer); // Read Transaction Body (variable size) TransactionBody transactionBody = TransactionBody::Deserialize(byteBuffer); return Transaction(std::move(offset), std::move(transactionBody)); } Json::Value Transaction::ToJSON() const { Json::Value txNode; txNode["offset"] = JsonUtil::ConvertToJSON(GetOffset()); txNode["body"] = GetBody().ToJSON(); return txNode; } Transaction Transaction::FromJSON(const Json::Value& transactionJSON) { Json::Value offsetJSON = JsonUtil::GetRequiredField(transactionJSON, "offset"); BlindingFactor offset = JsonUtil::ConvertToBlindingFactor(offsetJSON); Json::Value bodyJSON = JsonUtil::GetRequiredField(transactionJSON, "body"); TransactionBody body = TransactionBody::FromJSON(bodyJSON); return Transaction(std::move(offset), std::move(body)); } const Hash& Transaction::GetHash() const { std::unique_lock lock(m_mutex); if (m_hash == Hash{}) { Serializer serializer; Serialize(serializer); m_hash = Hasher::Blake2b(serializer.GetBytes()); } return m_hash; } bool Transaction::FeeMeetsMinimum(const uint64_t block_height) const noexcept { uint64_t fee_base = Global::GetConfig().GetFeeBase(); uint64_t min_fee = fee_base * m_transactionBody.CalcWeight(block_height); return CalcFee() >= (min_fee << GetFeeShift()); }
0b432459a1d9c6e33e420e29bd05d7d544486a32
5b14015ef383e41068de03745ea88adb12793499
/Source/UnrealEnginePython/Private/Slate/UEPySWindow.cpp
da76f15a80adca76a317179335b447d118856a55
[ "MIT" ]
permissive
adaube/UnrealEnginePython
11fb628d51c3cf5a20a58e806b1384659a77e89a
cc639859f2ae94a3a09cee8d2c11450f20c56a2f
refs/heads/master
2021-01-22T11:15:29.831426
2017-05-28T16:23:38
2017-05-28T16:23:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,051
cpp
UEPySWindow.cpp
#include "UnrealEnginePythonPrivatePCH.h" #include "UEPySWindow.h" #define GET_s_window SWindow *s_window = (SWindow*)self->s_compound_widget.s_widget.s_widget static PyObject *py_ue_swindow_set_title(ue_PySWindow *self, PyObject * args) { char *title; if (!PyArg_ParseTuple(args, "s:set_title", &title)) { return NULL; } GET_s_window; s_window->SetTitle(FText::FromString(UTF8_TO_TCHAR(title))); Py_INCREF(self); return (PyObject *)self; } static PyObject *py_ue_swindow_resize(ue_PySWindow *self, PyObject * args) { int width; int height; if (!PyArg_ParseTuple(args, "ii:resize", &width, &height)) { return NULL; } GET_s_window; s_window->Resize(FVector2D(width, height)); Py_INCREF(self); return (PyObject *)self; } static PyObject *py_ue_swindow_set_content(ue_PySWindow *self, PyObject * args) { PyObject *py_content; if (!PyArg_ParseTuple(args, "O:set_content", &py_content)) { return NULL; } ue_PySWidget *py_swidget = py_ue_is_swidget(py_content); if (!py_swidget) { return PyErr_Format(PyExc_Exception, "argument is not a SWidget"); } // TODO: decrement reference when destroying parent Py_INCREF(py_swidget); GET_s_window; s_window->SetContent(py_swidget->s_widget->AsShared()); Py_INCREF(self); return (PyObject *)self; } static PyObject *py_ue_swindow_get_handle(ue_PySWindow *self, PyObject * args) { GET_s_window; return PyLong_FromLongLong((long long)s_window->GetNativeWindow()->GetOSWindowHandle()); } static PyObject *ue_PySWindow_str(ue_PySWindow *self) { return PyUnicode_FromFormat("<unreal_engine.SWindow '%p'>", self->s_compound_widget.s_widget.s_widget); } static PyMethodDef ue_PySWindow_methods[] = { { "set_title", (PyCFunction)py_ue_swindow_set_title, METH_VARARGS, "" }, { "resize", (PyCFunction)py_ue_swindow_resize, METH_VARARGS, "" }, { "set_client_size", (PyCFunction)py_ue_swindow_resize, METH_VARARGS, "" }, { "set_content", (PyCFunction)py_ue_swindow_set_content, METH_VARARGS, "" }, { "get_handle", (PyCFunction)py_ue_swindow_get_handle, METH_VARARGS, "" }, { NULL } /* Sentinel */ }; PyTypeObject ue_PySWindowType = { PyVarObject_HEAD_INIT(NULL, 0) "unreal_engine.SWindow", /* tp_name */ sizeof(ue_PySWindow), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ (reprfunc)ue_PySWindow_str, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "Unreal Engine SWindow", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ue_PySWindow_methods, /* tp_methods */ }; static int ue_py_swindow_init(ue_PySWindow *self, PyObject *args, PyObject *kwargs) { ue_py_snew(SWindow, s_compound_widget.s_widget); GET_s_window; FSlateApplication::Get().AddWindow(StaticCastSharedRef<SWindow>(s_window->AsShared()), true); return 0; } void ue_python_init_swindow(PyObject *ue_module) { ue_PySWindowType.tp_new = PyType_GenericNew; ue_PySWindowType.tp_init = (initproc)ue_py_swindow_init; ue_PySWindowType.tp_base = &ue_PySCompoundWidgetType; if (PyType_Ready(&ue_PySWindowType) < 0) return; Py_INCREF(&ue_PySWindowType); PyModule_AddObject(ue_module, "SWindow", (PyObject *)&ue_PySWindowType); }
c00af065a4623945924f44cc06c9e0daa25486c3
1a8b08ad3d8139f27098c47271a0a6421cdd10da
/src/mainview.cpp
4206107d7039418f494ef3da84e1d1ecc1b08d6e
[]
no_license
dudochkin-victor/touchcp-regionformat
a7149831cc48595e3f467dbbb56821a9db353108
7fc59ac6025cae8f3ba5d43cc123b329a1256152
refs/heads/master
2016-09-06T17:16:04.502523
2013-05-15T06:51:37
2013-05-15T06:51:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,329
cpp
mainview.cpp
/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Karoliina T. Salminen <karoliina.t.salminen@nokia.com> ** ** This file is part of duicontrolpanel-regionformatapplet. ** ** ** This program is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ /* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */ /* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino="(0,W2s,i2s,t0,l1,:0" */ #include <langinfo.h> #include <QDate> #include <QTime> #include <MLayout> #include <MContentItem> #include <MContainer> #include <MComboBox> #include <MLabel> #include <MLinearLayoutPolicy> #include <MButton> #include <MGConfItem> #include <MStylableWidget> #include "widgetlist.h" #include "infoitem.h" #include "businesslogic.h" #include "translation.h" #include "mainview.h" #include "drilldownitem.h" #include "titlewidget.h" #include "debug.h" #define ARABIC_LANGUAGE "ar" MainView::MainView (QGraphicsWidget *parent) : DcpWidget (parent) { initWidget (); QTimer::singleShot(0, this, SLOT(finishMainView())); } MainView::~MainView () { } bool MainView::pagePans () const { return false; } void MainView::initWidget() { MLayout *mainLayout; MLinearLayoutPolicy *layoutPolicy; /* * The mainLayout has one layout policy which is vertical. */ mainLayout = new MLayout (this); layoutPolicy = new MLinearLayoutPolicy (mainLayout, Qt::Vertical); mainLayout->setLandscapePolicy(layoutPolicy); mainLayout->setPortraitPolicy(layoutPolicy); mainLayout->setContentsMargins(0, 0, 0, 0); /* Header */ TitleWidget *headerLabel = new TitleWidget(_(AppletTitle)); layoutPolicy->addItem(headerLabel); /* * One list for selectable items to set something and one another * for only informational items. */ m_ButtonList = new WidgetList(); layoutPolicy->addItem(m_ButtonList); MStylableWidget *sep2 = new MStylableWidget(); sep2->setStyleName("CommonSpacer"); layoutPolicy->addItem(sep2); MContainer *exampleContainer = new MContainer(); exampleContainer->setStyleName("CommonTextFrameInverted"); m_InfoList = new WidgetList(exampleContainer); exampleContainer->setCentralWidget(m_InfoList); exampleContainer->setHeaderVisible(false); layoutPolicy->addItem(exampleContainer); /* * The region content item opens a view with the list of available regions */ m_RegionCItem = new DrillDownItem(); m_RegionCItem->setObjectName("RegionCItem"); m_ButtonList->addWidget(m_RegionCItem); m_ButtonList->setLayoutMargins(0, 0, 0, 0); connect(m_RegionCItem, SIGNAL(clicked()), this, SLOT (regionCItemClickedSlot())); /* * Number Combobox to choose number format. * FIXME Spec expects us to show it only for relevant/arabic region. Which those are? */ m_NumberCBox = new MComboBox(); m_NumberCBox->setObjectName("NumberCBox"); m_NumberCBox->setStyleName("CommonComboBoxInverted"); /* * Information labels to show example of several details * of the current regional settings. */ m_DateInfoItem = new InfoItem(QString("DateInfoItem")); m_InfoList->addWidget(m_DateInfoItem); m_TimeInfoItem = new InfoItem(QString("TimeInfoItem")); m_InfoList->addWidget(m_TimeInfoItem); m_NumberInfoItem = new InfoItem(QString("NumberInfoItem")); m_InfoList->addWidget(m_NumberInfoItem); m_CurrencyInfoItem = new InfoItem(QString("CurrencyInfoItem")); m_InfoList->addWidget(m_CurrencyInfoItem); MStylableWidget *sep3 = new MStylableWidget(); sep3->setStyleName("CommonSmallSpacer"); layoutPolicy->addItem(sep3); } QString MainView::title() const { return QString(_(AppletTitle)); } void MainView::finishMainView() { refreshNumberFormatCBox(); connect(m_NumberCBox, SIGNAL(activated(int)), this, SLOT(numberCBoxActivatedSlot(int))); BusinessLogic &bl = BusinessLogic::instance(); /* * Listening for changed system values */ connect(&bl, SIGNAL(regionChanged()), this, SLOT(regionChangedSlot())); connect(&bl, SIGNAL(settingsChanged()), this, SLOT(settingsChangedSlot())); retranslateUi (); regionChangedSlot(); } void MainView::settingsChangedSlot() { lcTimeChangedSlot(); lcNumericChangedSlot(); lcMonetaryChangedSlot(); lcCollateChangedSlot(); } void MainView::regionChangedSlot() { BusinessLogic &bl = BusinessLogic::instance(); m_RegionCItem->setSubtitle(bl.getRegionName()); /* * Show Number selection ComboBox only for arabic languages */ if(bl.getRegion().left(2) == ARABIC_LANGUAGE){ m_ButtonList->addWidget(m_NumberCBox); } else { m_ButtonList->removeWidget(m_NumberCBox); } } void MainView::lcTimeChangedSlot() { BusinessLogic &bl = BusinessLogic::instance(); m_DateInfoItem->setContent(bl.dateExample()); m_TimeInfoItem->setContent(bl.timeExample()); } void MainView::lcCollateChangedSlot() { } void MainView::lcNumericChangedSlot() { BusinessLogic &bl = BusinessLogic::instance(); m_NumberInfoItem->setContent(bl.numberExample()); } void MainView::lcMonetaryChangedSlot() { BusinessLogic &bl = BusinessLogic::instance(); m_CurrencyInfoItem->setContent(bl.currencyExample()); } void MainView::regionCItemClickedSlot() { refererToChangeWidget(View::Main); emit changeWidget(View::Region); } void MainView::numberCBoxActivatedSlot(int index) { /* * When we clear the combo box a signal is emitted with -1 as index. */ if (index < 0) { qWarning("Invalid index: %d", index); return; } BusinessLogic &bl = BusinessLogic::instance(); bl.setNumberFormat( index ? BusinessLogic::ArabicNumbers : BusinessLogic::LatinNumbers); } void MainView::refreshNumberFormatCBox() { BusinessLogic &bl = BusinessLogic::instance(); m_NumberCBox->clear(); m_NumberCBox->addItems(bl.getNumberFormatEndonymList()); if(bl.getLcNumeric().left(2) == ARABIC_LANGUAGE) m_NumberCBox->setCurrentIndex(BusinessLogic::ArabicNumbers); else m_NumberCBox->setCurrentIndex(BusinessLogic::LatinNumbers); } void MainView::retranslateUi() { BusinessLogic &bl = BusinessLogic::instance(); m_RegionCItem->setTitle(_(SelectRegion)); m_RegionCItem->setSubtitle(bl.getRegionName()); m_NumberCBox->setTitle(_(SelectNumber)); refreshNumberFormatCBox(); m_DateInfoItem->setTitle(_(DateTitle)); m_DateInfoItem->setContent(bl.dateExample()); m_TimeInfoItem->setTitle(_(TimeTitle)); m_TimeInfoItem->setContent(bl.timeExample()); m_NumberInfoItem->setTitle(_(NumberTitle)); m_NumberInfoItem->setContent(bl.numberExample()); m_CurrencyInfoItem->setTitle(_(CurrencyTitle)); m_CurrencyInfoItem->setContent(bl.currencyExample()); }
d3eaf7f4d8dbfab403b49a9915e722d0722d6101
f7f99058381ee79b1a969d34cb19936a317b2645
/Bsaic_DS/Quick_Sort/main.cpp
bff6a7f0a5bb155b79250397ef8c350f31c08df6
[]
no_license
GS-prepare/DataStructure
f92d2b97450b2b2222fbba6a6fd91bc2fa3b2870
de5b8b6644cc87e12a5da1d1eea5499421599cd2
refs/heads/master
2020-11-29T21:36:59.429392
2020-01-27T11:55:40
2020-01-27T11:55:40
230,220,848
0
0
null
null
null
null
UTF-8
C++
false
false
1,186
cpp
main.cpp
// // main.cpp // Quick_Sort // // Created by Sun on 2019/12/31. // Copyright © 2019 Sun. All rights reserved. // #include <iostream> using namespace std; void Quick_Sort(int arr[], int L, int R){ if(L<R){ int i = L, j = R+1, pivot = arr[L]; //initial do{ do i++; while(arr[i] < pivot); // 找陣列資料中 ≥pivot 的值 do j--; while(arr[j] > pivot); // 找陣列資料中 ≤pivot 的值 if(i<j) swap(arr[i], arr[j]); // i,j 交錯時,資料交換 }while(i<j); swap(arr[L], arr[j]); //將pivot值交換到正確的位置上 Quick_Sort(arr, L, j-1); //recursion 解左半邊 Quick_Sort(arr, j+1, R); //recursion 解右半邊 } } void printArray(int arr[], int n){ for (int i=0; i<n; i++){ std::cout << arr[i] << " | " ; } std::cout << endl; } int main(int argc, const char * argv[]) { int arr[9] = {23, 3, 33, 1, 58, 18, 60, 45, 15}; std::cout << "Original Data : "; printArray(arr,9); //Using Divide and Conquar Quick_Sort(arr,0,8); //Print Result std::cout << "Sorted Data : "; printArray(arr, 9); return 0; }
a2366b79b79a692bbc8e742029f621bc651c24e9
7e1314190616848a093d5e40c10409f686b49710
/m26.cpp
47f6f87738b22a7d3e4d626975621253f01d97be
[]
no_license
xyzkpsf/110A
109cacec854cae2ff74abd4761ee1f3d5435f820
b63549e09cafd64bb4417f83a3672b780963b9ee
refs/heads/master
2022-11-30T22:20:16.574198
2020-08-20T16:38:33
2020-08-20T16:38:33
289,055,476
0
0
null
null
null
null
UTF-8
C++
false
false
4,590
cpp
m26.cpp
/* ID:w78034117 Filename: m26.cpp Assignment : M26: strcmp Description: Mobile Service Provider, Part 3 */ #include <iostream> #include <iomanip> #include <fstream> #include <cstring> using namespace std; int main() { char package, month[10]; int min, maxMin; float additionalFee = 0, fee; bool isDone; ifstream fin; fin.open("data.txt"); fin >> month >> package >> min; cout << fixed << setprecision(2); if(!fin) cout << "Error! File could not be opened!\n"; else { if((strcmp(month, "January")) && (strcmp(month, "February")) && (strcmp(month, "March")) && (strcmp(month, "April")) && (strcmp(month, "May")) && (strcmp(month, "June")) && (strcmp(month, "July")) && (strcmp(month, "August")) && (strcmp(month, "September")) && (strcmp(month, "October")) && (strcmp(month, "November")) && (strcmp(month, "December")) ) { cout << "Month enter invalid!\n"; isDone = true; } else { if (strcmp(month, "January")== 0 || (strcmp(month, "March")) == 0 || (strcmp(month, "May"))== 0 || (strcmp(month, "July"))== 0 || (strcmp(month, "August"))== 0 || (strcmp(month, "October"))== 0 || (strcmp(month, "December"))== 0 ) { maxMin = 44640; if (min > maxMin) { cout << "Minutes enter invalid!\n"; isDone = true; } } if (strcmp(month, "February")== 0) { maxMin = 40320; if (min > maxMin) { cout << "Minutes enter invalid!\n"; isDone = true; } } if ((strcmp(month, "April") == 0) || (strcmp(month, "June"))== 0 || (strcmp(month, "September"))== 0 || (strcmp(month, "November"))== 0 ) { maxMin = 43200; if (min > maxMin) { cout << "Minutes enter invalid!\n"; isDone = true; } } } if (isDone != true) { switch (package) { case 'a': case 'A': if (min > 450) additionalFee = (min - 450)*0.45; fee = 39.99 + additionalFee; cout << "You total amount due is $" << fee << endl; break; case 'b': case 'B': if (min > 900) additionalFee = (min - 900)*0.40; fee = 59.99 + additionalFee; cout << "You total amount due is $" << fee << endl; break; case 'c': case 'C': fee = 69.99; cout << "You total amount due is $" << fee << endl; break; default: cout << "Invalid data!\n"; } double feeLess; if ((package == 'a' || package == 'A') && min > 494 && min < 900) { feeLess = 59.99; cout << "If you purchased package B, you can save $" << fee - feeLess << " dollars!\n"; } else if ((package == 'a' || package == 'A') && min >= 900 && min <= 925) { feeLess = 59.99 + (min - 900)*0.40; cout << "If you purchased package B, you can save $" << fee - feeLess << " dollars!\n"; } else if ((package == 'a' || package == 'A' || package == 'b' || package == 'B') && min >= 926) { cout << "If you purchased package C, you can save $" << fee - 69.99 << " dollars!\n"; } } } fin.close(); return 0; } /* OUTPUT [xzhu91@hills CS110A]$ g++ m26.cpp [xzhu91@hills CS110A]$ cat data.txt Septemberr b 300 [xzhu91@hills CS110A]$ ./a.out Month enter invalid! [xzhu91@hills CS110A]$ cat data.txt September b 43119 [xzhu91@hills CS110A]$ ./a.out You total amount due is $16947.59 If you purchased package C, you can save $16877.60 dollars! [xzhu91@hills CS110A]$ cat data.txt September b 43201 [xzhu91@hills CS110A]$ ./a.out Minutes enter invalid! [xzhu91@hills CS110A]$ cat data.txt August b 43201 [xzhu91@hills CS110A]$ ./a.out You total amount due is $16980.39 If you purchased package C, you can save $16910.40 dollars! */
3250d805c45a828bc993da8c7d1019582e413fdb
d4644544c31a5f0e0a0b071138dedfd4cf9e4603
/remove_duplicates_from_sorted_array/duplicate.cpp
e91b4c6a3c33a817c9f07057c515e9355ea142ae
[]
no_license
xiangbai/LeetCode
d095250de91c9293f51818a648828e1c9ad4eade
15f66bb56511966e53bcbc0d3f8a09ad37845d00
refs/heads/master
2021-01-10T20:04:40.068965
2014-04-27T13:02:43
2014-04-27T13:02:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
877
cpp
duplicate.cpp
/************************************************************************* > File Name: duplicate.cpp > Author: wang > Mail:xiangbai@qq.com > Created Time: Sat 19 Apr 2014 10:00:24 AM CST ************************************************************************/ #include<iostream> using namespace std; class Solution{ public: int removeDuplicates(int A[] , int n) { int i , j = 0; int flag ; int len = 0 ; if(n == 0) { return 0 ; } flag = A[0] ; A[j++] = flag ; len++ ; for(i = 1 ; i < n ; ++i) { if(flag != A[i]) { flag = A[i] ; A[j++] = flag ; len ++; } } return len ; } }; int main(int argc , char **argv) { int A[3] = {1,1,2} ; Solution sol ; int num = sol.removeDuplicates(A , 3) ; for(int i = 0 ; i < num ; ++i) { std::cout<<A[i] <<" " ; } std::cout<<std::endl; return 0 ; }
1873005a59e9a8e182528b61585fd6c216b209dd
c281896bbd547170ac3a25614a565f047328f08c
/src/frontend/lexer/token.hpp
8054cb26fe9c64d06e95d9e64326a14e53f11b3b
[]
no_license
anastasiarazb/c-format-checker
0c2c420bec946efebf1fd49933cc337533d1c0d2
b4a672a762e06ef674b7417cd3690edf283a8987
refs/heads/master
2020-05-09T11:21:49.344762
2019-06-20T21:53:16
2019-06-20T21:53:16
181,076,376
1
0
null
null
null
null
UTF-8
C++
false
false
2,734
hpp
token.hpp
#ifndef LEXER_H #define LEXER_H #include "frontend/lexer/coords.hpp" #include <algorithm> #include <iostream> #include <string> #include <vector> #include <frontend/rules/rules.hpp> namespace lexem { enum Type { LPAREN, // ( RPAREN, // ) LBRACKET, // [ RBRACKET, // ] LBRACE, // { RBRACE, // } LANGLE, // < RANGLE, // > BACKSLASH, // '\' SEMICOLON, // ; COLON, // : COMMA, // , DOLLAR, // $ DOT, // . ELLIPSIS, // ... IDENT, // [a-zA-Z][a-zA-Z0-9]* STRING, // ".*" CHAR, // '\n' NUM, // [0-9a-fA-FuUlLxX]+(\.[0-9a-fA-FuUlLxX]+)?([eEpP][+-]?[0-9a-fA-FuUlLxX]+)? INC_DEC, // ++, -- OPERATOR, // +, -, /, %, ~, |, ^, <<, >>, !, &&, || ARROW, // -> STAR, // * ASSIGNOP, // =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>= COMPAREOP, // >, <, !=, <=, =>, == HASH, // # DOUBLEHASH,// ## AMPERSAND, // & QUESTIONMARK, // ? /* KEYWORDS */ CASE, DEFAULT, DO, ELSE, ENUM, FOR, IF, STRUCT, SWITCH, UNION, WHILE, TYPEDEF, TYPENAME, KEYWORD, // WHITESPACE, // [' ''\t']+ NEWLINE, // [\r\n][WHITESPACE\r\n]* END_OF_FILE, ERROR // now used only for uninitialized tokens }; std::string to_string(lexem::Type t); } //namespace lexem class Token { protected: lexem::Type m_type = lexem::Type::ERROR; std::string_view m_image; Coords m_start; Coords m_follow; public: Rules::Cases rule = Rules::Cases::BLOCK; Token() = default; Token(lexem::Type type, std::string_view image, Coords start, Coords follow); Token(Token &&tok) noexcept; Token(const Token &tok) = default; Token& operator=(const Token&) = default; inline bool operator==(lexem::Type type) const { return m_type == type; } inline bool operator!=(lexem::Type type) const { return m_type != type; } lexem::Type type() const; std::string_view image() const; std::string image_escaped() const; Coords start() const; Coords follow() const; inline std::string coords_to_string() const { return Coords::coords_to_string(m_start, m_follow); } inline bool in(const std::vector<lexem::Type> &set) const { return std::find(set.begin(), set.end(), m_type) != set.end(); } inline bool isEOF() const { return m_type == lexem::END_OF_FILE;} inline bool notEOF() const { return m_type != lexem::END_OF_FILE;} // bool in(std::initializer_list<lexem::Type> values); explicit operator std::string() const; }; std::ostream& operator<<(std::ostream& os, const Token& obj); #endif // LEXER_H
9b535017d2461e3d5b169e5004daa523fa638dc4
920e748cdcdcea9a71b74889a5e44f4b97a98699
/Src/DarunGrim2C.cpp
5d3d6b92ac31b7416f684fb2d05901fdfeeb5a3f
[ "BSD-3-Clause" ]
permissive
fengjixuchui/DarunGrim
5e50af3cb7ea2c47bcc257b9aefa59707aeb8a6c
a6cbe5c064f9399423845dea0ab67355d5ac5852
refs/heads/master
2020-12-18T09:31:05.212773
2020-05-25T02:22:21
2020-05-25T02:22:21
235,330,249
0
0
NOASSERTION
2020-05-25T02:22:22
2020-01-21T11:48:54
C
UTF-8
C++
false
false
3,695
cpp
DarunGrim2C.cpp
#include "Common.h" #ifdef _DEBUG #include <conio.h> #include <ctype.h> #endif #include "Configuration.h" #include "DiffMachine.h" #include "Storage.h" #include "XGetopt.h" #include "ProcessUtils.h" #include "Log.h" #include "DarunGrim.h" #define strtoul10(X) strtoul(X,NULL,10) void main(int argc,char *argv[]) { bool CreateNewDBFromIDA=TRUE; TCHAR *optstring=TEXT("f:i:I:L:ld:s:t:y"); int optind=0; TCHAR *optarg; int c; char *SourceFilename=NULL; char *TargetFilename=NULL; char *LogFilename=NULL; BOOL bListFiles=FALSE; char *IDAPath=NULL; BOOL UseIDASync=FALSE; DWORD SourceFunctionAddress=0; DWORD TargetFunctionAddress = 0; int SourceFileID; int TargetFileID; int DebugLevel = 0; bool is_64 = false; //TODO: #ifdef DEBUG_MEMORY _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT); _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDOUT); #endif while((c=getopt(argc,argv,optstring,&optind,&optarg))!=EOF) { switch(c) { case 'f': SourceFilename=optarg; TargetFilename=argv[optind]; optind++; break; case 'i': SourceFileID=strtoul10(optarg); TargetFileID=strtoul10(argv[optind]); optind++; break; case 'd': DebugLevel=strtoul10(optarg); break; case 's': SourceFunctionAddress = strtoul(optarg, NULL, 16); break; case 't': TargetFunctionAddress = strtoul(optarg, NULL, 16); break; case 'I': IDAPath=optarg; break; case 'L': LogFilename=optarg; break; case 'l': bListFiles=TRUE; break; case 'y': UseIDASync=TRUE; break; } } if(argc<=optind) { printf("Usage: %s [-f <original filename> <patched filename>]|[-i <original file id> <patched file id>]|-l -L <Log Filename> [-y] <database filename>\r\n" " - f <original filename> <patched filename>\r\n" " Original filename and patched filename\r\n" " Retrieve data from IDA using DarunGrim IDA plugin\r\n" "-i <original file id> <patched file id>\r\n" " Original files ID in the database and patched files ID in the database\r\n" " Retrieve data from database file created using DarunGrim IDA plugin\r\n" "-I IDA Program path.\r\n" //Debugging related parameters "-L Debug Log Filename\r\n" "-d <level> Debug Level\r\n" "-s <function address> Function address to analyze for the original binary\r\n" "-t <function address> Function address to analyze for the patched binary\r\n" "-y Use IDA synchorinzation mode\r\n" "-l: \r\n" " List file informations in the <database filename>\r\n" "<database filename>\r\n" " Database filename to use\r\n\r\n", argv[0]); return; } DarunGrim *pDarunGrim = new DarunGrim(); if (IDAPath) pDarunGrim->SetIDAPath(IDAPath,is_64); pDarunGrim->SetLogParameters(LogToStdout, DebugLevel, ""); char *DiffDatabaseFilename=argv[optind]; if (bListFiles) { pDarunGrim->ListDiffDatabase(DiffDatabaseFilename); } else if (SourceFilename && TargetFilename && DiffDatabaseFilename) { pDarunGrim->PerformDiff( SourceFilename, SourceFunctionAddress, TargetFilename, TargetFunctionAddress, DiffDatabaseFilename); } else { pDarunGrim->AcceptIDAClientsFromSocket(); pDarunGrim->PerformDiff(); } if(UseIDASync) { pDarunGrim->ShowOnIDA(); } #ifdef DEBUG_MEMORY _CrtDumpMemoryLeaks(); #endif }