blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
sequencelengths
1
1
author
stringlengths
0
119
a3d13c443719b1738e13083dfcbd40751aade215
5d91784aa3a9a543de413e275c7c73bc0804caf9
/Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_OpCode.cpp
babf6be70828d901936598cdfbd085a66d24a73c
[ "MIT" ]
permissive
eudora-jia/CIDLib
c957dd2f4b9fbe5c7c12be9fb67589faca10758c
02795d283d95f8a5a4fafa401b6189851901b81b
refs/heads/master
2020-05-28T10:19:10.410157
2019-05-28T04:29:56
2019-05-28T04:29:56
188,968,337
1
0
MIT
2019-05-28T06:32:49
2019-05-28T06:32:48
null
UTF-8
C++
false
false
29,207
cpp
// // FILE NAME: CIDMacroEng_OpCode.cpp // // AUTHOR: Dean Roddey // // CREATED: 01/15/2003 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2019 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This file implements the TMEngOpCode class, which represents an opcode // in the virtual machine assembly code of the engine. // // CAVEATS/GOTCHAS: // // LOG: // // $_CIDLib_Log_$ // // --------------------------------------------------------------------------- // Facility specific includes // --------------------------------------------------------------------------- #include "CIDMacroEng_.hpp" // --------------------------------------------------------------------------- // CLASS: TMEngOpCode // PREFIX: meop // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TMEngOpCode: Constructors and Destructor // --------------------------------------------------------------------------- TMEngOpCode::TMEngOpCode() : m_eOpCode(tCIDMacroEng::EOpCodes::None) { TRawMem::SetMemBuf(&m_uStorage, tCIDLib::TCard1(0), sizeof(m_uStorage)); } TMEngOpCode::TMEngOpCode(const TMEngOpCode& meopToCopy) : m_eOpCode(meopToCopy.m_eOpCode) , m_uStorage(meopToCopy.m_uStorage) { } TMEngOpCode::~TMEngOpCode() { } // --------------------------------------------------------------------------- // TMEngOpCode: Public operators // --------------------------------------------------------------------------- TMEngOpCode& TMEngOpCode::operator=(const TMEngOpCode& meopToAssign) { if (this != &meopToAssign) { m_eOpCode = meopToAssign.m_eOpCode; m_uStorage = meopToAssign.m_uStorage; } return *this; } // --------------------------------------------------------------------------- // TMEngOpCode: Public, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::TBoolean TMEngOpCode::bConvertNumeric(const tCIDLib::TCard2 c2TargetId) { // Based on the opcode, which will be one of the immediate value types, // see if we can convert it in place to fit the target numeric type. // tCIDLib::TBoolean bRet = kCIDLib::True; switch(m_eOpCode) { case tCIDMacroEng::EOpCodes::PushImCard1 : case tCIDMacroEng::EOpCodes::PushImCard2 : case tCIDMacroEng::EOpCodes::PushImCard4 : { tCIDLib::TCard4 c4Val; if (m_eOpCode == tCIDMacroEng::EOpCodes::PushImCard1) c4Val = m_uStorage.c1Immediate; else if (m_eOpCode == tCIDMacroEng::EOpCodes::PushImCard2) c4Val = m_uStorage.c2Immediate; else c4Val = m_uStorage.c4Immediate; if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Card1)) && (c4Val <= kCIDLib::c1MaxCard)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImCard1; m_uStorage.c1Immediate = tCIDLib::TCard1(c4Val); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Card2)) && (c4Val <= kCIDLib::c2MaxCard)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImCard2; m_uStorage.c2Immediate = tCIDLib::TCard2(c4Val); } else if (c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Card4)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImCard4; m_uStorage.c4Immediate = c4Val; } else if (c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Card8)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImCard8; m_uStorage.c8Immediate = c4Val; } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Int1)) && (c4Val <= kCIDLib::i1MaxInt)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImInt1; m_uStorage.i1Immediate = tCIDLib::TInt1(c4Val); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Int2)) && (c4Val <= kCIDLib::i2MaxInt)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImInt2; m_uStorage.i2Immediate = tCIDLib::TInt2(c4Val); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Int4)) && (c4Val <= kCIDLib::i4MaxInt)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImInt4; m_uStorage.i4Immediate = tCIDLib::TInt4(c4Val); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Float4)) && (c4Val <= kCIDLib::f4MaxFloat)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImFloat4; m_uStorage.f4Immediate = tCIDLib::TFloat4(c4Val); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Float8)) && (c4Val <= kCIDLib::f8MaxFloat)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImFloat8; m_uStorage.f8Immediate = tCIDLib::TFloat8(c4Val); } else { bRet = kCIDLib::False; } break; } case tCIDMacroEng::EOpCodes::PushImCard8 : { const tCIDLib::TCard8 c8Val = m_uStorage.c8Immediate; if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Card1)) && (c8Val <= kCIDLib::c1MaxCard)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImCard1; m_uStorage.c1Immediate = tCIDLib::TCard1(c8Val); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Card2)) && (c8Val <= kCIDLib::c2MaxCard)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImCard2; m_uStorage.c2Immediate = tCIDLib::TCard2(c8Val); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Card4)) && (c8Val <= kCIDLib::c4MaxCard)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImCard4; m_uStorage.c4Immediate = tCIDLib::TCard4(c8Val); } else if (c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Card8)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImCard8; m_uStorage.c8Immediate = c8Val; } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Int1)) && (c8Val <= kCIDLib::i1MaxInt)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImInt1; m_uStorage.i1Immediate = tCIDLib::TInt1(c8Val); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Int2)) && (c8Val <= kCIDLib::i2MaxInt)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImInt2; m_uStorage.i2Immediate = tCIDLib::TInt2(c8Val); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Int4)) && (c8Val <= kCIDLib::i4MaxInt)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImInt4; m_uStorage.i4Immediate = tCIDLib::TInt4(c8Val); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Float4)) && (c8Val <= kCIDLib::f4MaxFloat)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImFloat4; m_uStorage.f4Immediate = tCIDLib::TFloat4(c8Val); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Float8)) && (c8Val <= kCIDLib::f8MaxFloat)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImFloat8; m_uStorage.f8Immediate = tCIDLib::TFloat8(c8Val); } else { bRet = kCIDLib::False; } break; } case tCIDMacroEng::EOpCodes::PushImChar : bRet = kCIDLib::False; break; case tCIDMacroEng::EOpCodes::PushImFloat4 : { // // If we are converting to any of the cardinal/integral types, // we just throw away the decimal part. // tCIDLib::TFloat4 f4Integral; tCIDLib::TFloat4 f4Fract; const tCIDLib::TFloat4 f4Val = m_uStorage.f4Immediate; f4Fract = TMathLib::f4Split(f4Val, f4Integral); if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Card1)) && (f4Integral >= 0) && (f4Integral <= tCIDLib::TFloat4(kCIDLib::c1MaxCard))) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImCard1; m_uStorage.c1Immediate = tCIDLib::TCard1(f4Integral); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Card2)) && (f4Integral >= 0) && (f4Integral <= tCIDLib::TFloat4(kCIDLib::c2MaxCard))) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImCard2; m_uStorage.c2Immediate = tCIDLib::TCard2(f4Integral); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Card4)) && (f4Integral >= 0) && (f4Integral <= tCIDLib::TFloat4(kCIDLib::c4MaxCard))) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImCard4; m_uStorage.c4Immediate = tCIDLib::TCard4(f4Integral); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Card8)) && (f4Integral >= 0)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImCard8; m_uStorage.c8Immediate = tCIDLib::TCard8(f4Integral); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Int1)) && (f4Integral >= tCIDLib::TFloat4(kCIDLib::i1MinInt)) && (f4Integral <= tCIDLib::TFloat4(kCIDLib::i1MaxInt))) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImInt1; m_uStorage.i1Immediate = tCIDLib::TInt1(f4Integral); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Int2)) && (f4Integral >= tCIDLib::TFloat4(kCIDLib::i2MinInt)) && (f4Integral <= tCIDLib::TFloat4(kCIDLib::i2MaxInt))) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImInt2; m_uStorage.i2Immediate = tCIDLib::TInt2(f4Integral); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Int4)) && (f4Integral >= tCIDLib::TFloat4(kCIDLib::i4MinInt)) && (f4Integral <= tCIDLib::TFloat4(kCIDLib::i4MaxInt))) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImInt4; m_uStorage.i4Immediate = tCIDLib::TInt4(f4Integral); } else if (c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Float8)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImFloat8; m_uStorage.f8Immediate = tCIDLib::TFloat8(f4Val); } else { bRet = kCIDLib::False; } break; } case tCIDMacroEng::EOpCodes::PushImFloat8 : { // // If we are converting to any of the cardinal/integral types, // we just throw away the decimal part. // tCIDLib::TFloat8 f8Integral; tCIDLib::TFloat8 f8Fract; const tCIDLib::TFloat8 f8Val = m_uStorage.f8Immediate; f8Fract = TMathLib::f8Split(f8Val, f8Integral); if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Card1)) && (f8Integral >= 0) && (f8Integral <= tCIDLib::TFloat8(kCIDLib::c1MaxCard))) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImCard1; m_uStorage.c1Immediate = tCIDLib::TCard1(f8Integral); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Card2)) && (f8Integral >= 0) && (f8Integral <= tCIDLib::TFloat8(kCIDLib::c2MaxCard))) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImCard2; m_uStorage.c2Immediate = tCIDLib::TCard2(f8Integral); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Card4)) && (f8Integral >= 0) && (f8Integral <= tCIDLib::TFloat8(kCIDLib::c4MaxCard))) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImCard4; m_uStorage.c4Immediate = tCIDLib::TCard4(f8Integral); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Card8)) && (f8Integral >= 0) && (f8Integral <= tCIDLib::TFloat8(kCIDLib::c8MaxCard))) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImCard8; m_uStorage.c8Immediate = tCIDLib::TCard8(f8Integral); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Int1)) && (f8Integral >= tCIDLib::TFloat8(kCIDLib::i1MinInt)) && (f8Integral <= tCIDLib::TFloat8(kCIDLib::i1MaxInt))) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImInt1; m_uStorage.i1Immediate = tCIDLib::TInt1(f8Integral); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Int2)) && (f8Integral >= tCIDLib::TFloat8(kCIDLib::i2MinInt)) && (f8Integral <= tCIDLib::TFloat8(kCIDLib::i2MaxInt))) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImInt2; m_uStorage.i2Immediate = tCIDLib::TInt2(f8Integral); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Int4)) && (f8Integral >= tCIDLib::TFloat8(kCIDLib::i4MinInt)) && (f8Integral <= tCIDLib::TFloat8(kCIDLib::i4MaxInt))) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImInt4; m_uStorage.i4Immediate = tCIDLib::TInt4(f8Integral); } else if (c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Float4)) { if ((f8Val >= -kCIDLib::f4MaxFloat) || (f8Val <= kCIDLib::f4MaxFloat)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImFloat4; m_uStorage.f4Immediate = tCIDLib::TFloat4(f8Val); } else { bRet = kCIDLib::False; } } else { bRet = kCIDLib::False; } break; } case tCIDMacroEng::EOpCodes::PushImInt1 : case tCIDMacroEng::EOpCodes::PushImInt2 : case tCIDMacroEng::EOpCodes::PushImInt4 : { tCIDLib::TInt4 i4Val; if (m_eOpCode == tCIDMacroEng::EOpCodes::PushImInt1) i4Val = m_uStorage.i1Immediate; else if (m_eOpCode == tCIDMacroEng::EOpCodes::PushImInt2) i4Val = m_uStorage.i2Immediate; else i4Val = m_uStorage.i4Immediate; if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Card1)) && (i4Val >= 0) && (i4Val <= kCIDLib::c1MaxCard)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImCard1; m_uStorage.c1Immediate = tCIDLib::TCard1(i4Val); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Card2)) && (i4Val >= 0) && (i4Val < kCIDLib::c2MaxCard)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImCard2; m_uStorage.c2Immediate = tCIDLib::TCard2(i4Val); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Card4)) && (i4Val >= 0)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImCard4; m_uStorage.c4Immediate = tCIDLib::TCard4(i4Val); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Card8)) && (i4Val >= 0)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImCard8; m_uStorage.c8Immediate = tCIDLib::TCard8(i4Val); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Int1)) && (i4Val >= kCIDLib::i1MinInt) && (i4Val <= kCIDLib::i1MaxInt)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImInt1; m_uStorage.i1Immediate = tCIDLib::TInt1(i4Val); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Int2)) && (i4Val >= kCIDLib::i2MinInt) && (i4Val <= kCIDLib::i2MaxInt)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImInt2; m_uStorage.i2Immediate = tCIDLib::TInt2(i4Val); } else if (c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Int4)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImInt4; m_uStorage.i4Immediate = i4Val; } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Float4)) && (i4Val >= -kCIDLib::f4MaxFloat) && (i4Val <= kCIDLib::f4MaxFloat)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImFloat4; m_uStorage.f4Immediate = tCIDLib::TFloat4(i4Val); } else if ((c2TargetId == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Float8)) && (i4Val >= -kCIDLib::f8MaxFloat) && (i4Val <= kCIDLib::f8MaxFloat)) { m_eOpCode = tCIDMacroEng::EOpCodes::PushImFloat8; m_uStorage.f8Immediate = tCIDLib::TFloat8(i4Val); } else { bRet = kCIDLib::False; } break; } default : // This shouldn't happen facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_NotImNumOpCode , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , TInteger(tCIDLib::i4EnumOrd(eOpCode())) ); break; } return bRet; } tCIDLib::TCard4 TMEngOpCode::c4Immediate(const tCIDLib::TCard4 c4ToSet) { m_uStorage.c4Immediate = c4ToSet; return m_uStorage.c4Immediate; } tCIDLib::TVoid TMEngOpCode::Format(TTextOutStream& strmTarget, const TCIDMacroEngine& meOwner) const { // // Write out the opcode itself. We want each one to be left justified // in a field big enough to keep them corectly aligned. // static const TStreamFmt sfmtOpCode ( 16 , 0 , tCIDLib::EHJustify::Left , kCIDLib::chSpace ); static const TStreamFmt sfmtData ( 8 , 4 , tCIDLib::EHJustify::Right , kCIDLib::chSpace ); static const TStreamFmt sfmtText ( 0 , 0 , tCIDLib::EHJustify::Left , kCIDLib::chSpace ); // Retain the original stream formatting TStreamJanitor janStream(&strmTarget); // Put put the opcode with the opcode format strmTarget << sfmtOpCode << m_eOpCode; // Group the one's that share common data, and show it switch(m_eOpCode) { case tCIDMacroEng::EOpCodes::CallLocal : case tCIDMacroEng::EOpCodes::CallMember : case tCIDMacroEng::EOpCodes::CallParm : case tCIDMacroEng::EOpCodes::CallStack : case tCIDMacroEng::EOpCodes::PushEnum : { strmTarget << sfmtData << m_uStorage.ac2Indices[0] << m_uStorage.ac2Indices[1]; break; } case tCIDMacroEng::EOpCodes::CondJump : case tCIDMacroEng::EOpCodes::CondJumpNP : case tCIDMacroEng::EOpCodes::CurLine : case tCIDMacroEng::EOpCodes::MultiPop : case tCIDMacroEng::EOpCodes::NotCondJump : case tCIDMacroEng::EOpCodes::NotCondJumpNP : case tCIDMacroEng::EOpCodes::PushImCard4 : case tCIDMacroEng::EOpCodes::Repush : case tCIDMacroEng::EOpCodes::ThrowFmt : case tCIDMacroEng::EOpCodes::Try : strmTarget << sfmtData << m_uStorage.c4Immediate; break; case tCIDMacroEng::EOpCodes::Jump : case tCIDMacroEng::EOpCodes::PushImCard2 : strmTarget << sfmtData << m_uStorage.c2Immediate; break; case tCIDMacroEng::EOpCodes::Throw : case tCIDMacroEng::EOpCodes::PushImBoolean : strmTarget << sfmtData << m_uStorage.bImmediate; break; case tCIDMacroEng::EOpCodes::PushImCard1 : strmTarget << sfmtData << m_uStorage.c1Immediate; break; case tCIDMacroEng::EOpCodes::PushImCard8 : strmTarget << sfmtData << m_uStorage.c8Immediate; break; case tCIDMacroEng::EOpCodes::PushImChar : strmTarget << sfmtData << m_uStorage.chImmediate; break; case tCIDMacroEng::EOpCodes::PushImFloat4 : strmTarget << sfmtData << m_uStorage.f4Immediate; break; case tCIDMacroEng::EOpCodes::PushImFloat8 : strmTarget << sfmtData << m_uStorage.f8Immediate; break; case tCIDMacroEng::EOpCodes::PushImInt1 : strmTarget << sfmtData << m_uStorage.i1Immediate; break; case tCIDMacroEng::EOpCodes::PushImInt2 : strmTarget << sfmtData << m_uStorage.i2Immediate; break; case tCIDMacroEng::EOpCodes::PushImInt4 : strmTarget << sfmtData << m_uStorage.i4Immediate; break; case tCIDMacroEng::EOpCodes::CallExcept : case tCIDMacroEng::EOpCodes::CallParent : case tCIDMacroEng::EOpCodes::CallThis : case tCIDMacroEng::EOpCodes::PushLocal : case tCIDMacroEng::EOpCodes::PushMember : case tCIDMacroEng::EOpCodes::PushParm : case tCIDMacroEng::EOpCodes::PushStrPoolItem : case tCIDMacroEng::EOpCodes::PushTempConst : case tCIDMacroEng::EOpCodes::PushTempVar : case tCIDMacroEng::EOpCodes::TableJump : case tCIDMacroEng::EOpCodes::TypeCast : strmTarget << sfmtData << m_uStorage.ac2Indices[0]; break; case tCIDMacroEng::EOpCodes::ColIndex : case tCIDMacroEng::EOpCodes::Copy : case tCIDMacroEng::EOpCodes::CondEnumInc : case tCIDMacroEng::EOpCodes::EndTry : case tCIDMacroEng::EOpCodes::FlipTop : case tCIDMacroEng::EOpCodes::LogicalAnd : case tCIDMacroEng::EOpCodes::LogicalOr : case tCIDMacroEng::EOpCodes::LogicalXor : case tCIDMacroEng::EOpCodes::Negate : case tCIDMacroEng::EOpCodes::NoOp : case tCIDMacroEng::EOpCodes::PopTop : case tCIDMacroEng::EOpCodes::PopToReturn : case tCIDMacroEng::EOpCodes::PushCurLine : case tCIDMacroEng::EOpCodes::PushException : case tCIDMacroEng::EOpCodes::PushThis : case tCIDMacroEng::EOpCodes::ResetEnum : case tCIDMacroEng::EOpCodes::Return : // No data break; default : strmTarget << L"???"; break; } } tCIDLib::TVoid TMEngOpCode::SetOpCode(const tCIDMacroEng::EOpCodes eOpCode) { TRawMem::SetMemBuf(&m_uStorage, tCIDLib::TCard1(0), sizeof(m_uStorage)); m_eOpCode = eOpCode; } tCIDLib::TVoid TMEngOpCode::SetSingleIndex(const tCIDMacroEng::EOpCodes eOpCode , const tCIDLib::TCard2 c2Index) { TRawMem::SetMemBuf(&m_uStorage, tCIDLib::TCard1(0), sizeof(m_uStorage)); m_eOpCode = eOpCode; m_uStorage.ac2Indices[0] = c2Index; } tCIDLib::TVoid TMEngOpCode::SetDoubleIndex(const tCIDMacroEng::EOpCodes eOpCode , const tCIDLib::TCard2 c2Index1 , const tCIDLib::TCard2 c2Index2) { TRawMem::SetMemBuf(&m_uStorage, tCIDLib::TCard1(0), sizeof(m_uStorage)); m_eOpCode = eOpCode; m_uStorage.ac2Indices[0] = c2Index1; m_uStorage.ac2Indices[1] = c2Index2; } tCIDLib::TVoid TMEngOpCode::SetImmediate( const tCIDMacroEng::EOpCodes eOpCode , const tCIDLib::TBoolean bImmediate) { TRawMem::SetMemBuf(&m_uStorage, tCIDLib::TCard1(0), sizeof(m_uStorage)); m_eOpCode = eOpCode; m_uStorage.bImmediate = bImmediate; } tCIDLib::TVoid TMEngOpCode::SetImmediate( const tCIDMacroEng::EOpCodes eOpCode , const tCIDLib::TCard1 c1Immediate) { TRawMem::SetMemBuf(&m_uStorage, tCIDLib::TCard1(0), sizeof(m_uStorage)); m_eOpCode = eOpCode; m_uStorage.c1Immediate = c1Immediate; } tCIDLib::TVoid TMEngOpCode::SetImmediate( const tCIDMacroEng::EOpCodes eOpCode , const tCIDLib::TCard2 c2Immediate) { TRawMem::SetMemBuf(&m_uStorage, tCIDLib::TCard1(0), sizeof(m_uStorage)); m_eOpCode = eOpCode; m_uStorage.c2Immediate = c2Immediate; } tCIDLib::TVoid TMEngOpCode::SetImmediate( const tCIDMacroEng::EOpCodes eOpCode , const tCIDLib::TCard4 c4Immediate) { TRawMem::SetMemBuf(&m_uStorage, tCIDLib::TCard1(0), sizeof(m_uStorage)); m_eOpCode = eOpCode; m_uStorage.c4Immediate = c4Immediate; } tCIDLib::TVoid TMEngOpCode::SetImmediate( const tCIDMacroEng::EOpCodes eOpCode , const tCIDLib::TCard8 c8Immediate) { TRawMem::SetMemBuf(&m_uStorage, tCIDLib::TCard1(0), sizeof(m_uStorage)); m_eOpCode = eOpCode; m_uStorage.c8Immediate = c8Immediate; } tCIDLib::TVoid TMEngOpCode::SetImmediate( const tCIDMacroEng::EOpCodes eOpCode , const tCIDLib::TCh chImmediate) { TRawMem::SetMemBuf(&m_uStorage, tCIDLib::TCard1(0), sizeof(m_uStorage)); m_eOpCode = eOpCode; m_uStorage.chImmediate = chImmediate; } tCIDLib::TVoid TMEngOpCode::SetImmediate( const tCIDMacroEng::EOpCodes eOpCode , const tCIDLib::TFloat4 f4Immediate) { TRawMem::SetMemBuf(&m_uStorage, tCIDLib::TCard1(0), sizeof(m_uStorage)); m_eOpCode = eOpCode; m_uStorage.f4Immediate = f4Immediate; } tCIDLib::TVoid TMEngOpCode::SetImmediate( const tCIDMacroEng::EOpCodes eOpCode , const tCIDLib::TFloat8 f8Immediate) { TRawMem::SetMemBuf(&m_uStorage, tCIDLib::TCard1(0), sizeof(m_uStorage)); m_eOpCode = eOpCode; m_uStorage.f8Immediate = f8Immediate; } tCIDLib::TVoid TMEngOpCode::SetImmediate( const tCIDMacroEng::EOpCodes eOpCode , const tCIDLib::TInt1 i1Immediate) { TRawMem::SetMemBuf(&m_uStorage, tCIDLib::TCard1(0), sizeof(m_uStorage)); m_eOpCode = eOpCode; m_uStorage.i1Immediate = i1Immediate; } tCIDLib::TVoid TMEngOpCode::SetImmediate( const tCIDMacroEng::EOpCodes eOpCode , const tCIDLib::TInt2 i2Immediate) { TRawMem::SetMemBuf(&m_uStorage, tCIDLib::TCard1(0), sizeof(m_uStorage)); m_eOpCode = eOpCode; m_uStorage.i2Immediate = i2Immediate; } tCIDLib::TVoid TMEngOpCode::SetImmediate( const tCIDMacroEng::EOpCodes eOpCode , const tCIDLib::TInt4 i4Immediate) { TRawMem::SetMemBuf(&m_uStorage, tCIDLib::TCard1(0), sizeof(m_uStorage)); m_eOpCode = eOpCode; m_uStorage.i4Immediate = i4Immediate; } // --------------------------------------------------------------------------- // TMEngOpCode: Private, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::TVoid TMEngOpCode::BadIndex(const tCIDLib::TCard4 c4Index) const { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadOpcodeIndex , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , TCardinal(c4Index) ); }
e5ea3dbf476c874ba660d3670b7071380fdad42c
b86af7b533294f141d90053a611e4957db046961
/examples/cpp/Draw.cpp
101b0ab81b9c868609535ec52dafdd10b18b328f
[ "MIT" ]
permissive
khanhgithead/Open3D
8bdc3501a81f097a20fadc14744058e1024e8c7e
caa3ae0a533594ce5055f07b32cf96c595f6dbd5
refs/heads/master
2022-01-30T06:06:58.452831
2022-01-16T01:09:24
2022-01-16T01:09:24
188,728,657
0
0
NOASSERTION
2019-05-26T20:29:15
2019-05-26T20:29:15
null
UTF-8
C++
false
false
12,903
cpp
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2018-2021 www.open3d.org // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // ---------------------------------------------------------------------------- #include <cstdlib> #include "open3d/Open3D.h" using namespace open3d; const std::string TEST_DIR = "../../../examples/test_data"; double GetRandom() { return double(std::rand()) / double(RAND_MAX); } std::shared_ptr<geometry::PointCloud> MakePointCloud( int npts, const Eigen::Vector3d center, double radius, bool colorize) { auto cloud = std::make_shared<geometry::PointCloud>(); cloud->points_.reserve(npts); for (int i = 0; i < npts; ++i) { cloud->points_.push_back({radius * GetRandom() + center.x(), radius * GetRandom() + center.y(), radius * GetRandom() + center.z()}); } if (colorize) { cloud->colors_.reserve(npts); for (int i = 0; i < npts; ++i) { cloud->colors_.push_back({GetRandom(), GetRandom(), GetRandom()}); } } return cloud; } void SingleObject() { // No colors, no normals, should appear unlit black auto cube = geometry::TriangleMesh::CreateBox(1, 2, 4); visualization::Draw({cube}); } void MultiObjects() { const double pc_rad = 1.0; auto pc_nocolor = MakePointCloud(100, {0.0, -2.0, 0.0}, pc_rad, false); auto pc_color = MakePointCloud(100, {3.0, -2.0, 0.0}, pc_rad, true); const double r = 0.4; auto sphere_unlit = geometry::TriangleMesh::CreateSphere(r); sphere_unlit->Translate({0.0, 1.0, 0.0}); auto sphere_colored_unlit = geometry::TriangleMesh::CreateSphere(r); sphere_colored_unlit->PaintUniformColor({1.0, 0.0, 0.0}); sphere_colored_unlit->Translate({2.0, 1.0, 0.0}); auto sphere_lit = geometry::TriangleMesh::CreateSphere(r); sphere_lit->ComputeVertexNormals(); sphere_lit->Translate({4, 1, 0}); auto sphere_colored_lit = geometry::TriangleMesh::CreateSphere(r); sphere_colored_lit->ComputeVertexNormals(); sphere_colored_lit->PaintUniformColor({0.0, 1.0, 0.0}); sphere_colored_lit->Translate({6, 1, 0}); auto big_bbox = std::make_shared<geometry::AxisAlignedBoundingBox>( Eigen::Vector3d{-pc_rad, -3, -pc_rad}, Eigen::Vector3d{6.0 + r, 1.0 + r, pc_rad}); big_bbox->color_ = {0.0, 0.0, 0.0}; auto bbox = sphere_unlit->GetAxisAlignedBoundingBox(); auto sphere_bbox = std::make_shared<geometry::AxisAlignedBoundingBox>( bbox.min_bound_, bbox.max_bound_); sphere_bbox->color_ = {1.0, 0.5, 0.0}; auto lines = geometry::LineSet::CreateFromAxisAlignedBoundingBox( sphere_lit->GetAxisAlignedBoundingBox()); lines->PaintUniformColor({0.0, 1.0, 0.0}); auto lines_colored = geometry::LineSet::CreateFromAxisAlignedBoundingBox( sphere_colored_lit->GetAxisAlignedBoundingBox()); lines_colored->PaintUniformColor({0.0, 0.0, 1.0}); visualization::Draw({pc_nocolor, pc_color, sphere_unlit, sphere_colored_unlit, sphere_lit, sphere_colored_lit, big_bbox, sphere_bbox, lines, lines_colored}); } void Actions() { const char *SOURCE_NAME = "Source"; const char *RESULT_NAME = "Result (Poisson reconstruction)"; const char *TRUTH_NAME = "Ground truth"; auto bunny = std::make_shared<geometry::TriangleMesh>(); io::ReadTriangleMesh(TEST_DIR + "/Bunny.ply", *bunny); if (bunny->vertices_.empty()) { utility::LogError( "Please download the Standford Bunny dataset using:\n" " cd <open3d_dir>/examples/python\n" " python -c 'from open3d_example import *; " "get_bunny_mesh()'"); return; } bunny->PaintUniformColor({1, 0.75, 0}); bunny->ComputeVertexNormals(); auto cloud = std::make_shared<geometry::PointCloud>(); cloud->points_ = bunny->vertices_; cloud->normals_ = bunny->vertex_normals_; cloud->PaintUniformColor({0, 0.2, 1.0}); auto make_mesh = [SOURCE_NAME, RESULT_NAME]( visualization::visualizer::O3DVisualizer &o3dvis) { std::shared_ptr<geometry::PointCloud> source = std::dynamic_pointer_cast<geometry::PointCloud>( o3dvis.GetGeometry(SOURCE_NAME).geometry); auto mesh = std::get<0>( geometry::TriangleMesh::CreateFromPointCloudPoisson(*source)); mesh->PaintUniformColor({1, 1, 1}); mesh->ComputeVertexNormals(); o3dvis.AddGeometry(RESULT_NAME, mesh); o3dvis.ShowGeometry(SOURCE_NAME, false); }; auto toggle_result = [TRUTH_NAME, RESULT_NAME](visualization::visualizer::O3DVisualizer &o3dvis) { bool truth_vis = o3dvis.GetGeometry(TRUTH_NAME).is_visible; o3dvis.ShowGeometry(TRUTH_NAME, !truth_vis); o3dvis.ShowGeometry(RESULT_NAME, truth_vis); }; visualization::Draw({visualization::DrawObject(SOURCE_NAME, cloud), visualization::DrawObject(TRUTH_NAME, bunny, false)}, "Open3D: Draw Example: Actions", 1024, 768, {{"Create Mesh", make_mesh}, {"Toggle truth/result", toggle_result}}); } Eigen::Matrix4d_u GetICPTransform( const geometry::PointCloud &source, const geometry::PointCloud &target, const std::vector<visualization::visualizer::O3DVisualizerSelections:: SelectedIndex> &source_picked, const std::vector<visualization::visualizer::O3DVisualizerSelections:: SelectedIndex> &target_picked) { std::vector<Eigen::Vector2i> indices; for (size_t i = 0; i < source_picked.size(); ++i) { indices.push_back({source_picked[i].index, target_picked[i].index}); } // Estimate rough transformation using correspondences pipelines::registration::TransformationEstimationPointToPoint p2p; auto trans_init = p2p.ComputeTransformation(source, target, indices); // Point-to-point ICP for refinement const double max_dist = 0.03; // 3cm distance threshold auto result = pipelines::registration::RegistrationICP( source, target, max_dist, trans_init); return result.transformation_; } void Selections() { std::cout << "Selection example:" << std::endl; std::cout << " One set: pick three points from the source (yellow), " << std::endl; std::cout << " then pick the same three points in the target" "(blue) cloud" << std::endl; std::cout << " Two sets: pick three points from the source cloud, " << std::endl; std::cout << " then create a new selection set, and pick the" << std::endl; std::cout << " three points from the target." << std::endl; const auto cloud0_path = TEST_DIR + "/ICP/cloud_bin_0.pcd"; const auto cloud1_path = TEST_DIR + "/ICP/cloud_bin_2.pcd"; auto source = std::make_shared<geometry::PointCloud>(); io::ReadPointCloud(cloud0_path, *source); if (source->points_.empty()) { utility::LogError("Could not open {}", cloud0_path); return; } auto target = std::make_shared<geometry::PointCloud>(); io::ReadPointCloud(cloud1_path, *target); if (target->points_.empty()) { utility::LogError("Could not open {}", cloud1_path); return; } source->PaintUniformColor({1.000, 0.706, 0.000}); target->PaintUniformColor({0.000, 0.651, 0.929}); const char *source_name = "Source (yellow)"; const char *target_name = "Target (blue)"; auto DoICPOneSet = [source, target, source_name, target_name](visualization::visualizer::O3DVisualizer &o3dvis) { auto sets = o3dvis.GetSelectionSets(); if (sets.empty()) { utility::LogWarning( "You must select points for correspondence before " "running ICP!"); return; } auto &source_picked_set = sets[0][source_name]; auto &target_picked_set = sets[0][target_name]; std::vector<visualization::visualizer::O3DVisualizerSelections:: SelectedIndex> source_picked(source_picked_set.begin(), source_picked_set.end()); std::vector<visualization::visualizer::O3DVisualizerSelections:: SelectedIndex> target_picked(target_picked_set.begin(), target_picked_set.end()); std::sort(source_picked.begin(), source_picked.end()); std::sort(target_picked.begin(), target_picked.end()); auto t = GetICPTransform(*source, *target, source_picked, target_picked); source->Transform(t); // Update the source geometry o3dvis.RemoveGeometry(source_name); o3dvis.AddGeometry(source_name, source); }; auto DoICPTwoSets = [source, target, source_name, target_name](visualization::visualizer::O3DVisualizer &o3dvis) { auto sets = o3dvis.GetSelectionSets(); if (sets.size() < 2) { utility::LogWarning( "You must have at least two sets of selected " "points before running ICP!"); return; } auto &source_picked_set = sets[0][source_name]; auto &target_picked_set = sets[1][target_name]; std::vector<visualization::visualizer::O3DVisualizerSelections:: SelectedIndex> source_picked(source_picked_set.begin(), source_picked_set.end()); std::vector<visualization::visualizer::O3DVisualizerSelections:: SelectedIndex> target_picked(target_picked_set.begin(), target_picked_set.end()); std::sort(source_picked.begin(), source_picked.end()); std::sort(target_picked.begin(), target_picked.end()); auto t = GetICPTransform(*source, *target, source_picked, target_picked); source->Transform(t); // Update the source geometry o3dvis.RemoveGeometry(source_name); o3dvis.AddGeometry(source_name, source); }; visualization::Draw({visualization::DrawObject(source_name, source), visualization::DrawObject(target_name, target)}, "Open3D: Draw example: Selection", 1024, 768, {{"ICP Registration (one set)", DoICPOneSet}, {"ICP Registration (two sets)", DoICPTwoSets}}); } int main(int argc, char **argv) { if (!utility::filesystem::DirectoryExists(TEST_DIR)) { utility::LogError( "This example needs to be run from the <build>/bin/examples " "directory"); } SingleObject(); MultiObjects(); Actions(); Selections(); }
33a239b9940addb47b1efbee0b2e03d46648a5fc
299648a8c633728662d0b7651cd98afdc28db902
/src/thirdparty/sentry-native/external/crashpad/snapshot/win/thread_snapshot_win.h
64ec43de0f268c5eadfbbbc8e0a57bba642c6fbd
[ "BSD-3-Clause", "MIT", "Apache-2.0" ]
permissive
aardvarkxr/aardvark
2978277b34c2c3894d6aafc4c590f3bda50f4d43
300d0d5e9b872ed839fae932c56eff566967d24b
refs/heads/master
2023-01-12T18:42:10.705028
2021-08-18T04:09:02
2021-08-18T04:09:02
182,431,653
183
25
BSD-3-Clause
2023-01-07T12:42:14
2019-04-20T16:55:30
TypeScript
UTF-8
C++
false
false
3,249
h
// Copyright 2015 The Crashpad Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef CRASHPAD_SNAPSHOT_WIN_THREAD_SNAPSHOT_WIN_H_ #define CRASHPAD_SNAPSHOT_WIN_THREAD_SNAPSHOT_WIN_H_ #include <stdint.h> #include <memory> #include <vector> #include "base/macros.h" #include "build/build_config.h" #include "snapshot/cpu_context.h" #include "snapshot/memory_snapshot.h" #include "snapshot/memory_snapshot_generic.h" #include "snapshot/thread_snapshot.h" #include "snapshot/win/process_reader_win.h" #include "util/misc/initialization_state_dcheck.h" namespace crashpad { class ProcessReaderWin; namespace internal { //! \brief A ThreadSnapshot of a thread in a running (or crashed) process on a //! Windows system. class ThreadSnapshotWin final : public ThreadSnapshot { public: ThreadSnapshotWin(); ~ThreadSnapshotWin() override; //! \brief Initializes the object. //! //! \param[in] process_reader A ProcessReaderWin for the process containing //! the thread. //! \param[in] process_reader_thread The thread within the ProcessReaderWin //! for which the snapshot should be created. //! \param[in,out] gather_indirectly_referenced_memory_bytes_remaining If //! non-null, add extra memory regions to the snapshot pointed to by the //! thread's stack. The size of the regions added is subtracted from the //! count, and when it's `0`, no more regions will be added. //! //! \return `true` if the snapshot could be created, `false` otherwise with //! an appropriate message logged. bool Initialize( ProcessReaderWin* process_reader, const ProcessReaderWin::Thread& process_reader_thread, uint32_t* gather_indirectly_referenced_memory_bytes_remaining); // ThreadSnapshot: const CPUContext* Context() const override; const MemorySnapshot* Stack() const override; uint64_t ThreadID() const override; int SuspendCount() const override; int Priority() const override; uint64_t ThreadSpecificDataAddress() const override; std::vector<const MemorySnapshot*> ExtraMemory() const override; private: union { #if defined(ARCH_CPU_X86_FAMILY) CPUContextX86 x86; CPUContextX86_64 x86_64; #elif defined(ARCH_CPU_ARM64) CPUContextARM64 arm64; #else #error Unsupported Windows Arch #endif } context_union_; CPUContext context_; MemorySnapshotGeneric stack_; MemorySnapshotGeneric teb_; ProcessReaderWin::Thread thread_; InitializationStateDcheck initialized_; std::vector<std::unique_ptr<MemorySnapshotGeneric>> pointed_to_memory_; DISALLOW_COPY_AND_ASSIGN(ThreadSnapshotWin); }; } // namespace internal } // namespace crashpad #endif // CRASHPAD_SNAPSHOT_WIN_THREAD_SNAPSHOT_WIN_H_
f82bab34875c26f17c9f1f558678d342899e9c83
c358397368d34a4f3b6d0bab4a03179f1c155a73
/assignment3/assignment3/Main.cpp
e498a356dfb9636a853ff71ec62e4544254e02f4
[]
no_license
nguyengiahy/COS30008
b0e7d5e4ae6fe2dddca319e86123cef7e5061ea8
e70b1aa0c6e4460163dc8761088ad4853cb1f910
refs/heads/master
2021-09-26T16:41:40.884106
2021-09-11T17:52:19
2021-09-11T17:52:19
249,945,885
1
3
null
null
null
null
UTF-8
C++
false
false
1,832
cpp
#include <iostream> #include <cstdlib> #include <iomanip> #include "FibonacciSequence.h" #include "FibonacciSequenceIterator.h" using namespace std; int main(int argc, char* argv[]) { if (argc < 2) { cerr << "Missing argument!" << endl; cerr << "Usage: FibonacciIterator number" << endl; return 1; } cout << "Fibonacci sequence up to " << argv[1] << ":" << endl; FibonacciSequence lSequence(atoi(argv[1])); // test problem 1 // (not including iterator methods begin() and end()) for (unsigned long i = 1; i <= lSequence.getLimit(); i++) { cout << i << ":\t" << setw(5) << lSequence.current() << endl; lSequence.advance(); } // test problem 2 as well as begin() and end() of problem 1 // C++11 range loop cout << "Fibonacci sequence 1..20:" << endl; unsigned long i = 1; for (const unsigned long& n : lSequence) { cout << i++ << ":\t" << setw(5) << n << endl; } // Old-style loops cout << "Fibonacci sequence 1..20 (old-style):" << endl; FibonacciSequenceIterator lIteratorA = lSequence.begin(); unsigned long a = 1; for (; lIteratorA != lIteratorA.end(); lIteratorA++) { cout << a++ << ":\t" << setw(5) << *lIteratorA << endl; } cout << "Once more:" << endl; FibonacciSequenceIterator lIteratorB = lIteratorA.begin(); unsigned long b = 1; for (; lIteratorB != lIteratorB.end(); ++lIteratorB) { cout << b++ << ":\t" << setw(5) << *lIteratorB << endl; } cout << "Fibonacci sequence 1..21?:" << endl; FibonacciSequenceIterator lIteratorC = lIteratorB.begin(); unsigned long c = 1; while (lIteratorC != lIteratorC.end()) { cout << c++ << ":\t" << setw(5) << *lIteratorC++ << endl; } return 0; }
162560a043c539e71fb143c33c70eccc7a144ec1
8784b6f42399b39afcefb4c1cb1991c152f76ae3
/Barbarian.cpp
128d87a82f05d74470cf1c0764ffcc3c5bb699a8
[]
no_license
lee-vincent/CPP-User-Input-Controlled-Creature-Battle
56fc828fb20741dae08cc4b44b27e361e3229ea5
9bcd750b22a3a6c39d058a80db3c2f50e9a3aaa2
refs/heads/master
2021-01-21T15:57:46.105443
2017-02-10T23:54:43
2017-02-10T23:54:43
81,617,605
0
0
null
null
null
null
UTF-8
C++
false
false
2,441
cpp
// // Barbarian.cpp // assignment3 // // Created by Vincent Lee on 11/8/15. // Copyright © 2015 10k Bulbs. All rights reserved. // #include "Barbarian.h" #include <sstream> #include <iostream> #include <stdlib.h> Barbarian::Barbarian() { Construct(); std::string _name; std::ostringstream convert; convert << (int)rand() % 1000; _name = convert.str(); this->name = "Barbarian_" + _name; this->debug = true; this->team = team; this->team = -1; } Barbarian::Barbarian(std::string name, bool debug, int team) { Construct(); this->name = "Barbarian_" + name; this->debug = debug; this->team = team; } void Barbarian::Construct() { strengthPoints = 12; armor = 0; achilles = false; } void Barbarian::Attack(Creature *opponent) { int attack = 0; attack += rand() % 6 + 1; attack += rand() % 6 + 1; if(debug) std::cout << name << " attacking " << opponent->GetName() << "." << " Attack = " << attack << std::endl; if (achilles) { attack /= 2; if(debug) std::cout << name << " Achilles injured, Attack = " << attack << std::endl; } int opponentDefense = opponent->Defense(); if(opponentDefense == 0) { //Shadow produces 0 if missed return; } else { int damage = attack - opponentDefense; if(damage < 0) damage = 0; opponent->DoDamage(damage, false); } } void Barbarian::DoDamage(int damage, bool achillesInjured) { if(achillesInjured) this->achilles = true; int appliedDamage = damage - armor; if(appliedDamage < 0) appliedDamage = 0; if(debug) std::cout << name << " taking damage of = " << appliedDamage << std::endl; strengthPoints -= appliedDamage; if(debug) std::cout << name << " strengthPoints = " << strengthPoints << std::endl; } int Barbarian::Defense() { int defense = 0; defense += rand() % 6 + 1; defense += rand() % 6 + 1; if(debug) std::cout << name << " defense = " << defense << std::endl; return defense; } void Barbarian::Heal() { if(rand() % 3 == 0) { strengthPoints = 12; } else { int healPoints = 0; healPoints += rand() % (12 - (strengthPoints -1)) + 1; } if(debug) std::cout << name << " Healed. strengthPoints = " << strengthPoints << std::endl; }
1428a99266755488c38751ebba14881c6a628c89
d12f7bf84bba8f19ffe31b630a77c55e8432a4b7
/dynamic_programming/Longest_Common_Subsequence_3/main.cpp
c67c7d1e2082dbffa83a1444466baeb60f7f3158
[]
no_license
shreyasmishragithub/AlgorithmsAndDataStructures
279a6d74bbdbab211d64c7c0188f0e864b461f80
129a8bbaec632b52ca0463940cd8bd186cf5d285
refs/heads/master
2021-06-03T05:24:14.574141
2016-07-23T06:15:36
2016-07-23T06:15:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,657
cpp
// // main.cpp // Longest_Common_Subsequence // // Created by Nitesh Thali on 6/29/16. // Copyright © 2016 Nitesh Thali. All rights reserved. /* Question Ref: https://www.coursera.org/learn/algorithmic-toolbox/home/welcome Program to calculate LCS of 3 sequences. Algorithm: To length of LCS of two sequences and then generate all the sequences of that length. Then one at a time and look for LCS in third sequnce. */ #include <iostream> #include <vector> using namespace std; int lcs3(vector<int> &a, vector<int> &b, vector<int> &c) { int m = (int)a.size(), n = (int)b.size(), l=(int) c.size(); vector < vector <vector<int > > > dp (m+1, vector < vector <int> > (n+1, vector<int> (l+1))); int i, j, k; for (i=0; i<=m; i++){ for (j=0; j<=n; j++){ for (j=0; j<=n; j++){ if (i == 0 || j == 0 || k==0) dp[i][j][k] = 0; else if (a[i-1] == b[j-1] == c[k-1]) dp[i][j][k] = dp[i-1][j-1][k-1] + 1; else dp[i][j][k] = max(dp[i][j][k-1], dp[i][j-1][k]); } } } return dp[m][n][k]; } int main() { size_t an; std::cin >> an; vector<int> a(an); for (size_t i = 0; i < an; i++) { std::cin >> a[i]; } size_t bn; std::cin >> bn; vector<int> b(bn); for (size_t i = 0; i < bn; i++) { std::cin >> b[i]; } size_t cn; std::cin >> cn; vector<int> c(cn); for (size_t i = 0; i < cn; i++) { std::cin >> c[i]; } std::cout << lcs3(a, b, c) << std::endl; }
4074b4906e7f7d3d06573699b965862331ebacc8
02d3c6502bf08842599f07410aed99c2ca6a5ceb
/src/coxph_data.cpp
8518c98a4f8967812bacc4c8ef834ad425b991cd
[]
no_license
saemundo/probabel
8d37b055aea3c6584e258785ad2bad4d2ab2cf32
ba8caaab128a4bccd8efca6489dbf11db12c77a1
refs/heads/master
2021-01-20T18:10:03.214896
2016-06-03T06:30:06
2016-06-03T06:30:06
60,323,752
0
0
null
null
null
null
UTF-8
C++
false
false
15,271
cpp
/* * coxph_data.cpp * * Created on: Mar 31, 2012 * Author: mkooyman * * * Copyright (C) 2009--2015 Various members of the GenABEL team. See * the SVN commit logs for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program 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 * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * */ #include "coxph_data.h" #include <iostream> #include <cmath> extern "C" { #include "survproto.h" } // #include "reg1.h" #include "fvlib/AbstractMatrix.h" #include "fvlib/CastUtils.h" #include "fvlib/const.h" #include "fvlib/convert_util.h" #include "fvlib/FileVector.h" #include "fvlib/frutil.h" #include "fvlib/frversion.h" #include "fvlib/Logger.h" #include "fvlib/Transposer.h" // compare for sort of times int cmpfun(const void *a, const void *b) { double el1 = *(double*) a; double el2 = *(double*) b; if (el1 > el2) { return 1; } if (el1 < el2) { return -1; } if (el1 == el2) { return 0; } // You should never come here... return -9; } coxph_data::coxph_data(const coxph_data &obj) : sstat(obj.sstat), offset(obj.offset), strata(obj.strata), X(obj.X), order(obj.order) { nids = obj.nids; ncov = obj.ncov; ngpreds = obj.ngpreds; weights = obj.weights; stime = obj.stime; gcount = 0; freq = 0; masked_data = new unsigned short int[nids]; for (int i = 0; i < nids; i++) { masked_data[i] = obj.masked_data[i]; } } coxph_data::coxph_data(phedata &phed, gendata &gend, const int snpnum) { freq = 0; gcount = 0; nids = gend.nids; masked_data = new unsigned short int[nids]; for (int i = 0; i < nids; i++) { masked_data[i] = 0; } ngpreds = gend.ngpreds; if (snpnum >= 0) { ncov = phed.ncov + ngpreds; } else { ncov = phed.ncov; } if (phed.noutcomes != 2) { std::cerr << "coxph_data: number of outcomes should be 2 (now: " << phed.noutcomes << ")\n"; exit(1); } X.reinit(nids, (ncov + 1)); stime.reinit(nids, 1); sstat.reinit(nids, 1); weights.reinit(nids, 1); offset.reinit(nids, 1); strata.reinit(nids, 1); order.reinit(nids, 1); for (int i = 0; i < nids; i++) { stime[i] = (phed.Y).get(i, 0); sstat[i] = static_cast<int>((phed.Y).get(i, 1)); if (sstat[i] != 1 && sstat[i] != 0) { std::cerr << "coxph_data: status not 0/1 " <<"(correct order: id, fuptime, status ...)" << endl; exit(1); } } // Add a column with a constant (=1) to the X matrix (the mean) for (int i = 0; i < nids; i++) { X.put(1., i, 0); } for (int j = 1; j <= phed.ncov; j++) { for (int i = 0; i < nids; i++) { X.put((phed.X).get(i, j - 1), i, j); } } if (snpnum > 0) { for (int j = 0; j < ngpreds; j++) { double *snpdata = new double[nids]; gend.get_var(snpnum * ngpreds + j, snpdata); for (int i = 0; i < nids; i++) { X.put(snpdata[i], i, (ncov - ngpreds + j)); } delete[] snpdata; } } for (int i = 0; i < nids; i++) { weights[i] = 1.0; offset[i] = 0.0; strata[i] = 0; } // sort by time double *tmptime = new double[nids]; int *passed_sorted = new int[nids]; for (int i = 0; i < nids; i++) { tmptime[i] = stime[i]; passed_sorted[i] = 0; } qsort(tmptime, nids, sizeof(double), cmpfun); for (int i = 0; i < nids; i++) { int passed = 0; for (int j = 0; j < nids; j++) { if (tmptime[j] == stime[i]) { if (!passed_sorted[j]) { order[i] = j; passed_sorted[j] = 1; passed = 1; break; } } } if (passed != 1) { std::cerr << "cannot recover element " << i << "\n"; exit(1); } } stime = reorder(stime, order); sstat = reorder(sstat, order); weights = reorder(weights, order); strata = reorder(strata, order); offset = reorder(offset, order); X = reorder(X, order); // The coxfit2() function expects data in column major order. X = transpose(X); // X.print(); // offset.print(); // weights.print(); // stime.print(); // sstat.print(); delete[] tmptime; delete[] passed_sorted; } void coxph_data::update_snp(gendata *gend, const int snpnum) { /** * This is the main part of the fix of bug #1846 * (C) of the fix: * UMC St Radboud Nijmegen, * Dept of Epidemiology & Biostatistics, * led by Prof. B. Kiemeney * * Note this sorts by "order"!!! * Here we deal with transposed X, hence last two arguments are swapped * compared to the other 'update_snp' * Also, the starting column-1 is not necessary for cox X therefore * 'ncov-j' changes to 'ncov-j-1' **/ // reset counter for frequency since it is a new snp gcount = 0; freq = 0.0; for (int j = 0; j < ngpreds; j++) { double *snpdata = new double[nids]; for (int i = 0; i < nids; i++) { masked_data[i] = 0; } gend->get_var(snpnum * ngpreds + j, snpdata); for (int i = 0; i < nids; i++) { X.put(snpdata[i], (ncov - j), order[i]); if (std::isnan(snpdata[i])) { masked_data[order[i]] = 1; // snp not masked } else { // check for first predictor if (j == 0) { gcount++; if (ngpreds == 1) { freq += snpdata[i] * 0.5; } else if (ngpreds == 2) { freq += snpdata[i]; } } else if (j == 1) { // add second genotype in two predicor data form freq += snpdata[i] * 0.5; } } // end std::isnan(snpdata[i]) snp } // end i for loop delete[] snpdata; } // end ngpreds loop freq /= static_cast<double>(gcount); // Allele frequency } /** * update_snp() adds SNP information to the design matrix. This * function allows you to strip that information from X again. This * is used for example when calculating the null model. * */ void coxph_data::remove_snp_from_X() { if (ngpreds == 1) { X.delete_row(X.nrow -1); } else if (ngpreds == 2) { X.delete_row(X.nrow -1); X.delete_row(X.nrow -1); } else { cerr << "Error: ngpreds should be 1 or 2. " << "You should never come here!\n"; } } coxph_data::~coxph_data() { delete[] coxph_data::masked_data; // delete X; // delete sstat; // delete stime; // delete weights; // delete offset; // delete strata; // delete order; } coxph_data coxph_data::get_unmasked_data() { coxph_data to; // = coxph_data(*this); // filter missing data int nmeasured = 0; for (int i = 0; i < nids; i++) { if (masked_data[i] == 0) { nmeasured++; } } to.nids = nmeasured; to.ncov = ncov; to.ngpreds = ngpreds; int dim1X = X.nrow; (to.weights).reinit(to.nids, 1); (to.stime).reinit(to.nids, 1); (to.sstat).reinit(to.nids, 1); (to.offset).reinit(to.nids, 1); (to.strata).reinit(to.nids, 1); (to.order).reinit(to.nids, 1); (to.X).reinit(dim1X, to.nids); int j = 0; for (int i = 0; i < nids; i++) { if (masked_data[i] == 0) { (to.weights).put(weights.get(i, 0), j, 0); (to.stime).put(stime.get(i, 0), j, 0); (to.sstat).put(sstat.get(i, 0), j, 0); (to.offset).put(offset.get(i, 0), j, 0); (to.strata).put(strata.get(i, 0), j, 0); (to.order).put(order.get(i, 0), j, 0); for (int nc = 0; nc < dim1X; nc++) { (to.X).put(X.get(nc, i), nc, j); } j++; } } //delete [] to.masked_data; to.masked_data = new unsigned short int[to.nids]; for (int i = 0; i < to.nids; i++) { to.masked_data[i] = 0; } return (to); } coxph_reg::coxph_reg(coxph_data &cdatain) { coxph_data cdata = cdatain.get_unmasked_data(); beta.reinit(cdata.X.nrow, 1); sebeta.reinit(cdata.X.nrow, 1); loglik = - INFINITY; sigma2 = -1.; chi2_score = -1.; niter = 0; } void coxph_reg::estimate(coxph_data &cdatain, const int verbose, int maxiter, double eps, double tol_chol, const int model, const int interaction, const int ngpreds, const bool iscox, const int nullmodel, const mlinfo &snpinfo, const int cursnp) { coxph_data cdata = cdatain.get_unmasked_data(); mematrix<double> X = t_apply_model(cdata.X, model, interaction, ngpreds, iscox, nullmodel); int length_beta = X.nrow; beta.reinit(length_beta, 1); sebeta.reinit(length_beta, 1); mematrix<double> newoffset = cdata.offset - (cdata.offset).column_mean(0); mematrix<double> means(X.nrow, 1); for (int i = 0; i < X.nrow; i++) { beta[i] = 0.; } mematrix<double> u(X.nrow, 1); mematrix<double> imat(X.nrow, X.nrow); double *work = new double[X.ncol * 2 + 2 * (X.nrow) * (X.nrow) + 3 * (X.nrow)]; double loglik_int[2]; int flag; // Use Efron method of handling ties (for Breslow: 0.0), like in // R's coxph() double sctest = 1.0; // Set the maximum number of iterations that coxfit2() will run to // the default value from the class definition. int maxiterinput = maxiter; // When using Eigen coxfit2 needs to be called in a slightly // different way (i.e. the .data()-part needs to be added). #if EIGEN coxfit2(&maxiter, &cdata.nids, &X.nrow, cdata.stime.data.data(), cdata.sstat.data.data(), X.data.data(), newoffset.data.data(), cdata.weights.data.data(), cdata.strata.data.data(), means.data.data(), beta.data.data(), u.data.data(), imat.data.data(), loglik_int, &flag, work, &eps, &tol_chol, &sctest); #else coxfit2(&maxiter, &cdata.nids, &X.nrow, cdata.stime.data, cdata.sstat.data, X.data, newoffset.data, cdata.weights.data, cdata.strata.data, means.data, beta.data, u.data, imat.data, loglik_int, &flag, work, &eps, &tol_chol, &sctest); #endif niter = maxiter; // Check the results of the Cox fit; mirrored from the same checks // in coxph.fit.S and coxph.R from the R survival package. bool setToNAN = false; // Based on coxph.fit.S lines with 'which.sing' and coxph.R line // with if(any(is.NA(coefficients))). These lines set coefficients // to NA if flag < nvar (with nvar = ncol(x)) and maxiter > // 0. coxph.R then checks for any NAs in the coefficients and // outputs the warning message if NAs were found. if (flag < X.nrow) { #if EIGEN int which_sing = 0; MatrixXd imateigen = imat.data; VectorXd imatdiag = imateigen.diagonal(); // Start at i=1 to exclude the beta coefficient for the // (constant) mean from the check. for (int i=1; i < imatdiag.size(); i++) { if (imatdiag[i] == 0) { which_sing = i; setToNAN = true; std::cerr << "Warning for " << snpinfo.name[cursnp] << ": X matrix deemed to be singular (variable " << which_sing + 1 << ")" << std::endl; } } #else std::cerr << "Warning for " << snpinfo.name[cursnp] << ": can't check for singular X matrix." << " Please compile ProbABEL with Eigen support to fix this." << std::endl; #endif } if (niter >= maxiterinput) { cerr << "Warning for " << snpinfo.name[cursnp] << ": nr of iterations >= MAXITER (" << maxiterinput << "): " << niter << endl; } if (flag == 1000) { cerr << "Warning for " << snpinfo.name[cursnp] << ": Cox regression ran out of iterations and did not converge," << " setting beta and se to 'NaN'\n"; setToNAN = true; } else { #if EIGEN VectorXd ueigen = u.data; MatrixXd imateigen = imat.data; VectorXd infs = ueigen.transpose() * imateigen; infs = infs.cwiseAbs(); VectorXd betaeigen = beta.data; bool problems = false; assert(betaeigen.size() == infs.size()); // We check the beta's for all coefficients // (incl. covariates), maybe stick to only checking the SNP // coefficient? for (int i = 0; i < infs.size(); i++) { if (infs[i] > eps && infs[i] > sqrt(eps) * abs(betaeigen[i])) { problems = true; } } if (problems) { cerr << "Warning for " << snpinfo.name[cursnp] << ": beta may be infinite," << " setting beta and se to 'NaN'\n"; setToNAN = true; } #else cerr << "Warning for " << snpinfo.name[cursnp] << ": can't check for infinite betas." << " Please compile ProbABEL with Eigen support to fix this." << endl; #endif } for (int i = 0; i < X.nrow; i++) { if (setToNAN) { // Cox regression failed sebeta[i] = NAN; beta[i] = NAN; loglik = NAN; } else { sebeta[i] = sqrt(imat.get(i, i)); loglik = loglik_int[1]; } } delete[] work; }
d77d1657797e5295710803fa9ce0eef627d7fbc0
fd7f812ab0b20fb24f6c6a6eda93ec1622744abc
/extern/lodepng.h
d02b1a55aa06060a22ee6b2aac70ebb45719d775
[]
no_license
wenyi9890/Dendrite
335edf22d98dd423093b95f56c1fb4090e82c9cd
dbffc120fec0f8df68f7916012d1ab965bd99810
refs/heads/master
2021-06-10T07:01:08.340066
2017-02-01T21:00:32
2017-02-01T21:00:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
82,030
h
/* LodePNG version 20160501 Copyright (c) 2005-2016 Lode Vandevenne This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef LODEPNG_H #define LODEPNG_H #include <string.h> /*for size_t*/ extern const char* LODEPNG_VERSION_STRING; /* The following #defines are used to create code sections. They can be disabled to disable code sections, which can give faster compile time and smaller binary. The "NO_COMPILE" defines are designed to be used to pass as defines to the compiler command to disable them without modifying this header, e.g. -DLODEPNG_NO_COMPILE_ZLIB for gcc. In addition to those below, you can also define LODEPNG_NO_COMPILE_CRC to allow implementing a custom lodepng_crc32. */ /*deflate & zlib. If disabled, you must specify alternative zlib functions in the custom_zlib field of the compress and decompress settings*/ #ifndef LODEPNG_NO_COMPILE_ZLIB #define LODEPNG_COMPILE_ZLIB #endif /*png encoder and png decoder*/ #ifndef LODEPNG_NO_COMPILE_PNG #define LODEPNG_COMPILE_PNG #endif /*deflate&zlib decoder and png decoder*/ #ifndef LODEPNG_NO_COMPILE_DECODER #define LODEPNG_COMPILE_DECODER #endif /*deflate&zlib encoder and png encoder*/ #ifndef LODEPNG_NO_COMPILE_ENCODER #define LODEPNG_COMPILE_ENCODER #endif /*the optional built in harddisk file loading and saving functions*/ #ifndef LODEPNG_NO_COMPILE_DISK #define LODEPNG_COMPILE_DISK #endif /*support for chunks other than IHDR, IDAT, PLTE, tRNS, IEND: ancillary and unknown chunks*/ #ifndef LODEPNG_NO_COMPILE_ANCILLARY_CHUNKS #define LODEPNG_COMPILE_ANCILLARY_CHUNKS #endif /*ability to convert error numerical codes to English text string*/ #ifndef LODEPNG_NO_COMPILE_ERROR_TEXT #define LODEPNG_COMPILE_ERROR_TEXT #endif /*Compile the default allocators (C's free, malloc and realloc). If you disable this, you can define the functions lodepng_free, lodepng_malloc and lodepng_realloc in your source files with custom allocators.*/ #ifndef LODEPNG_NO_COMPILE_ALLOCATORS #define LODEPNG_COMPILE_ALLOCATORS #endif /*compile the C++ version (you can disable the C++ wrapper here even when compiling for C++)*/ #ifdef __cplusplus #ifndef LODEPNG_NO_COMPILE_CPP #define LODEPNG_COMPILE_CPP #endif #endif #ifdef LODEPNG_COMPILE_CPP #include <vector> #include <string> #endif /*LODEPNG_COMPILE_CPP*/ #ifdef LODEPNG_COMPILE_PNG /*The PNG color types (also used for raw).*/ typedef enum LodePNGColorType { LCT_GREY = 0, /*greyscale: 1,2,4,8,16 bit*/ LCT_RGB = 2, /*RGB: 8,16 bit*/ LCT_PALETTE = 3, /*palette: 1,2,4,8 bit*/ LCT_GREY_ALPHA = 4, /*greyscale with alpha: 8,16 bit*/ LCT_RGBA = 6 /*RGB with alpha: 8,16 bit*/ } LodePNGColorType; #ifdef LODEPNG_COMPILE_DECODER /* Converts PNG data in memory to raw pixel data. out: Output parameter. Pointer to buffer that will contain the raw pixel data. After decoding, its size is w * h * (bytes per pixel) bytes larger than initially. Bytes per pixel depends on colortype and bitdepth. Must be freed after usage with free(*out). Note: for 16-bit per channel colors, uses big endian format like PNG does. w: Output parameter. Pointer to width of pixel data. h: Output parameter. Pointer to height of pixel data. in: Memory buffer with the PNG file. insize: size of the in buffer. colortype: the desired color type for the raw output image. See explanation on PNG color types. bitdepth: the desired bit depth for the raw output image. See explanation on PNG color types. Return value: LodePNG error code (0 means no error). */ unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize, LodePNGColorType colortype, unsigned bitdepth); /*Same as lodepng_decode_memory, but always decodes to 32-bit RGBA raw image*/ unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize); /*Same as lodepng_decode_memory, but always decodes to 24-bit RGB raw image*/ unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize); #ifdef LODEPNG_COMPILE_DISK /* Load PNG from disk, from file with given name. Same as the other decode functions, but instead takes a filename as input. */ unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename, LodePNGColorType colortype, unsigned bitdepth); /*Same as lodepng_decode_file, but always decodes to 32-bit RGBA raw image.*/ unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename); /*Same as lodepng_decode_file, but always decodes to 24-bit RGB raw image.*/ unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename); #endif /*LODEPNG_COMPILE_DISK*/ #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER /* Converts raw pixel data into a PNG image in memory. The colortype and bitdepth of the output PNG image cannot be chosen, they are automatically determined by the colortype, bitdepth and content of the input pixel data. Note: for 16-bit per channel colors, needs big endian format like PNG does. out: Output parameter. Pointer to buffer that will contain the PNG image data. Must be freed after usage with free(*out). outsize: Output parameter. Pointer to the size in bytes of the out buffer. image: The raw pixel data to encode. The size of this buffer should be w * h * (bytes per pixel), bytes per pixel depends on colortype and bitdepth. w: width of the raw pixel data in pixels. h: height of the raw pixel data in pixels. colortype: the color type of the raw input image. See explanation on PNG color types. bitdepth: the bit depth of the raw input image. See explanation on PNG color types. Return value: LodePNG error code (0 means no error). */ unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth); /*Same as lodepng_encode_memory, but always encodes from 32-bit RGBA raw image.*/ unsigned lodepng_encode32(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h); /*Same as lodepng_encode_memory, but always encodes from 24-bit RGB raw image.*/ unsigned lodepng_encode24(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h); #ifdef LODEPNG_COMPILE_DISK /* Converts raw pixel data into a PNG file on disk. Same as the other encode functions, but instead takes a filename as output. NOTE: This overwrites existing files without warning! */ unsigned lodepng_encode_file(const char* filename, const unsigned char* image, unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth); /*Same as lodepng_encode_file, but always encodes from 32-bit RGBA raw image.*/ unsigned lodepng_encode32_file(const char* filename, const unsigned char* image, unsigned w, unsigned h); /*Same as lodepng_encode_file, but always encodes from 24-bit RGB raw image.*/ unsigned lodepng_encode24_file(const char* filename, const unsigned char* image, unsigned w, unsigned h); #endif /*LODEPNG_COMPILE_DISK*/ #endif /*LODEPNG_COMPILE_ENCODER*/ #ifdef LODEPNG_COMPILE_CPP namespace lodepng { #ifdef LODEPNG_COMPILE_DECODER /*Same as lodepng_decode_memory, but decodes to an std::vector. The colortype is the format to output the pixels to. Default is RGBA 8-bit per channel.*/ unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const unsigned char* in, size_t insize, LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const std::vector<unsigned char>& in, LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); #ifdef LODEPNG_COMPILE_DISK /* Converts PNG file from disk to raw pixel data in memory. Same as the other decode functions, but instead takes a filename as input. */ unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const std::string& filename, LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); #endif /* LODEPNG_COMPILE_DISK */ #endif /* LODEPNG_COMPILE_DECODER */ #ifdef LODEPNG_COMPILE_ENCODER /*Same as lodepng_encode_memory, but encodes to an std::vector. colortype is that of the raw input data. The output PNG color type will be auto chosen.*/ unsigned encode(std::vector<unsigned char>& out, const unsigned char* in, unsigned w, unsigned h, LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); unsigned encode(std::vector<unsigned char>& out, const std::vector<unsigned char>& in, unsigned w, unsigned h, LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); #ifdef LODEPNG_COMPILE_DISK /* Converts 32-bit RGBA raw pixel data into a PNG file on disk. Same as the other encode functions, but instead takes a filename as output. NOTE: This overwrites existing files without warning! */ unsigned encode(const std::string& filename, const unsigned char* in, unsigned w, unsigned h, LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); unsigned encode(const std::string& filename, const std::vector<unsigned char>& in, unsigned w, unsigned h, LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); #endif /* LODEPNG_COMPILE_DISK */ #endif /* LODEPNG_COMPILE_ENCODER */ } /* namespace lodepng */ #endif /*LODEPNG_COMPILE_CPP*/ #endif /*LODEPNG_COMPILE_PNG*/ #ifdef LODEPNG_COMPILE_ERROR_TEXT /*Returns an English description of the numerical error code.*/ const char* lodepng_error_text(unsigned code); #endif /*LODEPNG_COMPILE_ERROR_TEXT*/ #ifdef LODEPNG_COMPILE_DECODER /*Settings for zlib decompression*/ typedef struct LodePNGDecompressSettings LodePNGDecompressSettings; struct LodePNGDecompressSettings { unsigned ignore_adler32; /*if 1, continue and don't give an error message if the Adler32 checksum is corrupted*/ /*use custom zlib decoder instead of built in one (default: null)*/ unsigned (*custom_zlib)(unsigned char**, size_t*, const unsigned char*, size_t, const LodePNGDecompressSettings*); /*use custom deflate decoder instead of built in one (default: null) if custom_zlib is used, custom_deflate is ignored since only the built in zlib function will call custom_deflate*/ unsigned (*custom_inflate)(unsigned char**, size_t*, const unsigned char*, size_t, const LodePNGDecompressSettings*); const void* custom_context; /*optional custom settings for custom functions*/ }; extern const LodePNGDecompressSettings lodepng_default_decompress_settings; void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings); #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER /* Settings for zlib compression. Tweaking these settings tweaks the balance between speed and compression ratio. */ typedef struct LodePNGCompressSettings LodePNGCompressSettings; struct LodePNGCompressSettings /*deflate = compress*/ { /*LZ77 related settings*/ unsigned btype; /*the block type for LZ (0, 1, 2 or 3, see zlib standard). Should be 2 for proper compression.*/ unsigned use_lz77; /*whether or not to use LZ77. Should be 1 for proper compression.*/ unsigned windowsize; /*must be a power of two <= 32768. higher compresses more but is slower. Default value: 2048.*/ unsigned minmatch; /*mininum lz77 length. 3 is normally best, 6 can be better for some PNGs. Default: 0*/ unsigned nicematch; /*stop searching if >= this length found. Set to 258 for best compression. Default: 128*/ unsigned lazymatching; /*use lazy matching: better compression but a bit slower. Default: true*/ /*use custom zlib encoder instead of built in one (default: null)*/ unsigned (*custom_zlib)(unsigned char**, size_t*, const unsigned char*, size_t, const LodePNGCompressSettings*); /*use custom deflate encoder instead of built in one (default: null) if custom_zlib is used, custom_deflate is ignored since only the built in zlib function will call custom_deflate*/ unsigned (*custom_deflate)(unsigned char**, size_t*, const unsigned char*, size_t, const LodePNGCompressSettings*); const void* custom_context; /*optional custom settings for custom functions*/ }; extern const LodePNGCompressSettings lodepng_default_compress_settings; void lodepng_compress_settings_init(LodePNGCompressSettings* settings); #endif /*LODEPNG_COMPILE_ENCODER*/ #ifdef LODEPNG_COMPILE_PNG /* Color mode of an image. Contains all information required to decode the pixel bits to RGBA colors. This information is the same as used in the PNG file format, and is used both for PNG and raw image data in LodePNG. */ typedef struct LodePNGColorMode { /*header (IHDR)*/ LodePNGColorType colortype; /*color type, see PNG standard or documentation further in this header file*/ unsigned bitdepth; /*bits per sample, see PNG standard or documentation further in this header file*/ /* palette (PLTE and tRNS) Dynamically allocated with the colors of the palette, including alpha. When encoding a PNG, to store your colors in the palette of the LodePNGColorMode, first use lodepng_palette_clear, then for each color use lodepng_palette_add. If you encode an image without alpha with palette, don't forget to put value 255 in each A byte of the palette. When decoding, by default you can ignore this palette, since LodePNG already fills the palette colors in the pixels of the raw RGBA output. The palette is only supported for color type 3. */ unsigned char* palette; /*palette in RGBARGBA... order. When allocated, must be either 0, or have size 1024*/ size_t palettesize; /*palette size in number of colors (amount of bytes is 4 * palettesize)*/ /* transparent color key (tRNS) This color uses the same bit depth as the bitdepth value in this struct, which can be 1-bit to 16-bit. For greyscale PNGs, r, g and b will all 3 be set to the same. When decoding, by default you can ignore this information, since LodePNG sets pixels with this key to transparent already in the raw RGBA output. The color key is only supported for color types 0 and 2. */ unsigned key_defined; /*is a transparent color key given? 0 = false, 1 = true*/ unsigned key_r; /*red/greyscale component of color key*/ unsigned key_g; /*green component of color key*/ unsigned key_b; /*blue component of color key*/ } LodePNGColorMode; /*init, cleanup and copy functions to use with this struct*/ void lodepng_color_mode_init(LodePNGColorMode* info); void lodepng_color_mode_cleanup(LodePNGColorMode* info); /*return value is error code (0 means no error)*/ unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source); void lodepng_palette_clear(LodePNGColorMode* info); /*add 1 color to the palette*/ unsigned lodepng_palette_add(LodePNGColorMode* info, unsigned char r, unsigned char g, unsigned char b, unsigned char a); /*get the total amount of bits per pixel, based on colortype and bitdepth in the struct*/ unsigned lodepng_get_bpp(const LodePNGColorMode* info); /*get the amount of color channels used, based on colortype in the struct. If a palette is used, it counts as 1 channel.*/ unsigned lodepng_get_channels(const LodePNGColorMode* info); /*is it a greyscale type? (only colortype 0 or 4)*/ unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info); /*has it got an alpha channel? (only colortype 2 or 6)*/ unsigned lodepng_is_alpha_type(const LodePNGColorMode* info); /*has it got a palette? (only colortype 3)*/ unsigned lodepng_is_palette_type(const LodePNGColorMode* info); /*only returns true if there is a palette and there is a value in the palette with alpha < 255. Loops through the palette to check this.*/ unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info); /* Check if the given color info indicates the possibility of having non-opaque pixels in the PNG image. Returns true if the image can have translucent or invisible pixels (it still be opaque if it doesn't use such pixels). Returns false if the image can only have opaque pixels. In detail, it returns true only if it's a color type with alpha, or has a palette with non-opaque values, or if "key_defined" is true. */ unsigned lodepng_can_have_alpha(const LodePNGColorMode* info); /*Returns the byte size of a raw image buffer with given width, height and color mode*/ size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color); #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*The information of a Time chunk in PNG.*/ typedef struct LodePNGTime { unsigned year; /*2 bytes used (0-65535)*/ unsigned month; /*1-12*/ unsigned day; /*1-31*/ unsigned hour; /*0-23*/ unsigned minute; /*0-59*/ unsigned second; /*0-60 (to allow for leap seconds)*/ } LodePNGTime; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ /*Information about the PNG image, except pixels, width and height.*/ typedef struct LodePNGInfo { /*header (IHDR), palette (PLTE) and transparency (tRNS) chunks*/ unsigned compression_method;/*compression method of the original file. Always 0.*/ unsigned filter_method; /*filter method of the original file*/ unsigned interlace_method; /*interlace method of the original file*/ LodePNGColorMode color; /*color type and bits, palette and transparency of the PNG file*/ #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /* suggested background color chunk (bKGD) This color uses the same color mode as the PNG (except alpha channel), which can be 1-bit to 16-bit. For greyscale PNGs, r, g and b will all 3 be set to the same. When encoding the encoder writes the red one. For palette PNGs: When decoding, the RGB value will be stored, not a palette index. But when encoding, specify the index of the palette in background_r, the other two are then ignored. The decoder does not use this background color to edit the color of pixels. */ unsigned background_defined; /*is a suggested background color given?*/ unsigned background_r; /*red component of suggested background color*/ unsigned background_g; /*green component of suggested background color*/ unsigned background_b; /*blue component of suggested background color*/ /* non-international text chunks (tEXt and zTXt) The char** arrays each contain num strings. The actual messages are in text_strings, while text_keys are keywords that give a short description what the actual text represents, e.g. Title, Author, Description, or anything else. A keyword is minimum 1 character and maximum 79 characters long. It's discouraged to use a single line length longer than 79 characters for texts. Don't allocate these text buffers yourself. Use the init/cleanup functions correctly and use lodepng_add_text and lodepng_clear_text. */ size_t text_num; /*the amount of texts in these char** buffers (there may be more texts in itext)*/ char** text_keys; /*the keyword of a text chunk (e.g. "Comment")*/ char** text_strings; /*the actual text*/ /* international text chunks (iTXt) Similar to the non-international text chunks, but with additional strings "langtags" and "transkeys". */ size_t itext_num; /*the amount of international texts in this PNG*/ char** itext_keys; /*the English keyword of the text chunk (e.g. "Comment")*/ char** itext_langtags; /*language tag for this text's language, ISO/IEC 646 string, e.g. ISO 639 language tag*/ char** itext_transkeys; /*keyword translated to the international language - UTF-8 string*/ char** itext_strings; /*the actual international text - UTF-8 string*/ /*time chunk (tIME)*/ unsigned time_defined; /*set to 1 to make the encoder generate a tIME chunk*/ LodePNGTime time; /*phys chunk (pHYs)*/ unsigned phys_defined; /*if 0, there is no pHYs chunk and the values below are undefined, if 1 else there is one*/ unsigned phys_x; /*pixels per unit in x direction*/ unsigned phys_y; /*pixels per unit in y direction*/ unsigned phys_unit; /*may be 0 (unknown unit) or 1 (metre)*/ /* unknown chunks There are 3 buffers, one for each position in the PNG where unknown chunks can appear each buffer contains all unknown chunks for that position consecutively The 3 buffers are the unknown chunks between certain critical chunks: 0: IHDR-PLTE, 1: PLTE-IDAT, 2: IDAT-IEND Do not allocate or traverse this data yourself. Use the chunk traversing functions declared later, such as lodepng_chunk_next and lodepng_chunk_append, to read/write this struct. */ unsigned char* unknown_chunks_data[3]; size_t unknown_chunks_size[3]; /*size in bytes of the unknown chunks, given for protection*/ #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } LodePNGInfo; /*init, cleanup and copy functions to use with this struct*/ void lodepng_info_init(LodePNGInfo* info); void lodepng_info_cleanup(LodePNGInfo* info); /*return value is error code (0 means no error)*/ unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source); #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS void lodepng_clear_text(LodePNGInfo* info); /*use this to clear the texts again after you filled them in*/ unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str); /*push back both texts at once*/ void lodepng_clear_itext(LodePNGInfo* info); /*use this to clear the itexts again after you filled them in*/ unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag, const char* transkey, const char* str); /*push back the 4 texts of 1 chunk at once*/ #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ /* Converts raw buffer from one color type to another color type, based on LodePNGColorMode structs to describe the input and output color type. See the reference manual at the end of this header file to see which color conversions are supported. return value = LodePNG error code (0 if all went ok, an error if the conversion isn't supported) The out buffer must have size (w * h * bpp + 7) / 8, where bpp is the bits per pixel of the output color type (lodepng_get_bpp). For < 8 bpp images, there should not be padding bits at the end of scanlines. For 16-bit per channel colors, uses big endian format like PNG does. Return value is LodePNG error code */ unsigned lodepng_convert(unsigned char* out, const unsigned char* in, const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in, unsigned w, unsigned h); #ifdef LODEPNG_COMPILE_DECODER /* Settings for the decoder. This contains settings for the PNG and the Zlib decoder, but not the Info settings from the Info structs. */ typedef struct LodePNGDecoderSettings { LodePNGDecompressSettings zlibsettings; /*in here is the setting to ignore Adler32 checksums*/ unsigned ignore_crc; /*ignore CRC checksums*/ unsigned color_convert; /*whether to convert the PNG to the color type you want. Default: yes*/ #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS unsigned read_text_chunks; /*if false but remember_unknown_chunks is true, they're stored in the unknown chunks*/ /*store all bytes from unknown chunks in the LodePNGInfo (off by default, useful for a png editor)*/ unsigned remember_unknown_chunks; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } LodePNGDecoderSettings; void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings); #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER /*automatically use color type with less bits per pixel if losslessly possible. Default: AUTO*/ typedef enum LodePNGFilterStrategy { /*every filter at zero*/ LFS_ZERO, /*Use filter that gives minimum sum, as described in the official PNG filter heuristic.*/ LFS_MINSUM, /*Use the filter type that gives smallest Shannon entropy for this scanline. Depending on the image, this is better or worse than minsum.*/ LFS_ENTROPY, /* Brute-force-search PNG filters by compressing each filter for each scanline. Experimental, very slow, and only rarely gives better compression than MINSUM. */ LFS_BRUTE_FORCE, /*use predefined_filters buffer: you specify the filter type for each scanline*/ LFS_PREDEFINED } LodePNGFilterStrategy; /*Gives characteristics about the colors of the image, which helps decide which color model to use for encoding. Used internally by default if "auto_convert" is enabled. Public because it's useful for custom algorithms.*/ typedef struct LodePNGColorProfile { unsigned colored; /*not greyscale*/ unsigned key; /*if true, image is not opaque. Only if true and alpha is false, color key is possible.*/ unsigned short key_r; /*these values are always in 16-bit bitdepth in the profile*/ unsigned short key_g; unsigned short key_b; unsigned alpha; /*alpha channel or alpha palette required*/ unsigned numcolors; /*amount of colors, up to 257. Not valid if bits == 16.*/ unsigned char palette[1024]; /*Remembers up to the first 256 RGBA colors, in no particular order*/ unsigned bits; /*bits per channel (not for palette). 1,2 or 4 for greyscale only. 16 if 16-bit per channel required.*/ } LodePNGColorProfile; void lodepng_color_profile_init(LodePNGColorProfile* profile); /*Get a LodePNGColorProfile of the image.*/ unsigned lodepng_get_color_profile(LodePNGColorProfile* profile, const unsigned char* image, unsigned w, unsigned h, const LodePNGColorMode* mode_in); /*The function LodePNG uses internally to decide the PNG color with auto_convert. Chooses an optimal color model, e.g. grey if only grey pixels, palette if < 256 colors, ...*/ unsigned lodepng_auto_choose_color(LodePNGColorMode* mode_out, const unsigned char* image, unsigned w, unsigned h, const LodePNGColorMode* mode_in); /*Settings for the encoder.*/ typedef struct LodePNGEncoderSettings { LodePNGCompressSettings zlibsettings; /*settings for the zlib encoder, such as window size, ...*/ unsigned auto_convert; /*automatically choose output PNG color type. Default: true*/ /*If true, follows the official PNG heuristic: if the PNG uses a palette or lower than 8 bit depth, set all filters to zero. Otherwise use the filter_strategy. Note that to completely follow the official PNG heuristic, filter_palette_zero must be true and filter_strategy must be LFS_MINSUM*/ unsigned filter_palette_zero; /*Which filter strategy to use when not using zeroes due to filter_palette_zero. Set filter_palette_zero to 0 to ensure always using your chosen strategy. Default: LFS_MINSUM*/ LodePNGFilterStrategy filter_strategy; /*used if filter_strategy is LFS_PREDEFINED. In that case, this must point to a buffer with the same length as the amount of scanlines in the image, and each value must <= 5. You have to cleanup this buffer, LodePNG will never free it. Don't forget that filter_palette_zero must be set to 0 to ensure this is also used on palette or low bitdepth images.*/ const unsigned char* predefined_filters; /*force creating a PLTE chunk if colortype is 2 or 6 (= a suggested palette). If colortype is 3, PLTE is _always_ created.*/ unsigned force_palette; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*add LodePNG identifier and version as a text chunk, for debugging*/ unsigned add_id; /*encode text chunks as zTXt chunks instead of tEXt chunks, and use compression in iTXt chunks*/ unsigned text_compression; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } LodePNGEncoderSettings; void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings); #endif /*LODEPNG_COMPILE_ENCODER*/ #if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) /*The settings, state and information for extended encoding and decoding.*/ typedef struct LodePNGState { #ifdef LODEPNG_COMPILE_DECODER LodePNGDecoderSettings decoder; /*the decoding settings*/ #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER LodePNGEncoderSettings encoder; /*the encoding settings*/ #endif /*LODEPNG_COMPILE_ENCODER*/ LodePNGColorMode info_raw; /*specifies the format in which you would like to get the raw pixel buffer*/ LodePNGInfo info_png; /*info of the PNG image obtained after decoding*/ unsigned error; #ifdef LODEPNG_COMPILE_CPP /* For the lodepng::State subclass. */ virtual ~LodePNGState(){} #endif } LodePNGState; /*init, cleanup and copy functions to use with this struct*/ void lodepng_state_init(LodePNGState* state); void lodepng_state_cleanup(LodePNGState* state); void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source); #endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */ #ifdef LODEPNG_COMPILE_DECODER /* Same as lodepng_decode_memory, but uses a LodePNGState to allow custom settings and getting much more information about the PNG image and color mode. */ unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h, LodePNGState* state, const unsigned char* in, size_t insize); /* Read the PNG header, but not the actual data. This returns only the information that is in the header chunk of the PNG, such as width, height and color type. The information is placed in the info_png field of the LodePNGState. */ unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state, const unsigned char* in, size_t insize); #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER /*This function allocates the out buffer with standard malloc and stores the size in *outsize.*/ unsigned lodepng_encode(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h, LodePNGState* state); #endif /*LODEPNG_COMPILE_ENCODER*/ /* The lodepng_chunk functions are normally not needed, except to traverse the unknown chunks stored in the LodePNGInfo struct, or add new ones to it. It also allows traversing the chunks of an encoded PNG file yourself. PNG standard chunk naming conventions: First byte: uppercase = critical, lowercase = ancillary Second byte: uppercase = public, lowercase = private Third byte: must be uppercase Fourth byte: uppercase = unsafe to copy, lowercase = safe to copy */ /* Gets the length of the data of the chunk. Total chunk length has 12 bytes more. There must be at least 4 bytes to read from. If the result value is too large, it may be corrupt data. */ unsigned lodepng_chunk_length(const unsigned char* chunk); /*puts the 4-byte type in null terminated string*/ void lodepng_chunk_type(char type[5], const unsigned char* chunk); /*check if the type is the given type*/ unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type); /*0: it's one of the critical chunk types, 1: it's an ancillary chunk (see PNG standard)*/ unsigned char lodepng_chunk_ancillary(const unsigned char* chunk); /*0: public, 1: private (see PNG standard)*/ unsigned char lodepng_chunk_private(const unsigned char* chunk); /*0: the chunk is unsafe to copy, 1: the chunk is safe to copy (see PNG standard)*/ unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk); /*get pointer to the data of the chunk, where the input points to the header of the chunk*/ unsigned char* lodepng_chunk_data(unsigned char* chunk); const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk); /*returns 0 if the crc is correct, 1 if it's incorrect (0 for OK as usual!)*/ unsigned lodepng_chunk_check_crc(const unsigned char* chunk); /*generates the correct CRC from the data and puts it in the last 4 bytes of the chunk*/ void lodepng_chunk_generate_crc(unsigned char* chunk); /*iterate to next chunks. don't use on IEND chunk, as there is no next chunk then*/ unsigned char* lodepng_chunk_next(unsigned char* chunk); const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk); /* Appends chunk to the data in out. The given chunk should already have its chunk header. The out variable and outlength are updated to reflect the new reallocated buffer. Returns error code (0 if it went ok) */ unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk); /* Appends new chunk to out. The chunk to append is given by giving its length, type and data separately. The type is a 4-letter string. The out variable and outlength are updated to reflect the new reallocated buffer. Returne error code (0 if it went ok) */ unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length, const char* type, const unsigned char* data); /*Calculate CRC32 of buffer*/ unsigned lodepng_crc32(const unsigned char* buf, size_t len); #endif /*LODEPNG_COMPILE_PNG*/ #ifdef LODEPNG_COMPILE_ZLIB /* This zlib part can be used independently to zlib compress and decompress a buffer. It cannot be used to create gzip files however, and it only supports the part of zlib that is required for PNG, it does not support dictionaries. */ #ifdef LODEPNG_COMPILE_DECODER /*Inflate a buffer. Inflate is the decompression step of deflate. Out buffer must be freed after use.*/ unsigned lodepng_inflate(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings); /* Decompresses Zlib data. Reallocates the out buffer and appends the data. The data must be according to the zlib specification. Either, *out must be NULL and *outsize must be 0, or, *out must be a valid buffer and *outsize its size in bytes. out must be freed by user after usage. */ unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings); #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER /* Compresses data with Zlib. Reallocates the out buffer and appends the data. Zlib adds a small header and trailer around the deflate data. The data is output in the format of the zlib specification. Either, *out must be NULL and *outsize must be 0, or, *out must be a valid buffer and *outsize its size in bytes. out must be freed by user after usage. */ unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGCompressSettings* settings); /* Find length-limited Huffman code for given frequencies. This function is in the public interface only for tests, it's used internally by lodepng_deflate. */ unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies, size_t numcodes, unsigned maxbitlen); /*Compress a buffer with deflate. See RFC 1951. Out buffer must be freed after use.*/ unsigned lodepng_deflate(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGCompressSettings* settings); #endif /*LODEPNG_COMPILE_ENCODER*/ #endif /*LODEPNG_COMPILE_ZLIB*/ #ifdef LODEPNG_COMPILE_DISK /* Load a file from disk into buffer. The function allocates the out buffer, and after usage you should free it. out: output parameter, contains pointer to loaded buffer. outsize: output parameter, size of the allocated out buffer filename: the path to the file to load return value: error code (0 means ok) */ unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename); /* Save a file from buffer to disk. Warning, if it exists, this function overwrites the file without warning! buffer: the buffer to write buffersize: size of the buffer to write filename: the path to the file to save to return value: error code (0 means ok) */ unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename); #endif /*LODEPNG_COMPILE_DISK*/ #ifdef LODEPNG_COMPILE_CPP /* The LodePNG C++ wrapper uses std::vectors instead of manually allocated memory buffers. */ namespace lodepng { #ifdef LODEPNG_COMPILE_PNG class State : public LodePNGState { public: State(); State(const State& other); virtual ~State(); State& operator=(const State& other); }; #ifdef LODEPNG_COMPILE_DECODER /* Same as other lodepng::decode, but using a State for more settings and information. */ unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, State& state, const unsigned char* in, size_t insize); unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, State& state, const std::vector<unsigned char>& in); #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER /* Same as other lodepng::encode, but using a State for more settings and information. */ unsigned encode(std::vector<unsigned char>& out, const unsigned char* in, unsigned w, unsigned h, State& state); unsigned encode(std::vector<unsigned char>& out, const std::vector<unsigned char>& in, unsigned w, unsigned h, State& state); #endif /*LODEPNG_COMPILE_ENCODER*/ #ifdef LODEPNG_COMPILE_DISK /* Load a file from disk into an std::vector. return value: error code (0 means ok) */ unsigned load_file(std::vector<unsigned char>& buffer, const std::string& filename); /* Save the binary data in an std::vector to a file on disk. The file is overwritten without warning. */ unsigned save_file(const std::vector<unsigned char>& buffer, const std::string& filename); #endif /* LODEPNG_COMPILE_DISK */ #endif /* LODEPNG_COMPILE_PNG */ #ifdef LODEPNG_COMPILE_ZLIB #ifdef LODEPNG_COMPILE_DECODER /* Zlib-decompress an unsigned char buffer */ unsigned decompress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize, const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings); /* Zlib-decompress an std::vector */ unsigned decompress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in, const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings); #endif /* LODEPNG_COMPILE_DECODER */ #ifdef LODEPNG_COMPILE_ENCODER /* Zlib-compress an unsigned char buffer */ unsigned compress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize, const LodePNGCompressSettings& settings = lodepng_default_compress_settings); /* Zlib-compress an std::vector */ unsigned compress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in, const LodePNGCompressSettings& settings = lodepng_default_compress_settings); #endif /* LODEPNG_COMPILE_ENCODER */ #endif /* LODEPNG_COMPILE_ZLIB */ } /* namespace lodepng */ #endif /*LODEPNG_COMPILE_CPP*/ /* TODO: [.] test if there are no memory leaks or security exploits - done a lot but needs to be checked often [.] check compatibility with various compilers - done but needs to be redone for every newer version [X] converting color to 16-bit per channel types [ ] read all public PNG chunk types (but never let the color profile and gamma ones touch RGB values) [ ] make sure encoder generates no chunks with size > (2^31)-1 [ ] partial decoding (stream processing) [X] let the "isFullyOpaque" function check color keys and transparent palettes too [X] better name for the variables "codes", "codesD", "codelengthcodes", "clcl" and "lldl" [ ] don't stop decoding on errors like 69, 57, 58 (make warnings) [ ] let the C++ wrapper catch exceptions coming from the standard library and return LodePNG error codes [ ] allow user to provide custom color conversion functions, e.g. for premultiplied alpha, padding bits or not, ... [ ] allow user to give data (void*) to custom allocator */ #endif /*LODEPNG_H inclusion guard*/ /* LodePNG Documentation --------------------- 0. table of contents -------------------- 1. about 1.1. supported features 1.2. features not supported 2. C and C++ version 3. security 4. decoding 5. encoding 6. color conversions 6.1. PNG color types 6.2. color conversions 6.3. padding bits 6.4. A note about 16-bits per channel and endianness 7. error values 8. chunks and PNG editing 9. compiler support 10. examples 10.1. decoder C++ example 10.2. decoder C example 11. state settings reference 12. changes 13. contact information 1. about -------- PNG is a file format to store raster images losslessly with good compression, supporting different color types and alpha channel. LodePNG is a PNG codec according to the Portable Network Graphics (PNG) Specification (Second Edition) - W3C Recommendation 10 November 2003. The specifications used are: *) Portable Network Graphics (PNG) Specification (Second Edition): http://www.w3.org/TR/2003/REC-PNG-20031110 *) RFC 1950 ZLIB Compressed Data Format version 3.3: http://www.gzip.org/zlib/rfc-zlib.html *) RFC 1951 DEFLATE Compressed Data Format Specification ver 1.3: http://www.gzip.org/zlib/rfc-deflate.html The most recent version of LodePNG can currently be found at http://lodev.org/lodepng/ LodePNG works both in C (ISO C90) and C++, with a C++ wrapper that adds extra functionality. LodePNG exists out of two files: -lodepng.h: the header file for both C and C++ -lodepng.c(pp): give it the name lodepng.c or lodepng.cpp (or .cc) depending on your usage If you want to start using LodePNG right away without reading this doc, get the examples from the LodePNG website to see how to use it in code, or check the smaller examples in chapter 13 here. LodePNG is simple but only supports the basic requirements. To achieve simplicity, the following design choices were made: There are no dependencies on any external library. There are functions to decode and encode a PNG with a single function call, and extended versions of these functions taking a LodePNGState struct allowing to specify or get more information. By default the colors of the raw image are always RGB or RGBA, no matter what color type the PNG file uses. To read and write files, there are simple functions to convert the files to/from buffers in memory. This all makes LodePNG suitable for loading textures in games, demos and small programs, ... It's less suitable for full fledged image editors, loading PNGs over network (it requires all the image data to be available before decoding can begin), life-critical systems, ... 1.1. supported features ----------------------- The following features are supported by the decoder: *) decoding of PNGs with any color type, bit depth and interlace mode, to a 24- or 32-bit color raw image, or the same color type as the PNG *) encoding of PNGs, from any raw image to 24- or 32-bit color, or the same color type as the raw image *) Adam7 interlace and deinterlace for any color type *) loading the image from harddisk or decoding it from a buffer from other sources than harddisk *) support for alpha channels, including RGBA color model, translucent palettes and color keying *) zlib decompression (inflate) *) zlib compression (deflate) *) CRC32 and ADLER32 checksums *) handling of unknown chunks, allowing making a PNG editor that stores custom and unknown chunks. *) the following chunks are supported (generated/interpreted) by both encoder and decoder: IHDR: header information PLTE: color palette IDAT: pixel data IEND: the final chunk tRNS: transparency for palettized images tEXt: textual information zTXt: compressed textual information iTXt: international textual information bKGD: suggested background color pHYs: physical dimensions tIME: modification time 1.2. features not supported --------------------------- The following features are _not_ supported: *) some features needed to make a conformant PNG-Editor might be still missing. *) partial loading/stream processing. All data must be available and is processed in one call. *) The following public chunks are not supported but treated as unknown chunks by LodePNG cHRM, gAMA, iCCP, sRGB, sBIT, hIST, sPLT Some of these are not supported on purpose: LodePNG wants to provide the RGB values stored in the pixels, not values modified by system dependent gamma or color models. 2. C and C++ version -------------------- The C version uses buffers allocated with alloc that you need to free() yourself. You need to use init and cleanup functions for each struct whenever using a struct from the C version to avoid exploits and memory leaks. The C++ version has extra functions with std::vectors in the interface and the lodepng::State class which is a LodePNGState with constructor and destructor. These files work without modification for both C and C++ compilers because all the additional C++ code is in "#ifdef __cplusplus" blocks that make C-compilers ignore it, and the C code is made to compile both with strict ISO C90 and C++. To use the C++ version, you need to rename the source file to lodepng.cpp (instead of lodepng.c), and compile it with a C++ compiler. To use the C version, you need to rename the source file to lodepng.c (instead of lodepng.cpp), and compile it with a C compiler. 3. Security ----------- Even if carefully designed, it's always possible that LodePNG contains possible exploits. If you discover one, please let me know, and it will be fixed. When using LodePNG, care has to be taken with the C version of LodePNG, as well as the C-style structs when working with C++. The following conventions are used for all C-style structs: -if a struct has a corresponding init function, always call the init function when making a new one -if a struct has a corresponding cleanup function, call it before the struct disappears to avoid memory leaks -if a struct has a corresponding copy function, use the copy function instead of "=". The destination must also be inited already. 4. Decoding ----------- Decoding converts a PNG compressed image to a raw pixel buffer. Most documentation on using the decoder is at its declarations in the header above. For C, simple decoding can be done with functions such as lodepng_decode32, and more advanced decoding can be done with the struct LodePNGState and lodepng_decode. For C++, all decoding can be done with the various lodepng::decode functions, and lodepng::State can be used for advanced features. When using the LodePNGState, it uses the following fields for decoding: *) LodePNGInfo info_png: it stores extra information about the PNG (the input) in here *) LodePNGColorMode info_raw: here you can say what color mode of the raw image (the output) you want to get *) LodePNGDecoderSettings decoder: you can specify a few extra settings for the decoder to use LodePNGInfo info_png -------------------- After decoding, this contains extra information of the PNG image, except the actual pixels, width and height because these are already gotten directly from the decoder functions. It contains for example the original color type of the PNG image, text comments, suggested background color, etc... More details about the LodePNGInfo struct are at its declaration documentation. LodePNGColorMode info_raw ------------------------- When decoding, here you can specify which color type you want the resulting raw image to be. If this is different from the colortype of the PNG, then the decoder will automatically convert the result. This conversion always works, except if you want it to convert a color PNG to greyscale or to a palette with missing colors. By default, 32-bit color is used for the result. LodePNGDecoderSettings decoder ------------------------------ The settings can be used to ignore the errors created by invalid CRC and Adler32 chunks, and to disable the decoding of tEXt chunks. There's also a setting color_convert, true by default. If false, no conversion is done, the resulting data will be as it was in the PNG (after decompression) and you'll have to puzzle the colors of the pixels together yourself using the color type information in the LodePNGInfo. 5. Encoding ----------- Encoding converts a raw pixel buffer to a PNG compressed image. Most documentation on using the encoder is at its declarations in the header above. For C, simple encoding can be done with functions such as lodepng_encode32, and more advanced decoding can be done with the struct LodePNGState and lodepng_encode. For C++, all encoding can be done with the various lodepng::encode functions, and lodepng::State can be used for advanced features. Like the decoder, the encoder can also give errors. However it gives less errors since the encoder input is trusted, the decoder input (a PNG image that could be forged by anyone) is not trusted. When using the LodePNGState, it uses the following fields for encoding: *) LodePNGInfo info_png: here you specify how you want the PNG (the output) to be. *) LodePNGColorMode info_raw: here you say what color type of the raw image (the input) has *) LodePNGEncoderSettings encoder: you can specify a few settings for the encoder to use LodePNGInfo info_png -------------------- When encoding, you use this the opposite way as when decoding: for encoding, you fill in the values you want the PNG to have before encoding. By default it's not needed to specify a color type for the PNG since it's automatically chosen, but it's possible to choose it yourself given the right settings. The encoder will not always exactly match the LodePNGInfo struct you give, it tries as close as possible. Some things are ignored by the encoder. The encoder uses, for example, the following settings from it when applicable: colortype and bitdepth, text chunks, time chunk, the color key, the palette, the background color, the interlace method, unknown chunks, ... When encoding to a PNG with colortype 3, the encoder will generate a PLTE chunk. If the palette contains any colors for which the alpha channel is not 255 (so there are translucent colors in the palette), it'll add a tRNS chunk. LodePNGColorMode info_raw ------------------------- You specify the color type of the raw image that you give to the input here, including a possible transparent color key and palette you happen to be using in your raw image data. By default, 32-bit color is assumed, meaning your input has to be in RGBA format with 4 bytes (unsigned chars) per pixel. LodePNGEncoderSettings encoder ------------------------------ The following settings are supported (some are in sub-structs): *) auto_convert: when this option is enabled, the encoder will automatically choose the smallest possible color mode (including color key) that can encode the colors of all pixels without information loss. *) btype: the block type for LZ77. 0 = uncompressed, 1 = fixed huffman tree, 2 = dynamic huffman tree (best compression). Should be 2 for proper compression. *) use_lz77: whether or not to use LZ77 for compressed block types. Should be true for proper compression. *) windowsize: the window size used by the LZ77 encoder (1 - 32768). Has value 2048 by default, but can be set to 32768 for better, but slow, compression. *) force_palette: if colortype is 2 or 6, you can make the encoder write a PLTE chunk if force_palette is true. This can used as suggested palette to convert to by viewers that don't support more than 256 colors (if those still exist) *) add_id: add text chunk "Encoder: LodePNG <version>" to the image. *) text_compression: default 1. If 1, it'll store texts as zTXt instead of tEXt chunks. zTXt chunks use zlib compression on the text. This gives a smaller result on large texts but a larger result on small texts (such as a single program name). It's all tEXt or all zTXt though, there's no separate setting per text yet. 6. color conversions -------------------- An important thing to note about LodePNG, is that the color type of the PNG, and the color type of the raw image, are completely independent. By default, when you decode a PNG, you get the result as a raw image in the color type you want, no matter whether the PNG was encoded with a palette, greyscale or RGBA color. And if you encode an image, by default LodePNG will automatically choose the PNG color type that gives good compression based on the values of colors and amount of colors in the image. It can be configured to let you control it instead as well, though. To be able to do this, LodePNG does conversions from one color mode to another. It can convert from almost any color type to any other color type, except the following conversions: RGB to greyscale is not supported, and converting to a palette when the palette doesn't have a required color is not supported. This is not supported on purpose: this is information loss which requires a color reduction algorithm that is beyong the scope of a PNG encoder (yes, RGB to grey is easy, but there are multiple ways if you want to give some channels more weight). By default, when decoding, you get the raw image in 32-bit RGBA or 24-bit RGB color, no matter what color type the PNG has. And by default when encoding, LodePNG automatically picks the best color model for the output PNG, and expects the input image to be 32-bit RGBA or 24-bit RGB. So, unless you want to control the color format of the images yourself, you can skip this chapter. 6.1. PNG color types -------------------- A PNG image can have many color types, ranging from 1-bit color to 64-bit color, as well as palettized color modes. After the zlib decompression and unfiltering in the PNG image is done, the raw pixel data will have that color type and thus a certain amount of bits per pixel. If you want the output raw image after decoding to have another color type, a conversion is done by LodePNG. The PNG specification gives the following color types: 0: greyscale, bit depths 1, 2, 4, 8, 16 2: RGB, bit depths 8 and 16 3: palette, bit depths 1, 2, 4 and 8 4: greyscale with alpha, bit depths 8 and 16 6: RGBA, bit depths 8 and 16 Bit depth is the amount of bits per pixel per color channel. So the total amount of bits per pixel is: amount of channels * bitdepth. 6.2. color conversions ---------------------- As explained in the sections about the encoder and decoder, you can specify color types and bit depths in info_png and info_raw to change the default behaviour. If, when decoding, you want the raw image to be something else than the default, you need to set the color type and bit depth you want in the LodePNGColorMode, or the parameters colortype and bitdepth of the simple decoding function. If, when encoding, you use another color type than the default in the raw input image, you need to specify its color type and bit depth in the LodePNGColorMode of the raw image, or use the parameters colortype and bitdepth of the simple encoding function. If, when encoding, you don't want LodePNG to choose the output PNG color type but control it yourself, you need to set auto_convert in the encoder settings to false, and specify the color type you want in the LodePNGInfo of the encoder (including palette: it can generate a palette if auto_convert is true, otherwise not). If the input and output color type differ (whether user chosen or auto chosen), LodePNG will do a color conversion, which follows the rules below, and may sometimes result in an error. To avoid some confusion: -the decoder converts from PNG to raw image -the encoder converts from raw image to PNG -the colortype and bitdepth in LodePNGColorMode info_raw, are those of the raw image -the colortype and bitdepth in the color field of LodePNGInfo info_png, are those of the PNG -when encoding, the color type in LodePNGInfo is ignored if auto_convert is enabled, it is automatically generated instead -when decoding, the color type in LodePNGInfo is set by the decoder to that of the original PNG image, but it can be ignored since the raw image has the color type you requested instead -if the color type of the LodePNGColorMode and PNG image aren't the same, a conversion between the color types is done if the color types are supported. If it is not supported, an error is returned. If the types are the same, no conversion is done. -even though some conversions aren't supported, LodePNG supports loading PNGs from any colortype and saving PNGs to any colortype, sometimes it just requires preparing the raw image correctly before encoding. -both encoder and decoder use the same color converter. Non supported color conversions: -color to greyscale: no error is thrown, but the result will look ugly because only the red channel is taken -anything to palette when that palette does not have that color in it: in this case an error is thrown Supported color conversions: -anything to 8-bit RGB, 8-bit RGBA, 16-bit RGB, 16-bit RGBA -any grey or grey+alpha, to grey or grey+alpha -anything to a palette, as long as the palette has the requested colors in it -removing alpha channel -higher to smaller bitdepth, and vice versa If you want no color conversion to be done (e.g. for speed or control): -In the encoder, you can make it save a PNG with any color type by giving the raw color mode and LodePNGInfo the same color mode, and setting auto_convert to false. -In the decoder, you can make it store the pixel data in the same color type as the PNG has, by setting the color_convert setting to false. Settings in info_raw are then ignored. The function lodepng_convert does the color conversion. It is available in the interface but normally isn't needed since the encoder and decoder already call it. 6.3. padding bits ----------------- In the PNG file format, if a less than 8-bit per pixel color type is used and the scanlines have a bit amount that isn't a multiple of 8, then padding bits are used so that each scanline starts at a fresh byte. But that is NOT true for the LodePNG raw input and output. The raw input image you give to the encoder, and the raw output image you get from the decoder will NOT have these padding bits, e.g. in the case of a 1-bit image with a width of 7 pixels, the first pixel of the second scanline will the the 8th bit of the first byte, not the first bit of a new byte. 6.4. A note about 16-bits per channel and endianness ---------------------------------------------------- LodePNG uses unsigned char arrays for 16-bit per channel colors too, just like for any other color format. The 16-bit values are stored in big endian (most significant byte first) in these arrays. This is the opposite order of the little endian used by x86 CPU's. LodePNG always uses big endian because the PNG file format does so internally. Conversions to other formats than PNG uses internally are not supported by LodePNG on purpose, there are myriads of formats, including endianness of 16-bit colors, the order in which you store R, G, B and A, and so on. Supporting and converting to/from all that is outside the scope of LodePNG. This may mean that, depending on your use case, you may want to convert the big endian output of LodePNG to little endian with a for loop. This is certainly not always needed, many applications and libraries support big endian 16-bit colors anyway, but it means you cannot simply cast the unsigned char* buffer to an unsigned short* buffer on x86 CPUs. 7. error values --------------- All functions in LodePNG that return an error code, return 0 if everything went OK, or a non-zero code if there was an error. The meaning of the LodePNG error values can be retrieved with the function lodepng_error_text: given the numerical error code, it returns a description of the error in English as a string. Check the implementation of lodepng_error_text to see the meaning of each code. 8. chunks and PNG editing ------------------------- If you want to add extra chunks to a PNG you encode, or use LodePNG for a PNG editor that should follow the rules about handling of unknown chunks, or if your program is able to read other types of chunks than the ones handled by LodePNG, then that's possible with the chunk functions of LodePNG. A PNG chunk has the following layout: 4 bytes length 4 bytes type name length bytes data 4 bytes CRC 8.1. iterating through chunks ----------------------------- If you have a buffer containing the PNG image data, then the first chunk (the IHDR chunk) starts at byte number 8 of that buffer. The first 8 bytes are the signature of the PNG and are not part of a chunk. But if you start at byte 8 then you have a chunk, and can check the following things of it. NOTE: none of these functions check for memory buffer boundaries. To avoid exploits, always make sure the buffer contains all the data of the chunks. When using lodepng_chunk_next, make sure the returned value is within the allocated memory. unsigned lodepng_chunk_length(const unsigned char* chunk): Get the length of the chunk's data. The total chunk length is this length + 12. void lodepng_chunk_type(char type[5], const unsigned char* chunk): unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type): Get the type of the chunk or compare if it's a certain type unsigned char lodepng_chunk_critical(const unsigned char* chunk): unsigned char lodepng_chunk_private(const unsigned char* chunk): unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk): Check if the chunk is critical in the PNG standard (only IHDR, PLTE, IDAT and IEND are). Check if the chunk is private (public chunks are part of the standard, private ones not). Check if the chunk is safe to copy. If it's not, then, when modifying data in a critical chunk, unsafe to copy chunks of the old image may NOT be saved in the new one if your program doesn't handle that type of unknown chunk. unsigned char* lodepng_chunk_data(unsigned char* chunk): const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk): Get a pointer to the start of the data of the chunk. unsigned lodepng_chunk_check_crc(const unsigned char* chunk): void lodepng_chunk_generate_crc(unsigned char* chunk): Check if the crc is correct or generate a correct one. unsigned char* lodepng_chunk_next(unsigned char* chunk): const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk): Iterate to the next chunk. This works if you have a buffer with consecutive chunks. Note that these functions do no boundary checking of the allocated data whatsoever, so make sure there is enough data available in the buffer to be able to go to the next chunk. unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk): unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length, const char* type, const unsigned char* data): These functions are used to create new chunks that are appended to the data in *out that has length *outlength. The append function appends an existing chunk to the new data. The create function creates a new chunk with the given parameters and appends it. Type is the 4-letter name of the chunk. 8.2. chunks in info_png ----------------------- The LodePNGInfo struct contains fields with the unknown chunk in it. It has 3 buffers (each with size) to contain 3 types of unknown chunks: the ones that come before the PLTE chunk, the ones that come between the PLTE and the IDAT chunks, and the ones that come after the IDAT chunks. It's necessary to make the distionction between these 3 cases because the PNG standard forces to keep the ordering of unknown chunks compared to the critical chunks, but does not force any other ordering rules. info_png.unknown_chunks_data[0] is the chunks before PLTE info_png.unknown_chunks_data[1] is the chunks after PLTE, before IDAT info_png.unknown_chunks_data[2] is the chunks after IDAT The chunks in these 3 buffers can be iterated through and read by using the same way described in the previous subchapter. When using the decoder to decode a PNG, you can make it store all unknown chunks if you set the option settings.remember_unknown_chunks to 1. By default, this option is off (0). The encoder will always encode unknown chunks that are stored in the info_png. If you need it to add a particular chunk that isn't known by LodePNG, you can use lodepng_chunk_append or lodepng_chunk_create to the chunk data in info_png.unknown_chunks_data[x]. Chunks that are known by LodePNG should not be added in that way. E.g. to make LodePNG add a bKGD chunk, set background_defined to true and add the correct parameters there instead. 9. compiler support ------------------- No libraries other than the current standard C library are needed to compile LodePNG. For the C++ version, only the standard C++ library is needed on top. Add the files lodepng.c(pp) and lodepng.h to your project, include lodepng.h where needed, and your program can read/write PNG files. It is compatible with C90 and up, and C++03 and up. If performance is important, use optimization when compiling! For both the encoder and decoder, this makes a large difference. Make sure that LodePNG is compiled with the same compiler of the same version and with the same settings as the rest of the program, or the interfaces with std::vectors and std::strings in C++ can be incompatible. CHAR_BITS must be 8 or higher, because LodePNG uses unsigned chars for octets. *) gcc and g++ LodePNG is developed in gcc so this compiler is natively supported. It gives no warnings with compiler options "-Wall -Wextra -pedantic -ansi", with gcc and g++ version 4.7.1 on Linux, 32-bit and 64-bit. *) Clang Fully supported and warning-free. *) Mingw The Mingw compiler (a port of gcc for Windows) should be fully supported by LodePNG. *) Visual Studio and Visual C++ Express Edition LodePNG should be warning-free with warning level W4. Two warnings were disabled with pragmas though: warning 4244 about implicit conversions, and warning 4996 where it wants to use a non-standard function fopen_s instead of the standard C fopen. Visual Studio may want "stdafx.h" files to be included in each source file and give an error "unexpected end of file while looking for precompiled header". This is not standard C++ and will not be added to the stock LodePNG. You can disable it for lodepng.cpp only by right clicking it, Properties, C/C++, Precompiled Headers, and set it to Not Using Precompiled Headers there. NOTE: Modern versions of VS should be fully supported, but old versions, e.g. VS6, are not guaranteed to work. *) Compilers on Macintosh LodePNG has been reported to work both with gcc and LLVM for Macintosh, both for C and C++. *) Other Compilers If you encounter problems on any compilers, feel free to let me know and I may try to fix it if the compiler is modern and standards complient. 10. examples ------------ This decoder example shows the most basic usage of LodePNG. More complex examples can be found on the LodePNG website. 10.1. decoder C++ example ------------------------- #include "lodepng.h" #include <iostream> int main(int argc, char *argv[]) { const char* filename = argc > 1 ? argv[1] : "test.png"; //load and decode std::vector<unsigned char> image; unsigned width, height; unsigned error = lodepng::decode(image, width, height, filename); //if there's an error, display it if(error) std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl; //the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ... } 10.2. decoder C example ----------------------- #include "lodepng.h" int main(int argc, char *argv[]) { unsigned error; unsigned char* image; size_t width, height; const char* filename = argc > 1 ? argv[1] : "test.png"; error = lodepng_decode32_file(&image, &width, &height, filename); if(error) printf("decoder error %u: %s\n", error, lodepng_error_text(error)); / * use image here * / free(image); return 0; } 11. state settings reference ---------------------------- A quick reference of some settings to set on the LodePNGState For decoding: state.decoder.zlibsettings.ignore_adler32: ignore ADLER32 checksums state.decoder.zlibsettings.custom_...: use custom inflate function state.decoder.ignore_crc: ignore CRC checksums state.decoder.color_convert: convert internal PNG color to chosen one state.decoder.read_text_chunks: whether to read in text metadata chunks state.decoder.remember_unknown_chunks: whether to read in unknown chunks state.info_raw.colortype: desired color type for decoded image state.info_raw.bitdepth: desired bit depth for decoded image state.info_raw....: more color settings, see struct LodePNGColorMode state.info_png....: no settings for decoder but ouput, see struct LodePNGInfo For encoding: state.encoder.zlibsettings.btype: disable compression by setting it to 0 state.encoder.zlibsettings.use_lz77: use LZ77 in compression state.encoder.zlibsettings.windowsize: tweak LZ77 windowsize state.encoder.zlibsettings.minmatch: tweak min LZ77 length to match state.encoder.zlibsettings.nicematch: tweak LZ77 match where to stop searching state.encoder.zlibsettings.lazymatching: try one more LZ77 matching state.encoder.zlibsettings.custom_...: use custom deflate function state.encoder.auto_convert: choose optimal PNG color type, if 0 uses info_png state.encoder.filter_palette_zero: PNG filter strategy for palette state.encoder.filter_strategy: PNG filter strategy to encode with state.encoder.force_palette: add palette even if not encoding to one state.encoder.add_id: add LodePNG identifier and version as a text chunk state.encoder.text_compression: use compressed text chunks for metadata state.info_raw.colortype: color type of raw input image you provide state.info_raw.bitdepth: bit depth of raw input image you provide state.info_raw: more color settings, see struct LodePNGColorMode state.info_png.color.colortype: desired color type if auto_convert is false state.info_png.color.bitdepth: desired bit depth if auto_convert is false state.info_png.color....: more color settings, see struct LodePNGColorMode state.info_png....: more PNG related settings, see struct LodePNGInfo 12. changes ----------- The version number of LodePNG is the date of the change given in the format yyyymmdd. Some changes aren't backwards compatible. Those are indicated with a (!) symbol. *) 18 apr 2016: Changed qsort to custom stable sort (for platforms w/o qsort). *) 09 apr 2016: Fixed colorkey usage detection, and better file loading (within the limits of pure C90). *) 08 dec 2015: Made load_file function return error if file can't be opened. *) 24 okt 2015: Bugfix with decoding to palette output. *) 18 apr 2015: Boundary PM instead of just package-merge for faster encoding. *) 23 aug 2014: Reduced needless memory usage of decoder. *) 28 jun 2014: Removed fix_png setting, always support palette OOB for simplicity. Made ColorProfile public. *) 09 jun 2014: Faster encoder by fixing hash bug and more zeros optimization. *) 22 dec 2013: Power of two windowsize required for optimization. *) 15 apr 2013: Fixed bug with LAC_ALPHA and color key. *) 25 mar 2013: Added an optional feature to ignore some PNG errors (fix_png). *) 11 mar 2013 (!): Bugfix with custom free. Changed from "my" to "lodepng_" prefix for the custom allocators and made it possible with a new #define to use custom ones in your project without needing to change lodepng's code. *) 28 jan 2013: Bugfix with color key. *) 27 okt 2012: Tweaks in text chunk keyword length error handling. *) 8 okt 2012 (!): Added new filter strategy (entropy) and new auto color mode. (no palette). Better deflate tree encoding. New compression tweak settings. Faster color conversions while decoding. Some internal cleanups. *) 23 sep 2012: Reduced warnings in Visual Studio a little bit. *) 1 sep 2012 (!): Removed #define's for giving custom (de)compression functions and made it work with function pointers instead. *) 23 jun 2012: Added more filter strategies. Made it easier to use custom alloc and free functions and toggle #defines from compiler flags. Small fixes. *) 6 may 2012 (!): Made plugging in custom zlib/deflate functions more flexible. *) 22 apr 2012 (!): Made interface more consistent, renaming a lot. Removed redundant C++ codec classes. Reduced amount of structs. Everything changed, but it is cleaner now imho and functionality remains the same. Also fixed several bugs and shrunk the implementation code. Made new samples. *) 6 nov 2011 (!): By default, the encoder now automatically chooses the best PNG color model and bit depth, based on the amount and type of colors of the raw image. For this, autoLeaveOutAlphaChannel replaced by auto_choose_color. *) 9 okt 2011: simpler hash chain implementation for the encoder. *) 8 sep 2011: lz77 encoder lazy matching instead of greedy matching. *) 23 aug 2011: tweaked the zlib compression parameters after benchmarking. A bug with the PNG filtertype heuristic was fixed, so that it chooses much better ones (it's quite significant). A setting to do an experimental, slow, brute force search for PNG filter types is added. *) 17 aug 2011 (!): changed some C zlib related function names. *) 16 aug 2011: made the code less wide (max 120 characters per line). *) 17 apr 2011: code cleanup. Bugfixes. Convert low to 16-bit per sample colors. *) 21 feb 2011: fixed compiling for C90. Fixed compiling with sections disabled. *) 11 dec 2010: encoding is made faster, based on suggestion by Peter Eastman to optimize long sequences of zeros. *) 13 nov 2010: added LodePNG_InfoColor_hasPaletteAlpha and LodePNG_InfoColor_canHaveAlpha functions for convenience. *) 7 nov 2010: added LodePNG_error_text function to get error code description. *) 30 okt 2010: made decoding slightly faster *) 26 okt 2010: (!) changed some C function and struct names (more consistent). Reorganized the documentation and the declaration order in the header. *) 08 aug 2010: only changed some comments and external samples. *) 05 jul 2010: fixed bug thanks to warnings in the new gcc version. *) 14 mar 2010: fixed bug where too much memory was allocated for char buffers. *) 02 sep 2008: fixed bug where it could create empty tree that linux apps could read by ignoring the problem but windows apps couldn't. *) 06 jun 2008: added more error checks for out of memory cases. *) 26 apr 2008: added a few more checks here and there to ensure more safety. *) 06 mar 2008: crash with encoding of strings fixed *) 02 feb 2008: support for international text chunks added (iTXt) *) 23 jan 2008: small cleanups, and #defines to divide code in sections *) 20 jan 2008: support for unknown chunks allowing using LodePNG for an editor. *) 18 jan 2008: support for tIME and pHYs chunks added to encoder and decoder. *) 17 jan 2008: ability to encode and decode compressed zTXt chunks added Also various fixes, such as in the deflate and the padding bits code. *) 13 jan 2008: Added ability to encode Adam7-interlaced images. Improved filtering code of encoder. *) 07 jan 2008: (!) changed LodePNG to use ISO C90 instead of C++. A C++ wrapper around this provides an interface almost identical to before. Having LodePNG be pure ISO C90 makes it more portable. The C and C++ code are together in these files but it works both for C and C++ compilers. *) 29 dec 2007: (!) changed most integer types to unsigned int + other tweaks *) 30 aug 2007: bug fixed which makes this Borland C++ compatible *) 09 aug 2007: some VS2005 warnings removed again *) 21 jul 2007: deflate code placed in new namespace separate from zlib code *) 08 jun 2007: fixed bug with 2- and 4-bit color, and small interlaced images *) 04 jun 2007: improved support for Visual Studio 2005: crash with accessing invalid std::vector element [0] fixed, and level 3 and 4 warnings removed *) 02 jun 2007: made the encoder add a tag with version by default *) 27 may 2007: zlib and png code separated (but still in the same file), simple encoder/decoder functions added for more simple usage cases *) 19 may 2007: minor fixes, some code cleaning, new error added (error 69), moved some examples from here to lodepng_examples.cpp *) 12 may 2007: palette decoding bug fixed *) 24 apr 2007: changed the license from BSD to the zlib license *) 11 mar 2007: very simple addition: ability to encode bKGD chunks. *) 04 mar 2007: (!) tEXt chunk related fixes, and support for encoding palettized PNG images. Plus little interface change with palette and texts. *) 03 mar 2007: Made it encode dynamic Huffman shorter with repeat codes. Fixed a bug where the end code of a block had length 0 in the Huffman tree. *) 26 feb 2007: Huffman compression with dynamic trees (BTYPE 2) now implemented and supported by the encoder, resulting in smaller PNGs at the output. *) 27 jan 2007: Made the Adler-32 test faster so that a timewaste is gone. *) 24 jan 2007: gave encoder an error interface. Added color conversion from any greyscale type to 8-bit greyscale with or without alpha. *) 21 jan 2007: (!) Totally changed the interface. It allows more color types to convert to and is more uniform. See the manual for how it works now. *) 07 jan 2007: Some cleanup & fixes, and a few changes over the last days: encode/decode custom tEXt chunks, separate classes for zlib & deflate, and at last made the decoder give errors for incorrect Adler32 or Crc. *) 01 jan 2007: Fixed bug with encoding PNGs with less than 8 bits per channel. *) 29 dec 2006: Added support for encoding images without alpha channel, and cleaned out code as well as making certain parts faster. *) 28 dec 2006: Added "Settings" to the encoder. *) 26 dec 2006: The encoder now does LZ77 encoding and produces much smaller files now. Removed some code duplication in the decoder. Fixed little bug in an example. *) 09 dec 2006: (!) Placed output parameters of public functions as first parameter. Fixed a bug of the decoder with 16-bit per color. *) 15 okt 2006: Changed documentation structure *) 09 okt 2006: Encoder class added. It encodes a valid PNG image from the given image buffer, however for now it's not compressed. *) 08 sep 2006: (!) Changed to interface with a Decoder class *) 30 jul 2006: (!) LodePNG_InfoPng , width and height are now retrieved in different way. Renamed decodePNG to decodePNGGeneric. *) 29 jul 2006: (!) Changed the interface: image info is now returned as a struct of type LodePNG::LodePNG_Info, instead of a vector, which was a bit clumsy. *) 28 jul 2006: Cleaned the code and added new error checks. Corrected terminology "deflate" into "inflate". *) 23 jun 2006: Added SDL example in the documentation in the header, this example allows easy debugging by displaying the PNG and its transparency. *) 22 jun 2006: (!) Changed way to obtain error value. Added loadFile function for convenience. Made decodePNG32 faster. *) 21 jun 2006: (!) Changed type of info vector to unsigned. Changed position of palette in info vector. Fixed an important bug that happened on PNGs with an uncompressed block. *) 16 jun 2006: Internally changed unsigned into unsigned where needed, and performed some optimizations. *) 07 jun 2006: (!) Renamed functions to decodePNG and placed them in LodePNG namespace. Changed the order of the parameters. Rewrote the documentation in the header. Renamed files to lodepng.cpp and lodepng.h *) 22 apr 2006: Optimized and improved some code *) 07 sep 2005: (!) Changed to std::vector interface *) 12 aug 2005: Initial release (C++, decoder only) 13. contact information ----------------------- Feel free to contact me with suggestions, problems, comments, ... concerning LodePNG. If you encounter a PNG image that doesn't work properly with this decoder, feel free to send it and I'll use it to find and fix the problem. My email address is (puzzle the account and domain together with an @ symbol): Domain: gmail dot com. Account: lode dot vandevenne. Copyright (c) 2005-2016 Lode Vandevenne */
ff5c6cb2f08573088a06c7e2f4f144253a695edc
c0d04464479440bac6c100e3970cf159c5278f04
/imap.hpp
58a37db267447b36687bc1a2dcfec17aab17ca68
[]
no_license
Ares0324/OOP_MailPunk
68cb902e6cb9114a16e7c2513d277837db4cb273
d950c76ec0131fd1778fa6edb74f955b6f0c1b8c
refs/heads/master
2020-04-10T18:08:18.399666
2018-12-14T15:05:04
2018-12-14T15:05:04
161,194,915
0
0
null
null
null
null
UTF-8
C++
false
false
1,292
hpp
#ifndef IMAP_H #define IMAP_H #include "imaputils.hpp" #include <libetpan/libetpan.h> #include <string> #include <functional> namespace IMAP { class Message { unsigned int uid; std::string subject; std::string from; std::string body; public: Message(){} /** * Get the body of the message. You may chose to either include the headers or not. */ std::string getBody(); /** * Get one of the descriptor fields (subject, from, ...) */ std::string getField(std::string fieldname); /** * Remove this mail from its mailbox */ void deleteFromMailbox(); }; class Session { struct mailimap* imap; public: Session(std::function<void()> updateUI); /** * Get all messages in the INBOX mailbox terminated by a nullptr (like we did in class) */ Message** getMessages(); /** * connect to the specified server (143 is the standard unencrypte imap port) */ void connect(std::string const& server, size_t port = 143); /** * log in to the server (connect first, then log in) */ void login(std::string const& userid, std::string const& password); /** * select a mailbox (only one can be selected at any given time) * * this can only be performed after login */ void selectMailbox(std::string const& mailbox); ~Session(); }; } #endif /* IMAP_H */
bc0afcd9d4e406adc20d71000beec2c738605b56
0fda425126b4f6683cf575150d9db16a4eeb69ea
/cxx/graphidx/utils/viostream.hpp
12e691068352617109257dd9275841acbdd88f8b
[ "MIT" ]
permissive
EQt/graphidx
a62d22f5cda4f7f288d78852e97d231e1df1e804
cf29ef577083d1c5a22fb3fb23519e29f89674a5
refs/heads/main
2022-09-09T01:35:06.519563
2022-01-12T17:16:12
2022-01-12T17:16:12
207,818,825
4
0
null
null
null
null
UTF-8
C++
false
false
3,194
hpp
/** Input/output in the style of `iostream` / `cstdio` on containers. As long as a container `C` has support of `std::begin(&C)` and `std::end(&C)` the functions `std::cout << printer(c)` and `std::to_string(printer(c))` should produce a sensible list format. */ #pragma once #include <cstdio> #include <iostream> #include <set> #include <sstream> #include <vector> #include "../std/uvector.hpp" template <typename int_ = int> std::ostream& operator<<(std::ostream &out, const std::tuple<int_, int_> &t) { out << "[" << std::get<0>(t) << ", " << std::get<1>(t) << "]"; return out; } template <typename B, typename E> inline std::ostream& _print_list(std::ostream &o, const B &begin, const E &end, const bool curly = false) { bool first = true; o << (curly ? "{" : "["); for (auto it = begin; it != end; it++) { auto x = *it; if (first) { first = false; } else o << ", "; o << x; } return o << (curly ? "}" : "]"); } template <typename T> struct _Vec { const T *start; const size_t n; const T* begin() const { return start; } const T* end() const { return start + n; } }; template <typename T> inline _Vec<T> Vec(const T* start, size_t n) { return _Vec<T> {start, n}; } template<typename Container> inline void print_int_list( const Container &x, const char *sep = " ", FILE *out = stdout, const char * fmt = "%ld") { fprintf(out, "["); bool first = true; for (auto xi : x) { if (first) { first = false; } else { fprintf(out, "%s", sep); } fprintf(out, fmt, (long int)xi); } fprintf(out, "]\n"); } template<typename Container> inline void print_double_list( const Container &x, const int prec = 4, FILE *out = stdout, const char * fmt = "%.*f") { fprintf(out, "["); bool first = true; for (double xi : x) { if (first) { first = false; } else { fprintf(out, ", "); } fprintf(out, fmt, prec, xi); } fprintf(out, "]\n"); } template <typename T> struct _Printer { T &c; _Printer(T &c) : c(c) { } }; template <typename T> _Printer<T> printer(T &c) { return _Printer<T>(c); } namespace std { template <typename E> inline ostream& operator<<(ostream &o, const _Printer<E> &v) { return ::_print_list(o, begin(v.c), end(v.c)); } template <typename E> inline std::ostream& operator<<(std::ostream &o, const std::set<E> &v) { return ::_print_list(o, std::begin(v), std::end(v), true); } template <typename E> inline ostream& operator<<(ostream &o, const std::vector<E> &v) { return o << ::printer(v); } template <typename E> inline ostream& operator<<(ostream &o, const uvector<E> &v) { return o << ::printer(v); } template<typename E> std::string to_string(const std::vector<E> &v) { ostringstream s; s << v; return s.str(); } template<typename E> std::string to_string(const uvector<E> &v) { ostringstream s; s << v; return s.str(); } template<typename E> std::string to_string(const _Printer<E> &v) { ostringstream s; s << v; return s.str(); } } // namespace std::
cdef16a2c9dbab0aa54c3510c986b54cb968d44b
e43a512027ec7d98b9d78aec54a21f17b1e0ee87
/model/tree.h
3654d2590a3dd04f1930b70fd94deaf4d7a70f3a
[]
no_license
aksenoff/fastcomp
6670efde68ad4110b41c7b905a234247f82d1f13
67c65daac506d69c1a18570ad6c82ba0d15a4f08
refs/heads/master
2020-07-01T04:57:21.495614
2019-03-25T22:23:47
2019-03-25T22:23:47
32,548,595
0
0
null
2019-03-25T22:24:16
2015-03-19T22:03:21
C++
UTF-8
C++
false
false
652
h
#ifndef TREE_H #define TREE_H /* A tree holding probabilities for bytes encountered in input stream */ #include "..\common_arith\common_arith.h" #include "node.h" #include "model.h" class Node; class Model; extern FILE *log_file; extern Model model; class Tree { public: Tree(); void encode(short, SYMBOL*); void rescale(); void get_scale(SYMBOL*); short decode(unsigned short, SYMBOL*); void insert(unsigned short); unsigned short calculate_escape(); Node *rootNode; unsigned short totalCount; // total number of symbols encoded unsigned short numNodes; // number of different symbols encoded }; #endif
25ca68fd908a78596792aa2922dfd411ec75a865
d06a1a65bdf2b9d8be005f2c4ac58c68567d32b9
/41Write_File.cpp
b7aee6438dad7137c6c30059fcc31f6d226cedaa
[]
no_license
sinjin314/C-Plus-Plus-OOP-Programming
8af217cdc33af34757c548d94b9a932cff52d19a
c48aa5c3bc1d312237feb64033931a89ef12755f
refs/heads/master
2022-04-07T11:00:07.622362
2020-03-09T11:14:15
2020-03-09T11:14:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
601
cpp
#include <iostream> #include <fstream> #include<conio.h> using namespace std; /******************* ofstream Creates and writes to files ifstream Reads from files fstream A combination of ofstream and ifstream: creates, reads, and writes to files ***************************/ //To write to the file, use the insertion operator (<<) like operator overloading int main() { // Create and open a text file ofstream MyFile("myfile.txt"); // Write to the file MyFile << "Files can be tricky, but it is fun enough!"; // Close the file MyFile.close(); return 0; } //Navjot Singh Prince
7b9aa59010c6734b49b847230efc6b750a17e134
7d64e03e403eca85248677d8dc72751c93940e48
/test/db/MojDbWatchTest.cpp
e8ff1c7e3c32410b09acaf5ed4589b34a6d8d1e2
[ "Apache-2.0" ]
permissive
webosce/db8
a6f6ec64d3cb8653dc522ee7a3e8fad78fcc0203
994da8732319c6cafc59778eec5f82186f73b6ab
refs/heads/webosce
2023-05-13T15:18:39.562208
2018-08-23T08:51:14
2018-09-14T13:30:43
145,513,369
0
1
Apache-2.0
2023-04-26T02:43:57
2018-08-21T05:52:45
C++
UTF-8
C++
false
false
14,711
cpp
// Copyright (c) 2009-2018 LG Electronics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #include "MojDbWatchTest.h" #include "db/MojDb.h" static const MojChar* const MojKindStr = _T("{\"id\":\"WatchTest:1\",") _T("\"owner\":\"mojodb.admin\",") _T("\"indexes\":[{\"name\":\"foo\",\"props\":[{\"name\":\"foo\"}]},") _T("{\"name\":\"foo_rev\",\"props\":[{\"name\":\"foo\"},{\"name\":\"_rev\"}], \"incDel\":true},") _T("{\"name\":\"barfoo\",\"props\":[{\"name\":\"bar\"},{\"name\":\"foo\"}]}]}"); class TestWatcher : public MojSignalHandler { public: TestWatcher() : m_slot(this, &TestWatcher::handleChange), m_count(0) { ++s_instanceCount; } ~TestWatcher() { --s_instanceCount; } MojErr handleChange() { ++m_count; return MojErrNone; } MojDb::WatchSignal::Slot<TestWatcher> m_slot; int m_count; static int s_instanceCount; }; int TestWatcher::s_instanceCount = 0; MojDbWatchTest::MojDbWatchTest() : MojTestCase(_T("MojDbWatch")) { } MojErr MojDbWatchTest::run() { MojDb db; MojErr err = db.open(MojDbTestDir); MojTestErrCheck(err); MojObject type; err = type.fromJson(MojKindStr); MojTestErrCheck(err); err = db.putKind(type); MojTestErrCheck(err); // eq err = eqTest(db); MojTestErrCheck(err); // gt err = gtTest(db); MojTestErrCheck(err); // lt err = ltTest(db); MojTestErrCheck(err); // cancel err = cancelTest(db); MojTestErrCheck(err); // range err = rangeTest(db); MojTestErrCheck(err); // pages err = pageTest(db); MojTestErrCheck(err); // make sure we're not hanging onto watcher references MojTestAssert(TestWatcher::s_instanceCount == 0); err = db.close(); MojTestErrCheck(err); return MojErrNone; } MojErr MojDbWatchTest::eqTest(MojDb& db) { MojDbQuery query; MojErr err = query.from(_T("WatchTest:1")); MojTestErrCheck(err); err = query.where(_T("foo"), MojDbQuery::OpEq, 1); MojTestErrCheck(err); MojRefCountedPtr<TestWatcher> watcher(new TestWatcher); MojTestAssert(watcher.get()); MojDbCursor cursor; err = db.find(query, cursor, watcher->m_slot); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); MojTestAssert(watcher->m_count == 0); MojRefCountedPtr<TestWatcher> watcher2(new TestWatcher); MojTestAssert(watcher2.get()); bool fired = false; err = db.watch(query, cursor, watcher2->m_slot, fired); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); MojTestAssert(!fired); // puts MojObject id; err = put(db, 0, 0, id, m_rev); MojTestErrCheck(err); MojTestAssert(watcher->m_count == 0); MojTestAssert(watcher2->m_count == 0); err = put(db, 2, 2, id, m_rev); MojTestErrCheck(err); MojTestAssert(watcher->m_count == 0); MojTestAssert(watcher2->m_count == 0); err = put(db, 1, 1, id, m_rev); MojTestErrCheck(err); MojTestAssert(watcher->m_count == 1); MojTestAssert(watcher2->m_count == 1); err = put(db, 1, 1, id, m_rev); MojTestErrCheck(err); MojTestAssert(watcher->m_count == 1); MojTestAssert(watcher2->m_count == 1); // put, changing property not in index watcher.reset(new TestWatcher); MojTestAssert(watcher.get()); err = db.find(query, cursor, watcher->m_slot); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); err = put(db, 1, 2, id, m_rev); MojTestErrCheck(err); MojTestAssert(watcher->m_count == 1); // dels watcher.reset(new TestWatcher); MojTestAssert(watcher.get()); err = db.find(query, cursor, watcher->m_slot); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); watcher2.reset(new TestWatcher); MojTestAssert(watcher2.get()); MojDbQuery queryWithRev; err = queryWithRev.from(_T("WatchTest:1")); MojTestErrCheck(err); err = queryWithRev.where(_T("foo"), MojDbQuery::OpEq, 1); MojTestErrCheck(err); err = queryWithRev.where(_T("_rev"), MojDbQuery::OpGreaterThan, m_rev); MojTestErrCheck(err); err = queryWithRev.includeDeleted(); MojTestErrCheck(err); fired = false; err = db.watch(queryWithRev, cursor, watcher2->m_slot, fired); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); MojTestAssert(!fired); MojTestAssert(watcher->m_count == 0); MojTestAssert(watcher2->m_count == 0); bool found; err = db.del(id, found); MojTestErrCheck(err); MojTestAssert(found); MojTestAssert(watcher->m_count == 1); MojTestAssert(watcher2->m_count == 1); // ordering watcher.reset(new TestWatcher); MojTestAssert(watcher.get()); err = db.find(query, cursor, watcher->m_slot); MojTestErrCheck(err); err = put(db, 1, 1, id, m_rev); MojTestErrCheck(err); MojTestAssert(watcher->m_count == 0); err = cursor.close(); MojTestErrCheck(err); MojTestAssert(watcher->m_count == 1); return MojErrNone; } MojErr MojDbWatchTest::gtTest(MojDb& db) { MojDbQuery query; MojErr err = query.from(_T("WatchTest:1")); MojTestErrCheck(err); err = query.where(_T("foo"), MojDbQuery::OpGreaterThan, 1); MojTestErrCheck(err); MojRefCountedPtr<TestWatcher> watcher(new TestWatcher); MojTestAssert(watcher.get()); MojDbCursor cursor; err = db.find(query, cursor, watcher->m_slot); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); MojTestAssert(watcher->m_count == 0); MojRefCountedPtr<TestWatcher> watcher2(new TestWatcher); MojTestAssert(watcher2.get()); MojDbQuery queryWithRev; err = queryWithRev.from(_T("WatchTest:1")); MojTestErrCheck(err); err = queryWithRev.where(_T("foo"), MojDbQuery::OpEq, 2); MojTestErrCheck(err); err = queryWithRev.where(_T("_rev"), MojDbQuery::OpGreaterThan, m_rev); MojTestErrCheck(err); bool fired = false; err = db.watch(queryWithRev, cursor, watcher2->m_slot, fired); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); MojTestAssert(!fired); MojObject id; err = put(db, 1, 1, id, m_rev); MojTestErrCheck(err); MojTestAssert(watcher->m_count == 0); MojTestAssert(watcher2->m_count == 0); err = put(db, 2, 2, id, m_rev); MojTestErrCheck(err); MojTestAssert(watcher->m_count == 1); MojTestAssert(watcher2->m_count == 1); err = put(db, 2, 2, id, m_rev); MojTestErrCheck(err); MojTestAssert(watcher->m_count == 1); MojTestAssert(watcher2->m_count == 1); return MojErrNone; } MojErr MojDbWatchTest::ltTest(MojDb& db) { MojDbQuery query; MojErr err = query.from(_T("WatchTest:1")); MojTestErrCheck(err); err = query.where(_T("foo"), MojDbQuery::OpLessThanEq, 45); MojTestErrCheck(err); MojRefCountedPtr<TestWatcher> watcher(new TestWatcher); MojTestAssert(watcher.get()); MojDbCursor cursor; err = db.find(query, cursor, watcher->m_slot); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); MojTestAssert(watcher->m_count == 0); MojRefCountedPtr<TestWatcher> watcher2(new TestWatcher); MojTestAssert(watcher2.get()); MojDbQuery queryWithRev; err = queryWithRev.from(_T("WatchTest:1")); MojTestErrCheck(err); err = queryWithRev.where(_T("foo"), MojDbQuery::OpEq, 45); MojTestErrCheck(err); err = queryWithRev.where(_T("_rev"), MojDbQuery::OpGreaterThan, m_rev); MojTestErrCheck(err); bool fired = false; err = db.watch(queryWithRev, cursor, watcher2->m_slot, fired); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); MojTestAssert(!fired); MojObject id; err = put(db, 46, 46, id, m_rev); MojTestErrCheck(err); MojTestAssert(watcher->m_count == 0); MojTestAssert(watcher2->m_count == 0); err = put(db, 45, 45, id, m_rev); MojTestErrCheck(err); MojTestAssert(watcher->m_count == 1); MojTestAssert(watcher2->m_count == 1); err = put(db, 45, 45, id, m_rev); MojTestErrCheck(err); MojTestAssert(watcher->m_count == 1); MojTestAssert(watcher2->m_count == 1); return MojErrNone; } MojErr MojDbWatchTest::cancelTest(MojDb& db) { // cancel find MojDbQuery query; MojErr err = query.from(_T("WatchTest:1")); MojTestErrCheck(err); err = query.where(_T("foo"), MojDbQuery::OpLessThanEq, 45); MojTestErrCheck(err); MojRefCountedPtr<TestWatcher> watcher(new TestWatcher); MojTestAssert(watcher.get()); watcher->m_slot.cancel(); MojDbCursor cursor; err = db.find(query, cursor, watcher->m_slot); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); MojTestAssert(watcher->m_count == 0); watcher->m_slot.cancel(); MojTestAssert(watcher->m_count == 0); MojObject id; err = put(db, 1, 1, id, m_rev); MojTestErrCheck(err); MojTestAssert(watcher->m_count == 0); // cancel watch watcher.reset(new TestWatcher); MojTestAssert(watcher.get()); MojDbQuery queryWithRev; err = queryWithRev.from(_T("WatchTest:1")); MojTestErrCheck(err); err = queryWithRev.where(_T("foo"), MojDbQuery::OpEq, 45); MojTestErrCheck(err); err = queryWithRev.where(_T("_rev"), MojDbQuery::OpGreaterThan, m_rev); MojTestErrCheck(err); bool fired = false; err = db.watch(queryWithRev, cursor, watcher->m_slot, fired); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); MojTestAssert(!fired); MojTestAssert(watcher->m_count == 0); watcher->m_slot.cancel(); MojTestAssert(watcher->m_count == 0); err = put(db, 45, 45, id, m_rev); MojTestErrCheck(err); MojTestAssert(watcher->m_count == 0); return MojErrNone; } MojErr MojDbWatchTest::rangeTest(MojDb& db) { MojDbQuery query; MojErr err = query.from(_T("WatchTest:1")); MojTestErrCheck(err); err = query.where(_T("foo"), MojDbQuery::OpGreaterThan, 5); MojTestErrCheck(err); err = query.where(_T("foo"), MojDbQuery::OpLessThan, 100); MojTestErrCheck(err); MojRefCountedPtr<TestWatcher> watcher(new TestWatcher); MojTestAssert(watcher.get()); MojDbCursor cursor; err = db.find(query, cursor, watcher->m_slot); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); MojTestAssert(watcher->m_count == 0); MojObject id; MojInt64 rev; err = put(db, 5, 5, id, rev); MojTestErrCheck(err); MojTestAssert(watcher->m_count == 0); err = put(db, 100, 100, id, rev); MojTestErrCheck(err); MojTestAssert(watcher->m_count == 0); err = put(db, 6, 6, id, rev); MojTestErrCheck(err); MojTestAssert(watcher->m_count == 1); watcher.reset(new TestWatcher); MojTestAssert(watcher.get()); err = db.find(query, cursor, watcher->m_slot); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); MojTestAssert(watcher->m_count == 0); err = put(db, 99, 99, id, rev); MojTestErrCheck(err); MojTestAssert(watcher->m_count == 1); return MojErrNone; } MojErr MojDbWatchTest::pageTest(MojDb& db) { MojObject id; MojObject idFirst; MojObject idFourth; MojObject idLast; MojInt64 rev; for (int i = 100; i < 150; ++i) { MojErr err = put(db, 100, i, id, rev); MojTestErrCheck(err); if (i == 100) { idFirst = id; } else if (i == 103) { idFourth = id; } else if (i == 149) { idLast = id; } } MojDbQuery query; MojErr err = query.from(_T("WatchTest:1")); MojTestErrCheck(err); err = query.where(_T("foo"), MojDbQuery::OpGreaterThanEq, 100); MojTestErrCheck(err); query.limit(3); MojRefCountedPtr<TestWatcher> watcher(new TestWatcher); MojTestAssert(watcher.get()); MojDbCursor cursor; err = db.find(query, cursor, watcher->m_slot); MojTestErrCheck(err); bool found = false; MojUInt32 count = 0; do { MojObject obj; err = cursor.get(obj, found); MojTestErrCheck(err); if (found) ++count; } while (found); MojTestAssert(count == 3); MojDbQuery::Page page; err = cursor.nextPage(page); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); err = merge(db, idFourth, 53); MojTestErrCheck(err); MojTestAssert(watcher->m_count == 0); query.page(page); MojRefCountedPtr<TestWatcher> watcher2(new TestWatcher); MojTestAssert(watcher2.get()); err = db.find(query, cursor, watcher2->m_slot); MojTestErrCheck(err); found = false; count = 0; do { MojObject obj; err = cursor.get(obj, found); MojTestErrCheck(err); if (found) ++count; } while (found); MojTestAssert(count == 3); err = cursor.close(); MojTestErrCheck(err); err = db.del(idFirst, found); MojTestErrCheck(err); MojTestAssert(found); MojTestAssert(watcher->m_count == 1); MojTestAssert(watcher2->m_count == 0); err = db.del(idFourth, found); MojTestErrCheck(err); MojTestAssert(found); MojTestAssert(watcher->m_count == 1); MojTestAssert(watcher2->m_count == 1); // desc order query.page(MojDbQuery::Page()); query.desc(true); MojRefCountedPtr<TestWatcher> watcher3(new TestWatcher); MojTestAssert(watcher3.get()); err = db.find(query, cursor, watcher3->m_slot); MojTestErrCheck(err); found = false; count = 0; do { MojObject obj; err = cursor.get(obj, found); MojTestErrCheck(err); if (found) ++count; } while (found); MojTestAssert(count == 3); err = cursor.close(); MojTestErrCheck(err); err = merge(db, idLast, 53); MojTestErrCheck(err); MojTestAssert(watcher3->m_count == 1); MojRefCountedPtr<TestWatcher> watcher4(new TestWatcher); MojTestAssert(watcher4.get()); err = db.find(query, cursor, watcher4->m_slot); MojTestErrCheck(err); found = false; count = 0; do { MojObject obj; err = cursor.get(obj, found); MojTestErrCheck(err); if (found) ++count; } while (found); MojTestAssert(count == 3); err = cursor.close(); MojTestErrCheck(err); err = merge(db, idLast, 54); MojTestErrCheck(err); MojTestAssert(watcher4->m_count == 1); return MojErrNone; } MojErr MojDbWatchTest::limitTest(MojDb& db) { return MojErrNone; } MojErr MojDbWatchTest::put(MojDb& db, const MojObject& fooVal, const MojObject& barVal, MojObject& idOut, MojInt64& revOut) { MojObject obj; MojErr err = obj.putString(_T("_kind"), _T("WatchTest:1")); MojTestErrCheck(err); err = obj.put(_T("foo"), fooVal); MojTestErrCheck(err); err = obj.put(_T("bar"), barVal); MojTestErrCheck(err); err = db.put(obj); MojTestErrCheck(err); err = obj.getRequired(MojDb::IdKey, idOut); MojTestErrCheck(err); err = obj.getRequired(MojDb::RevKey, revOut); MojTestErrCheck(err); return MojErrNone; } MojErr MojDbWatchTest::merge(MojDb& db, const MojObject& id, const MojObject& barVal) { MojObject obj; MojErr err = obj.put(MojDb::IdKey, id); MojTestErrCheck(err); err = obj.put(_T("bar"), barVal); MojTestErrCheck(err); err = db.merge(obj); MojTestErrCheck(err); return MojErrNone; } void MojDbWatchTest::cleanup() { (void) MojRmDirRecursive(MojDbTestDir); }
82384da602c33f3b767558efa816c3fc7013608b
cc5af2031b84e22243cf3f8c3bd4463fe3897bd3
/touch_display/F4_GFX/Middlewares/ST/touchgfx/framework/include/touchgfx/widgets/PixelDataWidget.hpp
1f38d5dcea6a35bc24cbe01171f620f490cf889c
[]
no_license
nikaw525/SWAW_UltrasonicWaterMeasurement
2b0a1e87699e56153bfd5ebd8f19fa472c9ff52a
71c5c31f6a63b1a6caabe96648fdec507f049c33
refs/heads/main
2023-06-01T09:57:39.437031
2021-06-08T16:49:07
2021-06-08T16:49:07
348,816,725
1
2
null
2021-06-03T11:59:37
2021-03-17T18:44:45
C
UTF-8
C++
false
false
2,649
hpp
/** ****************************************************************************** * This file is part of the TouchGFX 4.14.0 distribution. * * <h2><center>&copy; Copyright (c) 2020 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ /** * @file touchgfx/widgets/PixelDataWidget.hpp * * Declares the touchgfx::PixelDataWidget class. */ #ifndef PIXELDATAWIDGET_HPP #define PIXELDATAWIDGET_HPP #include <touchgfx/Bitmap.hpp> #include <touchgfx/hal/Types.hpp> #include <touchgfx/widgets/Widget.hpp> namespace touchgfx { /** * A widget for displaying a buffer of pixel data. This can also be though of as a dynamic * bitmap where the dimensions of the bitmap is the same as the dimensions of the widget * and the actual bitmap data can be set and updated dynamically. The size of the buffer * must match the number of bytes required for the widget calculated as WIDTH x HEIGHT x * BYTES_PER_PIXEL. If the LCD is 16 bit per pixel the buffer must hold 2 bytes for each * pixel. If the LCD is 24 bit the buffer must hold 3 bytes for each pixel. */ class PixelDataWidget : public Widget { public: PixelDataWidget(); virtual void draw(const Rect& invalidatedArea) const; virtual Rect getSolidRect() const; /** * Set the pixel data to display. The given pointer must contain WIDTH x HEIGHT x * BYTES_PER_PIXEL bytes of addressable image data. * * @param [in] data Image data. * * @see setBitmapFormat */ void setPixelData(uint8_t* const data); /** * Set the format of the pixel data. The supported formats depend on the display type. * For example grayscale displays do not support color images. * * @param format Describes the format to use when reading the pixel data. */ void setBitmapFormat(Bitmap::BitmapFormat format); /** * @copydoc Image::setAlpha */ void setAlpha(uint8_t newAlpha); /** * @copydoc Image::getAlpha */ uint8_t getAlpha() const; protected: uint8_t* buffer; ///< The buffer where the pixels are copied from Bitmap::BitmapFormat format; ///< The pixel format for the data. uint8_t alpha; ///< The Alpha for this widget. }; } // namespace touchgfx #endif // PIXELDATAWIDGET_HPP
856c3f5dfd34ce23828c2c8b4de4993a6a727b74
a72d9357c5b43c5ae6b5b82ca16d548ac1fdd853
/examples/chapter04_04/src/util/utility/util_swdm.h
bce7da4c1dfcb1bac1164e49de58db86dea88060
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0", "LGPL-3.0-only" ]
permissive
ckormanyos/real-time-cpp
d61e90e79b47d41349ba4f34633a14ea35f36d70
1741e058cac3b0e865602be5f747d1fe828b7f6f
refs/heads/master
2023-08-29T02:58:32.175068
2023-08-28T11:48:04
2023-08-28T11:48:04
5,922,310
484
160
BSL-1.0
2023-08-28T11:48:05
2012-09-23T13:31:08
C++
UTF-8
C++
false
false
22,502
h
/////////////////////////////////////////////////////////////////////////////// // \author (c) Marco Paland ([email protected]) // 2014-2016, PALANDesign Hannover, Germany // // \license The MIT License (MIT) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // // \brief Single Wire Debug Monitor // This class is the single wire debug monitor, which allows easy inspecting and // manipulating (setting) memory / variable data over a single wire/pin in embedded systems. // NO DEPENDENCIES! NO UART! NO REQUIREMENTS! Just a 1 ms periodic tick is needed. That's all. // // SWDM uses a simple request/response protocol where the tester/PC is always the // master generating the request and the device/board is the slave sending the response. // The class below implements the SWDM slave. // // SWDM uses a service tick of 1ms, one bit is oversampled 4 times, which results // in a baudrate of 250 bit/sec, every byte has a low start bit, a high stop bit and // 8 data bits (LSB first). So a normal UART with 250 baud 8N1 can be used on the PC master side // for transmission / reception. // The line is used in half duplex bidirectional mode. It is high for idle / recessive levels // and low when active / dominant. // Use a resistor pulled-up open collector pin on the board site or set the pin as input // on a high level in your custom set_line() function. // // Protocol: // // request: | 0x55 | mode | address | data | crc | // // 0x55 (1 byte) : // Request sync byte // // mode (1 byte) : // bit 0-3 : data length, 0: 1 byte, 2: 3 bytes ... 15: 16 bytes // bit 4-5 : addr length, 0: 2 byte, 1: 3 byte, 2: 4 byte, 3: 8 byte // bit 6 : 0: byte access, 1: type access valid for uint8, uint16, uint32 and uint64 data length // bit 7 : 0: read data command, 1: write data command // // address (2 - 8 bytes) : // Big-endian order, MSB - the most significant address byte is sent first // // data (0 - 16 bytes) : // On read command, no data byte is transmitted, data field is skipped // Byte access: The byte of the specified address is send first, ascending address order byte by byte // Type access: MSB first, valid are 1,2,4 and 8 data bytes, the most significant data byte is sent first // // crc (1 byte) : // One byte CRC, using CRC-8 (ITU-T), x^8 + x^2 + x + 1 polynomial // CRC is build over mode, address and data bytes // // // response: | 0xAA | data | crc | // // 0xAA (1 byte) : // Response sync byte // // data (0 - 16 bytes) // Requested data bytes of read command // On write command no data is sent, the answer is | 0xAA | 0x00 | // Byte access: The byte of the specified address is send first, ascending address order byte by byte // Type access: MSB first, valid are 1, 2, 4 and 8 bytes, the most significant data byte is sent first // // crc (1 byte) : // One byte CRC, using CRC-8 (ITU-T), x^8 + x^2 + x + 1 polynomial // CRC is built over data bytes, in case of a write command, crc is 0x00 // // // Usage: // // #include "swdm.h" // // Define (implement) the two low level line/pin access routines in your system // or derive your own my_swdm class from swdm and define your access functions there. // // bool swdm::get_line() const // { // return the value of the according swdm interface line/pin // } // // void swdm::set_line(bool value) const // { // set the state of the according swdm line/pin to value (true = high/idle, false = low) // if you don't use an open collector driver, you MUST config the pin as input for high/idle levels // and before setting the line to false/low it must be configured as an output. // } // // Create a singleton instance of swdm: // // static swdm& get_swdm() // { // static swdm _swdm; // return _swdm; // } // // And call the swdm service routine with a rate of 1000 Hz: // // void system_tick_1ms() // { // get_swdm().service(); // } // // // \version // 2014-09-17 0.10 Initial version, ideas // 2014-09-23 0.80 Alpha version // 2015-02-05 0.90 Beta version, code clean up // 2015-02-25 0.91 Minor bug fixes, cleanup, more docu // 2016-04-13 0.92 Bug fixes and tests by B. Hempelmann and C. Kormanyos // 2016-04-17 1.00 Minor cleanups, first released version // /////////////////////////////////////////////////////////////////////////////// #ifndef UTIL_SWDM_2016_04_11_H_ #define UTIL_SWDM_2016_04_11_H_ #include <cstdint> #include <mcal_debug_monitor.h> #include <util/utility/util_noncopyable.h> // Defines the oversampling rate // The effective baud rate is the service_tick_rate / SWD_OVERSAMPLING_COUNT // For a service_tick_rate of 1 ms, the baud rate is 250 for 4 times oversampling #define SWDM_SAMPLE_PERIOD UINT8_C(4) // Defines the position where the bit is detected as a constant valid bit. // Should be at 50 to 75% of the SAMPLE period, 0 is the first sample position #define SWDM_SAMPLE_VALID_POS UINT8_C(2) // Defines the number of consecutive high samples to detect a line idle condition #define SWDM_SAMPLE_IDLE_COUNT UINT8_C(40) // Define this switch for 64 bit address support. If undefined, up to 32 bit addresses are supported // #define SWDM_64_BIT_ADDRESS_SUPPORT namespace util { class swdm : private util::noncopyable { public: // default ctor swdm() : uart_state_ (rx_start_bit), prot_state_ (rx_sync), bit_detect_last_state_ (true), bit_detect_sample_count_(UINT8_C(0)), bit_detect_idle_count_ (UINT8_C(0)) { // set pin to idle / recessive value set_line(true); } // Service routine, MUST be called periodically with 1000 Hz (1 ms) void service() { if( (uart_state_ == tx_data_bits) || (uart_state_ == tx_start_bit) || (uart_state_ == tx_stop_bit)) { // transmission if(bit_detect_sample_count_ == UINT8_C(0)) { // bit period done uart(true); } } else { // reception bool line = get_line(); // sync is done on every level change if(line != bit_detect_last_state_) { // line level has changed, new bit cell started bit_detect_last_state_ = line; bit_detect_sample_count_ = UINT8_C(0); } else { // no level change if((bit_detect_sample_count_ == SWDM_SAMPLE_VALID_POS) && (bit_detect_idle_count_ < SWDM_SAMPLE_IDLE_COUNT)) { // valid bit detected uart(line); } // idle detection bit_detect_idle_count_ = (line ? (bit_detect_idle_count_ + UINT8_C(1)) : UINT8_C(0)); if(bit_detect_idle_count_ >= SWDM_SAMPLE_IDLE_COUNT) { // line is idle, reset uart bit_detect_idle_count_ = SWDM_SAMPLE_IDLE_COUNT; uart_state_ = rx_start_bit; } } } if(++bit_detect_sample_count_ == SWDM_SAMPLE_PERIOD) { bit_detect_sample_count_ = UINT8_C(0); } } protected: // Line (pin) access function to get the actual line / pin state // This function MUST be defined somewhere in your project or in your derived class // \return The actual state of the swdm line / pin: true = high (idle/recessive), false = low (active/dominant) virtual bool get_line() const { return mcal::debug::debug_monitor_port_type::read_input_value(); } // Line (pin) access function to set the actual line / pin state // This function MUST be defined somewhere in your project // \param value The new state of the swdm line / pin: true = high (idle/recessive), false = low (active/dominant) virtual void set_line(const bool value) const { if(value) { mcal::debug::debug_monitor_port_type::set_direction_input(); } else { mcal::debug::debug_monitor_port_type::set_direction_output(); mcal::debug::debug_monitor_port_type::set_pin_low(); } } private: // Software UART, called by the service routine, when a valid bit is received or when a bit should be transmitted // \param bit The value of the received bit void uart(const bool bit) { switch(uart_state_) { case rx_start_bit: if((!bit)) { // start bit detected uart_data_bit_count_ = UINT8_C(0); uart_state_ = rx_data_bits; } break; case rx_data_bits: // LSB is transmitted first uart_buffer_ = static_cast<std::uint8_t>(std::uint_fast8_t(uart_buffer_ >> UINT8_C(1)) | std::uint_fast8_t(bit ? UINT8_C(0x80) : UINT8_C(0x00))); if(++uart_data_bit_count_ >= UINT8_C(8)) { uart_state_ = rx_stop_bit; } break; case rx_stop_bit: uart_state_ = rx_start_bit; if(bit) { // valid byte received, if no stop bit is detected, it's a framing error, discard data uart_rx_full(uart_buffer_); } else { // framing error, discard data prot_state_ = rx_sync; // reset the protocol state, because a byte error decays the whole command } break; case tx_start_bit: // send start bit set_line(false); uart_data_bit_count_ = UINT8_C(0); uart_state_ = tx_data_bits; break; case tx_data_bits: // send data bits, LSB is first set_line((uart_buffer_ & UINT8_C(0x01)) != UINT8_C(0)); uart_buffer_ >>= UINT8_C(1); if(++uart_data_bit_count_ >= UINT8_C(8)) { uart_state_ = tx_stop_bit; } break; case tx_stop_bit: // send stop bit set_line(true); uart_state_ = rx_start_bit; // byte transmission complete, inform protocol (transmitter empty) uart_tx_empty(); break; default: break; } } // UART transmit function // \param data The character to send void uart_send(const std::uint_fast8_t data) { uart_buffer_ = std::uint8_t(data); uart_state_ = tx_start_bit; } // This function is called by the (software) UART when the receiver is full // \param data The received character void uart_rx_full(const std::uint_fast8_t data) { switch(prot_state_) { case rx_sync: if(data == request_sync_field) { prot_state_ = rx_mode; } break; case rx_mode: prot_mode_ = data; prot_idx_ = UINT8_C(0); prot_crc_ = UINT8_C(0); prot_state_ = rx_addr; crc8(data); break; case rx_addr: { prot_addr_[prot_idx_++] = data; crc8(data); const std::uint_fast8_t addr_width = (prot_mode_ & UINT8_C(0x30)) >> UINT8_C(4); if( ((addr_width == UINT8_C(0)) && (prot_idx_ == UINT8_C(2))) // 16 bit address || ((addr_width == UINT8_C(1)) && (prot_idx_ == UINT8_C(3))) // 24 bit address || ((addr_width == UINT8_C(2)) && (prot_idx_ == UINT8_C(4))) // 32 bit address #if defined(SWDM_64_BIT_ADDRESS_SUPPORT) || ((addr_width == UINT8_C(3)) && (prot_idx_ == UINT8_C(8))) // 64 bit address #endif ) { prot_idx_ = UINT8_C(0); prot_state_ = (((prot_mode_ & UINT8_C(0x80)) != UINT8_C(0))? rx_data : rx_crc); } break; } case rx_data: prot_data_[prot_idx_++] = data; crc8(data); if(prot_idx_ > (prot_mode_ & UINT8_C(0x0F))) { prot_state_ = rx_crc; } break; case rx_crc: if(data == prot_crc_) { // CRC correct - execute request request(); // send response prot_state_ = tx_sync; // start the transmission uart_tx_empty(); } else { // CRC error - discard command, wait for next rx sync byte prot_state_ = rx_sync; } break; default: prot_state_ = rx_sync; break; case tx_sync: case tx_data: case tx_crc: break; } } // This function is called by the (software) UART when the transmitter is empty void uart_tx_empty() { switch(prot_state_) { case tx_sync: prot_idx_ = UINT8_C(0); prot_crc_ = UINT8_C(0); prot_state_ = (((prot_mode_ & UINT8_C(0x80)) != UINT8_C(0)) ? tx_crc : tx_data); // skip data on write command uart_send(response_sync_field); break; case tx_data: uart_send(prot_data_[prot_idx_]); crc8(prot_data_[prot_idx_]); if(++prot_idx_ >= ((prot_mode_ & UINT8_C(0x0F)) + UINT8_C(1))) { prot_state_ = tx_crc; } break; case tx_crc: uart_send(prot_crc_); prot_state_ = rx_sync; break; default: prot_state_ = rx_sync; break; case rx_sync: case rx_mode: case rx_addr: case rx_data: case rx_crc: break; } } // Process and execute the received request void request() { // get address width std::uint_fast8_t addr_width; switch((prot_mode_ & UINT32_C(0x30)) >> UINT8_C(4)) { case UINT8_C(0): addr_width = UINT8_C(2); break; // 16 bit address case UINT8_C(1): addr_width = UINT8_C(3); break; // 24 bit address default : case UINT8_C(2): addr_width = UINT8_C(4); break; // 32 bit address #if defined(SWDM_64_BIT_ADDRESS_SUPPORT) case UINT8_C(3): addr_width = UINT8_C(8); break; // 64 bit address #endif } #if defined(SWDM_64_BIT_ADDRESS_SUPPORT) std::uint64_t addr = UINT64_C(0); #else std::uint32_t addr = UINT32_C(0); #endif // assemble address for(std::uint_fast8_t i = UINT8_C(0); i < addr_width; ++i) { addr <<= UINT8_C(8); addr |= prot_addr_[i]; } // data length const std::uint_fast8_t data_length = (prot_mode_ & UINT8_C(0x0F)) + UINT8_C(1); if((prot_mode_ & UINT8_C(0x80)) != UINT8_C(0)) { // write command if(prot_mode_ & UINT8_C(0x40)) { // write type access switch(data_length) { case 1U: *reinterpret_cast<volatile std::uint8_t*>(addr) = prot_data_[0U]; break; case 2U: { const std::uint16_t value = (static_cast<std::uint16_t>(prot_data_[0U]) << UINT8_C(8)) | (static_cast<std::uint16_t>(prot_data_[1U])); *reinterpret_cast<volatile std::uint16_t*>(addr) = value; break; } case 4U: { const std::uint32_t value = (static_cast<std::uint32_t>(prot_data_[0U]) << UINT8_C(24)) | (static_cast<std::uint32_t>(prot_data_[1U]) << UINT8_C(16)) | (static_cast<std::uint32_t>(prot_data_[2U]) << UINT8_C( 8)) | (static_cast<std::uint32_t>(prot_data_[3U])); *reinterpret_cast<volatile std::uint32_t*>(addr) = value; break; } case 8U: { const std::uint64_t value = (static_cast<std::uint64_t>(prot_data_[0U]) << UINT8_C(56)) | (static_cast<std::uint64_t>(prot_data_[1U]) << UINT8_C(48)) | (static_cast<std::uint64_t>(prot_data_[2U]) << UINT8_C(40)) | (static_cast<std::uint64_t>(prot_data_[3U]) << UINT8_C(32)) | (static_cast<std::uint64_t>(prot_data_[4U]) << UINT8_C(24)) | (static_cast<std::uint64_t>(prot_data_[5U]) << UINT8_C(16)) | (static_cast<std::uint64_t>(prot_data_[6U]) << UINT8_C( 8)) | (static_cast<std::uint64_t>(prot_data_[7U])); *reinterpret_cast<volatile std::uint64_t*>(addr) = value; break; } default: // invalid data type, use byte access for(std::uint_fast8_t i = UINT8_C(0); i < data_length; i++) { *reinterpret_cast<volatile std::uint8_t*>(addr++) = prot_data_[i]; } break; } } else { // write byte access for(std::uint_fast8_t i = UINT8_C(0); i < data_length; i++) { *reinterpret_cast<volatile std::uint8_t*>(addr++) = prot_data_[i]; } } } else { // read command if((prot_mode_ & UINT8_C(0x40)) != UINT8_C(0)) { // read type access switch(data_length) { case UINT8_C(1): prot_data_[0U] = *reinterpret_cast<volatile std::uint8_t*>(addr); break; case UINT8_C(2): { std::uint16_t value = *reinterpret_cast<volatile std::uint16_t*>(addr); for(std::int_fast8_t tries = UINT8_C(4); --tries && (value != *reinterpret_cast<volatile std::uint16_t*>(addr)); value = *reinterpret_cast<volatile std::uint16_t*>(addr)) { ; } prot_data_[0U] = byte_part<std::uint16_t, 1U>(value); // MSB prot_data_[1U] = byte_part<std::uint16_t, 0U>(value); // LSB break; } case UINT8_C(4): { std::uint32_t value = *reinterpret_cast<volatile std::uint32_t*>(addr); for(std::int_fast8_t tries = UINT8_C(4); --tries && (value != *reinterpret_cast<volatile std::uint32_t*>(addr)); value = *reinterpret_cast<volatile std::uint32_t*>(addr)) { ; } prot_data_[0U] = byte_part<std::uint32_t, 3U>(value); // MSB prot_data_[1U] = byte_part<std::uint32_t, 2U>(value); prot_data_[2U] = byte_part<std::uint32_t, 1U>(value); prot_data_[3U] = byte_part<std::uint32_t, 0U>(value); // LSB break; } case UINT8_C(8): { std::uint64_t value = *reinterpret_cast<volatile std::uint64_t*>(addr); for(std::int_fast8_t tries = UINT8_C(4); --tries && (value != *reinterpret_cast<volatile std::uint64_t*>(addr)); value = *reinterpret_cast<volatile std::uint64_t*>(addr)) { ; } prot_data_[0U] = byte_part<std::uint64_t, 7U>(value); // MSB prot_data_[1U] = byte_part<std::uint64_t, 6U>(value); prot_data_[2U] = byte_part<std::uint64_t, 5U>(value); prot_data_[3U] = byte_part<std::uint64_t, 4U>(value); prot_data_[4U] = byte_part<std::uint64_t, 3U>(value); prot_data_[5U] = byte_part<std::uint64_t, 2U>(value); prot_data_[6U] = byte_part<std::uint64_t, 1U>(value); prot_data_[7U] = byte_part<std::uint64_t, 0U>(value); // LSB break; } default: // invalid data type, use byte access for(std::uint_fast8_t i = UINT8_C(0); i < data_length; i++) { prot_data_[i] = *reinterpret_cast<volatile std::uint8_t*>(addr++); } break; } } else { // read byte access for(std::uint_fast8_t i = UINT8_C(0); i < data_length; i++) { prot_data_[i] = *reinterpret_cast<volatile std::uint8_t*>(addr++); } } } } //////////////////////////////////////////////////////////////////////// // H E L P E R F U N C T I O N S // CRC-8 algorithm, using x^8 + x^2 + x + 1 polynomial // Process data, CRC result is in prot_crc_ // We use a shifter here instead of a table lookup to save code size, speed // is not so important at the swdm baudrate of 250 baud. // \param data Data to process void crc8(std::uint_fast8_t data) { for(std::uint_fast8_t i = UINT8_C(8); i; i--) { const std::uint_fast8_t sum = (prot_crc_ ^ data) & UINT8_C(0x01); prot_crc_ >>= UINT8_C(1); if(sum != UINT8_C(0)) { prot_crc_ ^= UINT8_C(0x8C); } data >>= UINT8_C(1); } } // Return the according byte of the given position // \param Long Type of the value // \param Position Byte position to return, 0 is LSB // \param value The Long value // \return The byte of the Long value at the given position template<typename LongType, const std::uint_fast8_t Position> std::uint8_t byte_part(const LongType& value) const { return static_cast<std::uint8_t>(value >> (Position * UINT8_C(8))); } private: static const std::uint_fast8_t request_sync_field = UINT8_C(0x55); // Request sync field static const std::uint_fast8_t response_sync_field = UINT8_C(0xAA); // Response sync field typedef enum enum_state_type { rx_start_bit, rx_data_bits, rx_stop_bit, tx_start_bit, tx_data_bits, tx_stop_bit } state_type; typedef enum enum_prot_state_type { rx_sync, rx_mode, rx_addr, rx_data, rx_crc, tx_sync, tx_data, tx_crc } prot_state_type; state_type uart_state_; std::uint_fast8_t uart_buffer_; std::uint_fast8_t uart_data_bit_count_; prot_state_type prot_state_; std::uint_fast8_t prot_mode_; std::uint8_t prot_addr_[ 8U]; std::uint8_t prot_data_[16U]; std::uint_fast8_t prot_crc_; std::uint_fast8_t prot_idx_; bool bit_detect_last_state_; std::uint_fast8_t bit_detect_sample_count_; std::uint_fast8_t bit_detect_idle_count_; }; } // namespace util #endif // UTIL_SWDM_2016_04_11_H_
d548a9dcf86f3fc6bbb82ff54c891399d5ac1bc7
cc1da8fed3fec51f6da3b1ae3314ff63a3da2443
/WeeklyContest-177/ValidateBT.cpp
d93da5cddbe9ddf8c1d633b543a0404d65480490
[]
no_license
Ashenn1/LeetCode-Contests
16d8d9c618417be010588a5dbcdb8d27ba93defe
b17b991e436062e08f18ac74af60e084a3dba4cd
refs/heads/master
2022-04-09T22:28:42.885017
2020-03-24T12:45:32
2020-03-24T12:45:32
242,691,671
0
0
null
null
null
null
UTF-8
C++
false
false
1,256
cpp
class Solution { public: int countNodes(vector<int> &l , vector<int> &r , int root){ if(root == -1) return 0; return 1+countNodes(l , r, l[root]) + countNodes(l , r, r[root]); } bool validateBinaryTreeNodes(int n, vector<int>& leftChild, vector<int>& rightChild) { vector<int> in_degree(n , 0); int root = -1; // Loop to count in-degrees for every node for(int i = 0; i< leftChild.size() ; i++){ if(leftChild[i] != -1 && ++in_degree[leftChild[i]] > 1) // if in-degree of a node exceeds 1 then return false return false; if(rightChild[i] != -1 && ++in_degree[rightChild[i]] > 1) return false; } // Loop to find the root of the tree for(int i = 0; i< leftChild.size(); i++){ if(in_degree[i] == 0) { if(root == -1) root = i; else return false; // Bec there exists more than one root! } } if( root == -1) return false; return (countNodes(leftChild , rightChild , root) == n); } };
8bb32fa76a8dee17d745f8e2fab9b54233654ac6
4bd5b7e2cc6fb511a0621c7d83a9f18a3b37432f
/bin/src/src/compiler/signals/ExitCodeSignal.cpp
062caf67816562532c5e735640f2b294d12b26ac
[]
no_license
billy-yoyo/Watermelon
9db4c2ab60e37b5a28f88d7e9a5604cdbc72abb6
600cd3230f1eac391861fe4d74d13716c6083676
refs/heads/master
2020-04-03T10:04:59.846657
2017-06-30T21:23:51
2017-06-30T21:23:51
95,490,804
0
0
null
null
null
null
UTF-8
C++
false
true
3,803
cpp
// Generated by Haxe 3.4.2 (git build master @ 890f8c7) #include <hxcpp.h> #ifndef INCLUDED_src_compiler_signals_ExitCodeSignal #include <src/compiler/signals/ExitCodeSignal.h> #endif #ifndef INCLUDED_src_compiler_signals_ExitSignal #include <src/compiler/signals/ExitSignal.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_fdb48758c82321f1_11_new,"src.compiler.signals.ExitCodeSignal","new",0xcbc3802d,"src.compiler.signals.ExitCodeSignal.new","src/compiler/signals/ExitCodeSignal.hx",11,0x84a61ee2) HX_LOCAL_STACK_FRAME(_hx_pos_fdb48758c82321f1_16_getName,"src.compiler.signals.ExitCodeSignal","getName",0xf31a3c4e,"src.compiler.signals.ExitCodeSignal.getName","src/compiler/signals/ExitCodeSignal.hx",16,0x84a61ee2) namespace src{ namespace compiler{ namespace signals{ void ExitCodeSignal_obj::__construct(){ HX_STACKFRAME(&_hx_pos_fdb48758c82321f1_11_new) HXDLIN( 11) super::__construct(HX_("",00,00,00,00)); } Dynamic ExitCodeSignal_obj::__CreateEmpty() { return new ExitCodeSignal_obj; } void *ExitCodeSignal_obj::_hx_vtable = 0; Dynamic ExitCodeSignal_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< ExitCodeSignal_obj > _hx_result = new ExitCodeSignal_obj(); _hx_result->__construct(); return _hx_result; } bool ExitCodeSignal_obj::_hx_isInstanceOf(int inClassId) { if (inClassId<=(int)0x1f7d2c12) { return inClassId==(int)0x00000001 || inClassId==(int)0x1f7d2c12; } else { return inClassId==(int)0x2d3d9abb; } } ::String ExitCodeSignal_obj::getName(){ HX_STACKFRAME(&_hx_pos_fdb48758c82321f1_16_getName) HXDLIN( 16) return HX_("ExitCodeSignal",53,d4,2f,fa); } ExitCodeSignal_obj::ExitCodeSignal_obj() { } hx::Val ExitCodeSignal_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 7: if (HX_FIELD_EQ(inName,"getName") ) { return hx::Val( getName_dyn() ); } } return super::__Field(inName,inCallProp); } #if HXCPP_SCRIPTABLE static hx::StorageInfo *ExitCodeSignal_obj_sMemberStorageInfo = 0; static hx::StaticInfo *ExitCodeSignal_obj_sStaticStorageInfo = 0; #endif static ::String ExitCodeSignal_obj_sMemberFields[] = { HX_HCSTRING("getName","\x01","\x22","\x82","\x1b"), ::String(null()) }; static void ExitCodeSignal_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(ExitCodeSignal_obj::__mClass,"__mClass"); }; #ifdef HXCPP_VISIT_ALLOCS static void ExitCodeSignal_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(ExitCodeSignal_obj::__mClass,"__mClass"); }; #endif hx::Class ExitCodeSignal_obj::__mClass; void ExitCodeSignal_obj::__register() { hx::Object *dummy = new ExitCodeSignal_obj; ExitCodeSignal_obj::_hx_vtable = *(void **)dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_HCSTRING("src.compiler.signals.ExitCodeSignal","\xbb","\xe5","\x42","\x75"); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mMarkFunc = ExitCodeSignal_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = hx::Class_obj::dupFunctions(ExitCodeSignal_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< ExitCodeSignal_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = ExitCodeSignal_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = ExitCodeSignal_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = ExitCodeSignal_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace src } // end namespace compiler } // end namespace signals
4148a1a99d306cb582b375fcb73c61021e41f1fc
d55755141c0e12552562cca50837020e73737ac7
/source/autumn-recruitment/53. Maximum Subarray.cpp
43d680e044f8ce49bac5b600b6fc7ff269944e33
[]
no_license
xulzee/LeetCodeProjectCPP
5452e218b57b5bf28117cab98b163f07bcce7329
129bea6296560676eca4fa9b20fe83dc935a3b92
refs/heads/master
2020-06-26T00:09:27.612312
2020-03-22T09:06:54
2020-03-22T09:06:54
199,463,509
4
1
null
null
null
null
UTF-8
C++
false
false
1,248
cpp
// // Created by liuze.xlz on 2019-08-06. // #include "utils.h" #include <tuple> class Solution { public: int maxSubArray(vector<int> &nums) { if (nums.empty()) { return 0; } int res = nums.front(); int sum = 0; for (auto &num : nums) { if (sum > 0) { sum += num; } else { sum = num; } res = max(res, sum); } return res; } int maxSubArrayWithIndex(vector<int> &nums) { if (nums.empty()) { return 0; } tuple<int, int, int> res = {nums[0], 0, 0}; // num, start, end int start = 0; int end = 0; int sum = 0; for (int i = 0; i < nums.size(); ++i) { if (sum > 0) { sum += nums[i]; ++end; } else { sum = nums[i]; start = i; end = i; } if (sum > get<0>(res)) { res = make_tuple(sum, start, end); } } return get<0>(res); } }; int main() { vector<int> nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4}; cout << Solution().maxSubArray(nums) << endl; }
e1195891ce83c64fc672588e926740b65f683573
610420c2ea69961aafe4852e8b4ce925673ff17a
/arduino/opencr_fw/opencr_fw_arduino/src/arduino/libraries/turtlebot3_ros_lib/std_msgs/Int8MultiArray.h
f84169a3294877392389376d62c726a913ab574a
[ "Apache-2.0" ]
permissive
ipa320/OpenCR
6d81cdf2a6cb683940c4c24ccb7af7ae26306419
09bf34f5f9ebc1253e03ac789cf820dcc46eb99d
refs/heads/master
2021-04-28T11:02:04.035274
2018-01-29T00:30:04
2018-01-29T00:30:04
122,081,159
0
2
Apache-2.0
2020-01-22T16:06:43
2018-02-19T15:23:27
C
UTF-8
C++
false
false
2,452
h
#ifndef _ROS_std_msgs_Int8MultiArray_h #define _ROS_std_msgs_Int8MultiArray_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" #include "std_msgs/MultiArrayLayout.h" namespace std_msgs { class Int8MultiArray : public ros::Msg { public: std_msgs::MultiArrayLayout layout; uint32_t data_length; int8_t st_data; int8_t * data; Int8MultiArray(): layout(), data_length(0), data(NULL) { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; offset += this->layout.serialize(outbuffer + offset); *(outbuffer + offset + 0) = (this->data_length >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (this->data_length >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (this->data_length >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (this->data_length >> (8 * 3)) & 0xFF; offset += sizeof(this->data_length); for( uint32_t i = 0; i < data_length; i++){ union { int8_t real; uint8_t base; } u_datai; u_datai.real = this->data[i]; *(outbuffer + offset + 0) = (u_datai.base >> (8 * 0)) & 0xFF; offset += sizeof(this->data[i]); } return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; offset += this->layout.deserialize(inbuffer + offset); uint32_t data_lengthT = ((uint32_t) (*(inbuffer + offset))); data_lengthT |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); data_lengthT |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); data_lengthT |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); offset += sizeof(this->data_length); if(data_lengthT > data_length) this->data = (int8_t*)realloc(this->data, data_lengthT * sizeof(int8_t)); data_length = data_lengthT; for( uint32_t i = 0; i < data_length; i++){ union { int8_t real; uint8_t base; } u_st_data; u_st_data.base = 0; u_st_data.base |= ((uint8_t) (*(inbuffer + offset + 0))) << (8 * 0); this->st_data = u_st_data.real; offset += sizeof(this->st_data); memcpy( &(this->data[i]), &(this->st_data), sizeof(int8_t)); } return offset; } const char * getType(){ return "std_msgs/Int8MultiArray"; }; const char * getMD5(){ return "d7c1af35a1b4781bbe79e03dd94b7c13"; }; }; } #endif
5179a5b1ead55af17eb2cc2cebd91ec6c0e42765
aade1e73011f72554e3bd7f13b6934386daf5313
/Contest/Opencup/XVIII/Urals/K.cpp
a8b19b55e04e75fa243c603b5176bf2e9ac6415b
[]
no_license
edisonhello/waynedisonitau123
3a57bc595cb6a17fc37154ed0ec246b145ab8b32
48658467ae94e60ef36cab51a36d784c4144b565
refs/heads/master
2022-09-21T04:24:11.154204
2022-09-18T15:23:47
2022-09-18T15:23:47
101,478,520
34
6
null
null
null
null
UTF-8
C++
false
false
4,184
cpp
#include <bits/stdc++.h> using namespace std; int main() { int n, m; cin >> n >> m; vector<string> s(n); for (int i = 0; i < n; ++i) { cin >> s[i]; } vector<vector<int>> dist(n * m, vector<int>(n * m, 200)); vector<vector<tuple<int, int, int>>> from(n * m, vector<tuple<int, int, int>>(n * m)); constexpr int dx[4] = {1, 0, -1, 0}; constexpr int dy[4] = {0, 1, 0, -1}; constexpr char kChar[4] = {'D', 'R', 'U', 'L'}; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (s[i][j] != '#') { dist[i * m + j][i * m + j] = 0; for (int k = 0; k < 4; ++k) { if (i + dx[k] < 0 || i + dx[k] >= n) continue; if (j + dy[k] < 0 || j + dy[k] >= m) continue; if (s[i + dx[k]][j + dy[k]] == '#') continue; dist[i * m + j][(i + dx[k]) * m + (j + dy[k])] = 1; from[i * m + j][(i + dx[k]) * m + (j + dy[k])] = make_tuple(-1, -1, k); } } } } vector<vector<pair<int, int>>> que(100); for (int i = 0; i < n * m; ++i) { for (int j = 0; j < n * m; ++j) { if (dist[i][j] == 200) continue; que[dist[i][j]].emplace_back(i, j); } } vector<vector<bool>> vis(n * m, vector<bool>(n * m)); for (int i = 0; i < 100; ++i) { for (auto g : que[i]) { int u = g.first, v = g.second; if (vis[u][v]) continue; vis[u][v] = true; int x1 = u / m, y1 = u % m; int x2 = v / m, y2 = v % m; for (int k = 0; k < 4; ++k) { if (x1 + dx[k] < 0 || x1 + dx[k] >= n) continue; if (y1 + dy[k] < 0 || y1 + dy[k] >= m) continue; if (x2 + dx[2 ^ k] < 0 || x2 + dx[2 ^ k] >= n) continue; if (y2 + dy[2 ^ k] < 0 || y2 + dy[2 ^ k] >= m) continue; if (s[x1 + dx[k]][y1 + dy[k]] == '#') continue; if (s[x2 + dx[2 ^ k]][y2 + dy[2 ^ k]] == '#') continue; int uu = (x1 + dx[k]) * m + (y1 + dy[k]); int vv = (x2 + dx[2 ^ k]) * m + (y2 + dy[2 ^ k]); if (dist[uu][vv] > dist[u][v] + 2) { dist[uu][vv] = dist[u][v] + 2; from[uu][vv] = make_tuple(u, v, k); if (dist[uu][vv] < 100) { que[dist[uu][vv]].emplace_back(uu, vv); } } } } } vector<vector<int>> g(n * m); for (int i = 0; i < n * m; ++i) { for (int j = 0; j < n * m; ++j) { assert(dist[i][j] == dist[j][i]); if (dist[i][j] <= 100) g[i].push_back(j); } } int st = -1, ed = -1; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (s[i][j] == 'S') { st = i * m + j; } if (s[i][j] == 'F') { ed = i * m + j; } } } assert(st != -1 && ed != -1); vector<int> qu(1, st); vector<int> ds(n * m, -1); vector<int> fr(n * m, -1); ds[st] = 0; for (int it = 0; it < qu.size(); ++it) { int x = qu[it]; for (int u : g[x]) { if (ds[u] == -1) { ds[u] = ds[x] + 1; fr[u] = x; qu.push_back(u); } } } cout << ds[ed] << "\n"; if (ds[ed] == -1) return 0; auto Path = [&](int x, int y) { string res = ""; while (dist[x][y] > 1) { int a = get<0>(from[x][y]); int b = get<1>(from[x][y]); int c = get<2>(from[x][y]); res += kChar[c ^ 2]; x = a; y = b; } string rev = res; reverse(rev.begin(), rev.end()); if (dist[x][y] == 0) return res + rev; return res + kChar[get<2>(from[x][y])] + rev; }; vector<string> ans; for (int x = ed; x != st; x = fr[x]) { ans.push_back(Path(fr[x], x)); } reverse(ans.begin(), ans.end()); for (auto &s : ans) cout << s << "\n"; return 0; }
0fc8271d5db5c6e9dba9e795ca64a24aa2b4fa9a
87117ee5b9410737995285d1485c2dffa2ea6dd0
/cheetahwutiOSController/boost.framework/Headers/mpl/set/aux_/iterator.hpp
48a070eaba044fe0d2a6891034de3521625aa658
[]
no_license
mxndev/cheetahwutiOSController
8b060ee5783f93815853ce22804d086a69dd7a93
78688a0add4df67de1015aad2960288d04577551
refs/heads/master
2021-01-18T22:43:31.522856
2016-07-03T18:56:48
2016-07-03T18:56:48
62,509,293
0
0
null
null
null
null
UTF-8
C++
false
false
2,390
hpp
#ifndef BOOST_MPL_SET_AUX_ITERATOR_HPP_INCLUDED #define BOOST_MPL_SET_AUX_ITERATOR_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2003-2007 // Copyright David Abrahams 2003-2004 // // 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) // // See http://www.boost.org/libs/mpl for documentation. // $Id: iterator.hpp 49267 2008-10-11 06:19:02Z agurtovoy $ // $Date: 2008-10-11 02:19:02 -0400 (Sam, 11 oct 2008) $ // $Revision: 49267 $ #include <boost/mpl/set/aux_/set0.hpp> #include <boost/mpl/has_key.hpp> #include <boost/mpl/iterator_tags.hpp> #include <boost/mpl/next.hpp> #include <boost/mpl/eval_if.hpp> #include <boost/mpl/if.hpp> #include <boost/mpl/identity.hpp> #include <boost/mpl/aux_/config/ctps.hpp> namespace boost { namespace mpl { // used by 's_iter_get' template< typename Set, typename Tail > struct s_iter; template< typename Set, typename Tail > struct s_iter_get : eval_if< has_key< Set,typename Tail::item_type_ > , identity< s_iter<Set,Tail> > , next< s_iter<Set,Tail> > > { }; template< typename Set, typename Tail > struct s_iter_impl { typedef Tail tail_; typedef forward_iterator_tag category; typedef typename Tail::item_type_ type; #if defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) typedef typename s_iter_get< Set,typename Tail::base >::type next; #endif }; #if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) template< typename Set, typename Tail > struct next< s_iter<Set,Tail> > : s_iter_get< Set,typename Tail::base > { }; template< typename Set > struct next< s_iter<Set,set0<> > > { typedef s_iter<Set,set0<> > type; }; template< typename Set, typename Tail > struct s_iter : s_iter_impl<Set,Tail> { }; template< typename Set > struct s_iter<Set, set0<> > { typedef forward_iterator_tag category; }; #else template< typename Set > struct s_end_iter { typedef forward_iterator_tag category; typedef s_iter<Set,set0<> > next; }; template< typename Set, typename Tail > struct s_iter : if_< is_same< Tail,set0<> > , s_end_iter<Set> , s_iter_impl<Set,Tail> >::type { }; #endif // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION }} #endif // BOOST_MPL_SET_AUX_ITERATOR_HPP_INCLUDED
9fae230d47bc113792cf669554311a39bbe44ee6
04b1803adb6653ecb7cb827c4f4aa616afacf629
/third_party/blink/renderer/core/script/script_scheduling_type.h
928143ec8955e014a8fa5ef29b132b6a9b571c71
[ "LGPL-2.0-only", "BSD-2-Clause", "LGPL-2.1-only", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "GPL-1.0-or-later", "GPL-2.0-only", "LicenseRef-scancode-other-copyleft", "MIT", "Apache-2.0", "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
2,078
h
// Copyright 2018 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 THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_SCRIPT_SCHEDULING_TYPE_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_SCRIPT_SCHEDULING_TYPE_H_ namespace blink { // Type of <script>'s scheduling. // // In the spec, this is determined which clause of Step 25 of // https://html.spec.whatwg.org/C/#prepare-a-script // is taken. // // The enum values are used in histograms and thus do not change existing // enum values when modifying. enum class ScriptSchedulingType { // Because the sheduling type is determined slightly after PendingScript // creation, it is set to kNotSet before ScriptLoader::TakePendingScript() // is called. kNotSet should not be observed. kNotSet, // Deferred scripts controlled by HTMLParserScriptRunner. // // Spec: 1st Clause. // // Examples: // - <script defer> (parser inserted) // - <script type="module"> (parser inserted) kDefer, // Parser-blocking external scripts controlled by XML/HTMLParserScriptRunner. // // Spec: 2nd Clause. // // Examples: // - <script> (parser inserted) kParserBlocking, // Parser-blocking inline scripts controlled by XML/HTMLParserScriptRunner. // // Spec: 5th Clause. kParserBlockingInline, // In-order scripts controlled by ScriptRunner. // // Spec: 3rd Clause. // // Examples (either classic or module): // - Dynamically inserted <script>s with s.async = false kInOrder, // Async scripts controlled by ScriptRunner. // // Spec: 4nd Clause. // // Examples (either classic or module): // - <script async> and <script async defer> (parser inserted) // - Dynamically inserted <script>s // - Dynamically inserted <script>s with s.async = true kAsync, // Inline <script> executed immediately within prepare-a-script. kImmediate }; static const int kLastScriptSchedulingType = static_cast<int>(ScriptSchedulingType::kImmediate); } // namespace blink #endif
e1bf6f9ed7e71a9fd0bfa24b8589c9281bc84aac
a5f1744553dac380ba3556263235937bce21c075
/Engine/src/Core/Timestep.h
7844c3107df404054844a2e27514a2523f7d973b
[]
no_license
bloodhero/Swordman-Remake
4c49a06d6451b3e24cce97d7ec226742aea33c0f
d2fb656754be6cbf7493969fa6cc9910efe4a140
refs/heads/master
2023-03-10T23:33:05.330952
2021-02-28T11:03:31
2021-02-28T11:03:31
278,327,158
8
3
null
null
null
null
UTF-8
C++
false
false
322
h
#pragma once #include <cstdint> namespace meow { class Timestep { public: // CREARTORS Timestep(); ~Timestep() = default; // ACCESSORS void onUpdate(); double getSeconds() const; double getMilliseconds() const; private: double m_Timestep; double m_CurrentTime; double m_LastFrameTime; }; }
88066e88526efa78a6d275b52be7aeef71ff3489
b5b5e825a618a37587f5cd41e03a52ad1c6e58f1
/src/doppelganger-routing/helper/ipv4-doppelganger-routing-helper.h
7dd620b9727d216859efc806aa2fbe33c9b23170
[]
no_license
wantonsolutions/replica-selection
e6cb2243284021b0f1d0d95c66bc8a15582451b3
7ac34eaacc6477f0801c4b744c6592152a40d8b0
refs/heads/master
2021-04-21T22:01:26.876399
2021-02-02T19:07:14
2021-02-02T19:07:14
249,820,031
1
0
null
null
null
null
UTF-8
C++
false
false
691
h
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ #ifndef IPV4_DOPPELGANGER_ROUTING_HELPER_H #define IPV4_DOPPELGANGER_ROUTING_HELPER_H #include "ns3/ipv4-doppelganger-routing.h" #include "ns3/ipv4-routing-helper.h" namespace ns3 { class Ipv4DoppelgangerRoutingHelper : public Ipv4RoutingHelper { public: Ipv4DoppelgangerRoutingHelper (); Ipv4DoppelgangerRoutingHelper (const Ipv4DoppelgangerRoutingHelper&); Ipv4DoppelgangerRoutingHelper* Copy (void) const; virtual Ptr<Ipv4RoutingProtocol> Create (Ptr<Node> node) const; Ptr<Ipv4DoppelgangerRouting> GetDoppelgangerRouting (Ptr<Ipv4> ipv4) const; }; } #endif /* IPV4_DOPPELGANGER_ROUTING_HELPER_H */
e0e587b52bc8a3eb3df014bbf16da0ae387d8c2b
0ec49633816a3d71b432e7afe79ac7621abaeedc
/GnecFilter/BufferPointD.cpp
fcf055d7f6e58643e07c4174175fef39b7033b22
[]
no_license
aclemotte/gazeFilters
af811c123287de1be6a809b851207c09c900d7d9
215f527d1821a8ed24015afb63e71a8707244171
refs/heads/master
2021-07-11T08:25:09.730701
2017-10-12T08:29:07
2017-10-12T08:29:07
106,666,111
0
0
null
null
null
null
UTF-8
C++
false
false
3,277
cpp
#include "BufferPointD.h" BufferPointD::BufferPointD() { clearBuffer(); } BufferPointD::~BufferPointD() { clearBuffer(); } //no hace lo que dice, falta hacer el sort PointD BufferPointD::getMeanMedianBuffer(PointD GazePoint) { //addPointD2Buffer(GazePoint); ////deben existir al menos tres puntos en el buffer para hacer lo siguiente //if (GazeBufferX.size() > 2) //{ // PointD gazeFiltered; // //si es par el promedio de los 4 centrales // //si es impar se promedia el del medio con sus vecinos // if (GazeBufferX.size() % 2 == 0)//si es par // { // gazeFiltered.X = ( // GazeBufferX[(GazeBufferX.size() / 2) - 2] + // GazeBufferX[(GazeBufferX.size() / 2) - 1] + // GazeBufferX[(GazeBufferX.size() / 2) + 0] + // GazeBufferX[(GazeBufferX.size() / 2) + 1]) / 4; // gazeFiltered.Y = ( // GazeBufferY[(GazeBufferX.size() / 2) - 2] + // GazeBufferY[(GazeBufferX.size() / 2) - 1] + // GazeBufferY[(GazeBufferX.size() / 2) + 0] + // GazeBufferY[(GazeBufferX.size() / 2) + 1]) / 4; // } // else//si es impar // { // gazeFiltered.X = ( // GazeBufferX[(GazeBufferX.size() / 2) - 1] + // GazeBufferX[(GazeBufferX.size() / 2) + 0] + // GazeBufferX[(GazeBufferX.size() / 2) + 1]) / 3; // gazeFiltered.Y = ( // GazeBufferY[(GazeBufferX.size() / 2) - 1] + // GazeBufferY[(GazeBufferX.size() / 2) + 0] + // GazeBufferY[(GazeBufferX.size() / 2) + 1]) / 3; // } // return gazeFiltered; //} //else //si el buffer tiene menos de 3 elementos, se devuelve el argumento //{ // return GazePoint; //} return GazePoint; } PointD BufferPointD::getAverageBuffer(PointD GazePoint) { addPointD2Buffer(GazePoint); PointD gazeFiltered; for (unsigned int indiceBuffer = 0; indiceBuffer < GazeBufferX.size(); indiceBuffer++) { gazeFiltered.X += GazeBufferX[indiceBuffer]; gazeFiltered.Y += GazeBufferY[indiceBuffer]; } gazeFiltered.X = gazeFiltered.X / GazeBufferX.size(); gazeFiltered.Y = gazeFiltered.Y / GazeBufferY.size(); return gazeFiltered; } PointD BufferPointD::getStdBuffer(PointD avgPoint) { PointD stdGaze; for (unsigned int indiceBuffer = 0; indiceBuffer < GazeBufferX.size(); indiceBuffer++) { stdGaze.X += (GazeBufferX[indiceBuffer] - avgPoint.X) * (GazeBufferX[indiceBuffer] - avgPoint.X); stdGaze.Y += (GazeBufferY[indiceBuffer] - avgPoint.Y) * (GazeBufferY[indiceBuffer] - avgPoint.Y); } stdGaze.X = sqrt((stdGaze.X / GazeBufferX.size())); stdGaze.Y = sqrt((stdGaze.Y / GazeBufferX.size())); return stdGaze; } PointD BufferPointD::getWABuffer(PointD GazePoint) { addPointD2Buffer(GazePoint); double pxf = 0; double pyf = 0; double qlen = GazeBufferX.size(); for (int i = 0; i<qlen; i++) { pxf += GazeBufferX.at(i) * (qlen - i) / (qlen*(qlen + 1) / 2); pyf += GazeBufferY.at(i) * (qlen - i) / (qlen*(qlen + 1) / 2); } PointD gazeFiltered(pxf, pyf); return gazeFiltered; } void BufferPointD::addPointD2Buffer(PointD GazePoint) { if (GazeBufferX.size() >= maxBufferSize) { GazeBufferX.pop_back(); GazeBufferY.pop_back(); } GazeBufferX.push_front(GazePoint.X); GazeBufferY.push_front(GazePoint.Y); } void BufferPointD::clearBuffer() { GazeBufferX.clear(); GazeBufferY.clear(); } int BufferPointD::getCurrentBufferSize() { return GazeBufferX.size(); }
3ff6f6c9422e1a7d7cb379a5249dc37057f127d7
6459ac2fc083d52fd1e4d58f52cad2d52c5db44a
/MyOpenGL/SceneObject.cpp
99313af43e10eca2e6598dfe98ee84e0939b0764
[]
no_license
giovani-luigi/OpenGL-Demo
34a1f8e79bfccda6eae800c28094df7713e34246
d53f36cac4e78c22ae61d77dfa278a44dc5ad75c
refs/heads/master
2023-02-12T08:52:23.611368
2020-12-26T21:19:25
2020-12-26T21:19:25
322,492,187
1
0
null
null
null
null
UTF-8
C++
false
false
3,667
cpp
#include "SceneObject.h" #include <utility> SceneObject::SceneObject( const std::vector<float>& vertices, const std::vector<float>& normals, SceneObjectType type, Shader shader, Material material ) : FollowsCamera(false), m_vao(0), m_tvbo(0), m_material(material), m_shader(shader), m_vertices(vertices), m_normals(normals) { // create the VBO and assign the VAO glGenVertexArrays(1, &m_vao); glBindVertexArray(m_vao); // create vertex buffer object for attribute: positions glGenBuffers(1, &m_vbo); // create 1 buffer glBindBuffer(GL_ARRAY_BUFFER, m_vbo); glBufferData(GL_ARRAY_BUFFER, m_vertices.size() * sizeof(float), &m_vertices[0], type); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr); // setup the layout of the buffer for positions glEnableVertexAttribArray(0); // enable the attribute // create vertex buffer object for attribute: normals glGenBuffers(1, &m_nvbo); // create 1 buffer glBindBuffer(GL_ARRAY_BUFFER, m_nvbo); glBufferData(GL_ARRAY_BUFFER, m_normals.size() * sizeof(float), &m_normals[0], type); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, nullptr); // setup the layout of the buffer for positions glEnableVertexAttribArray(1); // enable the attribute glDisableVertexAttribArray(2); // disable the texture coordinate attribute } SceneObject::SceneObject(const SceneObject& object) : FollowsCamera(object.FollowsCamera), m_transformation(object.m_transformation), m_material(object.m_material), m_shader(object.m_shader), m_vao(object.m_vao), m_vbo(object.m_vbo), m_nvbo(object.m_nvbo), m_tvbo(object.m_tvbo), m_vertices(object.m_vertices), m_normals(object.m_normals), m_texcoordinates(object.m_texcoordinates) { } void SceneObject::configure(const Camera& camera, const glm::mat4& projection, const SceneLights& lights) { // use specified shader for this object m_shader.use(); // set light parameters lights.set_uniforms(m_shader); // update uniforms for vertex shader m_shader.setMat4("u_view", camera.get_matrix()); m_shader.setMat4("u_proj", projection); // projection matrix if (FollowsCamera) { // counter act camera's transformations const auto cp = camera.get_position(); m_shader.setMat4("u_model", Transform3D() .translate(cp.x, cp.y, cp.z) .rotate_y_deg((camera.get_yaw_deg() + 90) * -1) // camera's initial YAW is -90 deg. .rotate_x_deg(camera.get_pitch_deg()) .combine(m_transformation) .get_matrix()); } else { m_shader.setMat4("u_model", m_transformation.get_matrix()); } // activate material m_material.use(m_shader); // inform shader if has texture m_shader.setBool("u_material.has_texture", has_texture()); } void SceneObject::draw() { glBindVertexArray(m_vao); glDrawArrays(GL_TRIANGLES, 0, (m_vertices.size() / 3)); } void SceneObject::set_texture_coordinates(std::vector<float>& coordinates) { m_texcoordinates = coordinates; if (!m_texcoordinates.empty()) { glBindVertexArray(m_vao); // create vertex buffer object for attribute: texture glGenBuffers(1, &m_tvbo); // create 1 buffer glBindBuffer(GL_ARRAY_BUFFER, m_tvbo); glBufferData(GL_ARRAY_BUFFER, m_texcoordinates.size() * sizeof(float), &m_texcoordinates[0], GL_STATIC_DRAW); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, nullptr); // setup the layout of the buffer for positions glEnableVertexAttribArray(2); // enable the attribute } }
29d0cdedfec41724277b55a3351684021ef9aed2
8b4c4546f92e1f185fc666e645a5f32926a81666
/thirdparty/physx/APEXSDK/framework/public/NxApexAssetPreviewScene.h
f7349016a35b6a7ba7ac57cb094055840a184bbb
[ "MIT" ]
permissive
johndpope/echo
a5db22b07421f9c330c219cd5b0e841629c7543c
e9ce2f4037e8a5d49b74cc7a9d9ee09f296e7fa7
refs/heads/master
2020-04-03T03:52:59.454520
2018-11-22T20:55:32
2018-11-22T20:55:32
154,997,449
0
0
MIT
2018-11-22T20:55:33
2018-10-27T18:39:23
C++
UTF-8
C++
false
false
1,978
h
/* * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. * * NVIDIA CORPORATION and its licensors retain all intellectual property * and proprietary rights in and to this software, related documentation * and any modifications thereto. Any use, reproduction, disclosure or * distribution of this software and related documentation without an express * license agreement from NVIDIA CORPORATION is strictly prohibited. */ #ifndef NX_APEX_ASSET_PREVIEW_SCENE_H #define NX_APEX_ASSET_PREVIEW_SCENE_H /*! \file \brief classes NxApexScene, NxApexSceneStats, NxApexSceneDesc */ #include "NxApexDesc.h" #include "NxApexRenderable.h" #include "NxApexContext.h" #include "foundation/PxVec3.h" #include <NxApexDefs.h> namespace physx { class PxCpuDispatcher; class PxGpuDispatcher; class PxTaskManager; class PxBaseTask; } #if NX_SDK_VERSION_MAJOR == 2 class NxScene; class NxDebugRenderable; #elif NX_SDK_VERSION_MAJOR == 3 #include "PxFiltering.h" namespace physx { class PxActor; class PxScene; class PxRenderBuffer; } #endif namespace NxParameterized { class Interface; } namespace physx { namespace apex { PX_PUSH_PACK_DEFAULT /** \brief An APEX class for */ class NxApexAssetPreviewScene : public NxApexInterface { public: /** \brief Sets the view matrix. Should be called whenever the view matrix needs to be updated. */ virtual void setCameraMatrix(const physx::PxMat44& viewTransform) = 0; /** \brief Returns the view matrix set by the user for the given viewID. */ virtual physx::PxMat44 getCameraMatrix() const = 0; /** \brief Sets whether the asset preview should simply show asset names or many other parameter values */ virtual void setShowFullInfo(bool showFullInfo) = 0; /** \brief Get the bool which determines whether the asset preview shows just asset names or parameter values */ virtual bool getShowFullInfo() const = 0; }; PX_POP_PACK } } // end namespace physx::apex #endif // NX_APEX_SCENE_H
2ec71e8b31175d666e7ee1442d0f70b70d73010e
398116ee19092a9833693c01845ee56309d8d172
/src/Audio/SoundWrapper.cpp
a02bb291e7c22a21af2b0318a20f55f478a30c3d
[]
no_license
RaphOb/worms_war-
9ed9eaa8b285a08fa534f97d77bc1167323e04ac
afe9a7cf47500034c35d5dcba61bcabd7373b422
refs/heads/master
2021-05-23T08:01:44.898337
2020-04-05T08:29:33
2020-04-05T08:29:33
253,188,537
0
0
null
null
null
null
UTF-8
C++
false
false
339
cpp
// // Created by geoff on 05/03/2020. // #include "SoundWrapper.hh" bool SoundWrapper::isStopped() { return m_sound.getStatus() == sf::SoundSource::Stopped; } void SoundWrapper::play() { m_sound.setVolume(m_volume); m_sound.play(); m_beenPlayed = true; } bool SoundWrapper::hasBeenPlayed() { return m_beenPlayed; }
6f399e15e9a82030ae40503d61da5014fcdc5846
50d4a30b6494ee797a7e63ab39788855e47e504c
/ESP12E/include/hx711scale.h
fb8bda87845b2be4f3a80ce1b0d1b51ee1c263fc
[]
no_license
miniship/ESP12_Drink_Water_Reminder_And_Tracker
202d860206ba948a91da013fd8c7fcb10541723f
6a54e8bb083fff101d87bba112c19dc3e2c217eb
refs/heads/master
2020-07-23T22:52:55.521664
2019-10-06T14:28:08
2019-10-06T14:28:08
207,730,491
0
0
null
null
null
null
UTF-8
C++
false
false
109
h
#ifndef hx711scale_h #define hx711scale_h namespace scale { void init(); float readData(); } #endif
5d9997330f816ff2535bf6a72ec89fc0ff44be25
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_11054.cpp
5efc933de9685f956544b4fa209277fd5ca5cfd3
[]
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
118
cpp
(l > limit || (l == limit && digit > last_digit_limit)) { l = UINT64_MAX; /* Truncate on overflow. */ break; }
22c26751156768282b28aad1ac8304b41abe4c77
ace28e29eaa4ff031fdf7aa4d29bb5d85b46eaa3
/Visual Mercutio/zReportWeb/PSS_PublishRuleBook.cpp
de502b2791b21fabdeed349c06eabdfd7c6d79fa
[ "MIT" ]
permissive
emtee40/Visual-Mercutio
675ff3d130783247b97d4b0c8760f931fbba68b3
f079730005b6ce93d5e184bb7c0893ccced3e3ab
refs/heads/master
2023-07-16T20:30:29.954088
2021-08-16T19:19:57
2021-08-16T19:19:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,453
cpp
/**************************************************************************** * ==> PSS_PublishRuleBook -------------------------------------------------* **************************************************************************** * Description : Provides a navigator which will publish the rule book to * * html files * * Developer : Processsoft * ****************************************************************************/ #include "StdAfx.h" #include "PSS_PublishRuleBook.h" // resources #include "zReportWebRes.h" #include "PSS_ModelResIDs.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[] = __FILE__; #define new DEBUG_NEW #endif //--------------------------------------------------------------------------- // PSS_PublishRuleBook //--------------------------------------------------------------------------- PSS_PublishRuleBook::PSS_PublishRuleBook(PSS_ProcessGraphModelMdlBP* pModel) : m_pRootModel(pModel), m_Level(0), m_Lvl1Counter(0), m_Lvl2Counter(0), m_Lvl3Counter(0) {} //--------------------------------------------------------------------------- PSS_PublishRuleBook::~PSS_PublishRuleBook() {} //--------------------------------------------------------------------------- bool PSS_PublishRuleBook::Publish(const CString& dir) { // if no doc or model defined, nothing to do if (!m_pRootModel) return false; // create the window to receive the file generation feedback m_FileGenerateWindow.Create(); if (!CreateFileSystem(m_pRootModel->GetMainLogicalRules(), dir)) { // hide the feedback dialog m_FileGenerateWindow.ShowWindow(SW_HIDE); return false; } // hide the feedback dialog m_FileGenerateWindow.ShowWindow(SW_HIDE); return true; } //--------------------------------------------------------------------------- bool PSS_PublishRuleBook::CreateFileSystem(PSS_LogicalRulesEntity* pRules, const CString& dir) { if (!pRules) return false; if (!m_HtmlFile.Create(GenerateFileName(dir))) return false; m_FileGenerateWindow.SetDestination(GenerateFileName(dir)); m_FileGenerateWindow.UpdateWindow(); CString title; title.LoadString(IDS_RULEBOOK_TITLE); GenerateHTMLPageHeader(title); CreateReport(pRules); GenerateHTMLPageFooter(); m_HtmlFile.CloseFile(); return true; } //--------------------------------------------------------------------------- void PSS_PublishRuleBook::CreateReport(PSS_LogicalRulesEntity* pRules) { if (!pRules) return; // get the rule name and description const CString ruleName = pRules->GetEntityName(); const CString ruleDesc = pRules->GetEntityDescription(); switch (m_Level) { case 0: GenerateHTMLDocumentHeader(ruleName, ruleDesc); break; case 1: ++m_Lvl1Counter; GenerateHTMLTable1(ruleName, ruleDesc); m_Lvl2Counter = 0; m_Lvl3Counter = 0; break; case 2: ++m_Lvl2Counter; GenerateHTMLTable2(ruleName, ruleDesc); m_Lvl3Counter = 0; break; case 3: default: ++m_Lvl3Counter; GenerateHTMLTable3(ruleName, ruleDesc); break; } // check if the rule contains children if (pRules->ContainEntity()) { const int count = pRules->GetEntityCount(); for (int i = 0; i < count; ++i) { PSS_LogicalRulesEntity* pEntity = dynamic_cast<PSS_LogicalRulesEntity*>(pRules->GetEntityAt(i)); if (!pEntity) continue; ++m_Level; CreateReport(pEntity); --m_Level; } } } //--------------------------------------------------------------------------- void PSS_PublishRuleBook::GenerateHTMLPageHeader(const CString& title) { CString output; output.Format(IDS_RULEBOOK_HTML_1, title); WriteLine(output); } //--------------------------------------------------------------------------- void PSS_PublishRuleBook::GenerateHTMLPageFooter() { WriteLine(IDS_RULEBOOK_HTML_2); } //--------------------------------------------------------------------------- void PSS_PublishRuleBook::GenerateHTMLDocumentHeader(const CString& ruleName, const CString& ruleDesc) { CString output; output.Format(IDS_RULEBOOK_HTML_6, ruleName, ruleDesc); WriteLine(output); } //--------------------------------------------------------------------------- void PSS_PublishRuleBook::GenerateHTMLTable1(const CString& ruleName, const CString& ruleDesc) { CString index; index.Format(_T("%d"), m_Lvl1Counter); CString output; output.Format(IDS_RULEBOOK_HTML_3, index, ruleName, ruleDesc); WriteLine(output); } //--------------------------------------------------------------------------- void PSS_PublishRuleBook::GenerateHTMLTable2(const CString& ruleName, const CString& ruleDesc) { CString index; index.Format(_T("%d.%d"), m_Lvl1Counter, m_Lvl2Counter); CString output; output.Format(IDS_RULEBOOK_HTML_4, index, ruleName, ruleDesc); WriteLine(output); } //--------------------------------------------------------------------------- void PSS_PublishRuleBook::GenerateHTMLTable3(const CString& ruleName, const CString& ruleDesc) { CString index; index.Format(_T("%d.%d.%d"), m_Lvl1Counter, m_Lvl2Counter, m_Lvl3Counter); CString output; output.Format(IDS_RULEBOOK_HTML_5, index, ruleName, ruleDesc); WriteLine(output); } //--------------------------------------------------------------------------- CString PSS_PublishRuleBook::GenerateFileName(const CString& dir) { CString fileName = dir; fileName += _T("RuleBook"); fileName += _T(".htm"); return fileName; } //--------------------------------------------------------------------------- void PSS_PublishRuleBook::WriteLine(const CString& text) { if (!text.IsEmpty()) m_HtmlFile << text; } //--------------------------------------------------------------------------- void PSS_PublishRuleBook::WriteLine(int id) { CString output; output.LoadString(id); if (!output.IsEmpty()) m_HtmlFile << output; } //---------------------------------------------------------------------------
90dfac13689c7f00aa10da7fd3e46ca8004fca48
83da30dc786e34cfd63d2c03d3e47df4d20155ef
/src/metatraits/gmetaserializer_trapall.cpp
722123c9e356780c183a288fb34fb0e1e1c7aa32
[ "Apache-2.0" ]
permissive
mvidelgauz/cpgf
bd6aa06454fb1ebfc7a45398b7ed6f2a13e02ce1
7e7a424b3e61c6a6957ec6d262feb31471345315
refs/heads/develop
2022-05-28T19:02:58.258675
2017-05-11T05:38:06
2017-05-11T05:38:06
116,567,011
0
0
NOASSERTION
2022-05-22T15:27:25
2018-01-07T13:19:23
C++
UTF-8
C++
false
false
3,376
cpp
#include "cpgf/metatraits/gmetaserializer_trapall.h" #include "cpgf/serialization/gmetaarchivecommon.h" #include "cpgf/serialization/gmetaarchivereader.h" #include "cpgf/serialization/gmetaarchivewriter.h" #include "cpgf/gsharedinterface.h" namespace cpgf { class GMetaSerializerTrapAll : public IMetaSerializer { G_INTERFACE_IMPL_OBJECT G_INTERFACE_IMPL_EXTENDOBJECT public: GMetaSerializerTrapAll(const GMetaType & metaType, IMetaSerializer * serializer) : metaType(metaType), serializer(serializer) { } virtual ~GMetaSerializerTrapAll() {} virtual const char * G_API_CC getClassTypeName(IMetaArchiveWriter * archiveWriter, const void * instance, IMetaClass * metaClass) { if(this->serializer) { return this->serializer->getClassTypeName(archiveWriter, instance, metaClass); } else { return this->metaType.getBaseName(); } } virtual void G_API_CC writeObject(IMetaArchiveWriter * archiveWriter, IMetaSerializerWriter * /*serializerWriter*/, GMetaArchiveWriterParam * param) { GMetaTypeData typeData = this->metaType.refData(); archiveWriter->writeData(param->name, param->instance, &typeData, this->serializer.get()); } virtual void * G_API_CC allocateObject(IMetaArchiveReader * archiveReader, IMetaClass * metaClass) { if(this->serializer) { return this->serializer->allocateObject(archiveReader, metaClass); } else { GScopedInterface<IMetaClass> metaClassHolder; if(metaClass == nullptr && this->metaType.getBaseName() != nullptr) { GScopedInterface<IMetaService> service(archiveReader->getMetaService()); metaClassHolder.reset(service->findClassByName(this->metaType.getBaseName())); metaClass = metaClassHolder.get(); } if(metaClass != nullptr) { return metaClass->createInstance(); } else { return nullptr; } } } virtual void G_API_CC freeObject(IMetaArchiveReader * archiveReader, IMetaClass * metaClass, void * instance) { if(this->serializer) { this->serializer->freeObject(archiveReader, metaClass, instance); } else { GScopedInterface<IMetaClass> metaClassHolder; if(metaClass == nullptr && this->metaType.getBaseName() != nullptr) { GScopedInterface<IMetaService> service(archiveReader->getMetaService()); metaClassHolder.reset(service->findClassByName(this->metaType.getBaseName())); metaClass = metaClassHolder.get(); } if(metaClass != nullptr) { metaClass->destroyInstance(instance); } } } virtual void G_API_CC readObject(IMetaArchiveReader * archiveReader, IMetaSerializerReader * /*serializerReader*/, GMetaArchiveReaderParam * param) { GMetaTypeData typeData = this->metaType.refData(); void * ptr = param->instance; if(this->metaType.isPointer()) { ptr = &param->instance; } archiveReader->readData(param->name, ptr, &typeData, this->serializer.get()); } private: GMetaType metaType; GSharedInterface<IMetaSerializer> serializer; }; namespace metatraits_internal { IMetaSerializer * doCreateTrapAllSerializer(const GMetaType & metaType, IMetaSerializer * serializer) { if(serializer != nullptr || canSerializeMetaType(metaType)) { return new GMetaSerializerTrapAll(metaType, serializer); } else { return nullptr; } } } // namespace metatraits_internal } // namespace cpgf
e7ad0b561fa19d35140450bd316adbf452706c3d
117e7c3b88925a338e4400ad5adddab893c1a31a
/src/support/events.h
5d9b4eb50d51850ee56e70b3cbd1cf7102a54b54
[ "MIT" ]
permissive
phanngocchien1986/machinecoin-core
4c4df2f63eedc6e3ab49a527237ffb549e0532fb
4fb709ff6df894bdc515b92c5623666f4424b51e
refs/heads/master
2020-03-07T19:47:42.743853
2018-02-28T11:48:28
2018-02-28T11:48:28
127,680,258
1
0
null
2018-04-01T23:40:59
2018-04-01T23:40:59
null
UTF-8
C++
false
false
1,708
h
// Copyright (c) 2016 The Machinecoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef MACHINECOIN_SUPPORT_EVENTS_H #define MACHINECOIN_SUPPORT_EVENTS_H #include <ios> #include <memory> #include <event2/event.h> #include <event2/http.h> #define MAKE_RAII(type) \ /* deleter */\ struct type##_deleter {\ void operator()(struct type* ob) {\ type##_free(ob);\ }\ };\ /* unique ptr typedef */\ typedef std::unique_ptr<struct type, type##_deleter> raii_##type MAKE_RAII(event_base); MAKE_RAII(event); MAKE_RAII(evhttp); MAKE_RAII(evhttp_request); MAKE_RAII(evhttp_connection); raii_event_base obtain_event_base() { auto result = raii_event_base(event_base_new()); if (!result.get()) throw std::runtime_error("cannot create event_base"); return result; } raii_event obtain_event(struct event_base* base, evutil_socket_t s, short events, event_callback_fn cb, void* arg) { return raii_event(event_new(base, s, events, cb, arg)); } raii_evhttp obtain_evhttp(struct event_base* base) { return raii_evhttp(evhttp_new(base)); } raii_evhttp_request obtain_evhttp_request(void(*cb)(struct evhttp_request *, void *), void *arg) { return raii_evhttp_request(evhttp_request_new(cb, arg)); } raii_evhttp_connection obtain_evhttp_connection_base(struct event_base* base, std::string host, uint16_t port) { auto result = raii_evhttp_connection(evhttp_connection_base_new(base, NULL, host.c_str(), port)); if (!result.get()) throw std::runtime_error("create connection failed"); return result; } #endif // MACHINECOIN_SUPPORT_EVENTS_H
9be69cffe904678315b35bc4f2ff8a5530f302d0
430061343e7b5f279f72b5c874e7b4385424a881
/Arduino/libraries/Nexus_FRAM_SPI/Nexus_FRAM_SPI.hpp
4a5dac61da4175a1bab7b46686a321e2b5598d80
[ "BSD-2-Clause" ]
permissive
mikeaustin/arduino-nexus-archived
e652c45903c2875ea2a7906254ec72943c71364e
74dde12b4f45a3a3e614e0058629d70f68f3825e
refs/heads/master
2021-05-30T17:55:26.658577
2015-12-13T21:18:15
2015-12-13T21:18:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,867
hpp
// // Nexus_FRAM_SPI.cpp // namespace Nexus { // // class FRAM_SPI // // Initialize pins and SPI template<uint8_t CS_Pin, uint8_t CLK_Pin, uint8_t MISO_Pin, uint8_t MOSI_Pin> void FRAM_SPI<CS_Pin, CLK_Pin, MISO_Pin, MOSI_Pin>::begin() { pinMode(CS_Pin, OUTPUT); digitalWrite(CS_Pin, HIGH); this->initialize(); uint8_t mfgID; uint16_t prodID; getDeviceID(&mfgID, &prodID); if (mfgID != 0x04 || prodID != 0x0302) { return false; } return _initialized = true; } // Read and write to memory template<uint8_t CS_Pin, uint8_t CLK_Pin, uint8_t MISO_Pin, uint8_t MOSI_Pin> void FRAM_SPI<CS_Pin, CLK_Pin, MISO_Pin, MOSI_Pin>::write(uint16_t addr, uint8_t data) { digitalWrite(CS_Pin, LOW); this->transfer(Opcode_WRITE); this->transfer(highByte(addr)); // (uint8_t)(addr >> 8 & 0xFF) this->transfer(lowByte(addr)); // (uint8_t)(addr >> 0 & 0xFF) this->transfer(data); digitalWrite(CS_Pin, HIGH); } template<uint8_t CS_Pin, uint8_t CLK_Pin, uint8_t MISO_Pin, uint8_t MOSI_Pin> uint8_t FRAM_SPI<CS_Pin, CLK_Pin, MISO_Pin, MOSI_Pin>::read(uint16_t addr) { digitalWrite(CS_Pin, LOW); this->transfer(Opcode_READ); this->transfer(highByte(addr)); this->transfer(lowByte(addr)); uint8_t data = this->transfer(0); digitalWrite(CS_Pin, HIGH); return data; } // Get the device identifier template<uint8_t CS_Pin, uint8_t CLK_Pin, uint8_t MISO_Pin, uint8_t MOSI_Pin> void FRAM_SPI<CS_Pin, CLK_Pin, MISO_Pin, MOSI_Pin>::getDeviceID(uint8_t *mfgID, uint16_t *prodID) { uint8_t array[4], results; digitalWrite(CS_Pin, LOW); this->transfer(Opcode_RDID); array[0] = this->transfer(0); array[1] = this->transfer(0); array[2] = this->transfer(0); array[3] = this->transfer(0); digitalWrite(CS_Pin, HIGH); *mfgID = (array[0]); *prodID = (array[2] << 8) + array[3]; } // Get and set the status register template<uint8_t CS_Pin, uint8_t CLK_Pin, uint8_t MISO_Pin, uint8_t MOSI_Pin> uint8_t FRAM_SPI<CS_Pin, CLK_Pin, MISO_Pin, MOSI_Pin>::getStatusRegister() { uint8_t reg = 0; digitalWrite(CS_Pin, LOW); this->transfer(Opcode_RDSR); reg = this->transfer(0); digitalWrite(CS_Pin, HIGH); return reg; } template<uint8_t CS_Pin, uint8_t CLK_Pin, uint8_t MISO_Pin, uint8_t MOSI_Pin> void FRAM_SPI<CS_Pin, CLK_Pin, MISO_Pin, MOSI_Pin>::setStatusRegister(uint8_t reg) { digitalWrite(CS_Pin, LOW); this->transfer(Opcode_WRSR); this->transfer(reg); digitalWrite(CS_Pin, HIGH); } }
e0b2d5de7cb6aa73a487222fb54cfb968c46f42b
9095705da4f7d28ab522f4c983cb73a74599a95b
/thread_edu_vs/utils.cpp
03f4cd67e4589e16ca81ad9051d5e61d51a5d292
[]
no_license
fanxiaohui/cpp
ca576e14d81279b7325bb44ac7293f6678e61c1f
1079895ff963dfd9933df40eee2f8077c684cf2b
refs/heads/master
2021-04-02T04:35:02.848512
2020-02-21T11:34:24
2020-02-21T11:34:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
867
cpp
#include "utils.h" void PrintIntroduction() { int i; int nFrame = 59; printf ("\t%c", 201); for (i=0; i<nFrame; i++) { printf ("%c", 205); } printf ("%c\n", 187); printf ("\t%c The wait command is used within a computer batch file %c\n", 186, 186); printf ("\t%c and allows the computer to pause the currently running %c\n", 186, 186); printf ("\t%c batch file for an amount of milliseconds . %c\n", 186, 186); printf ("\t%c Usage: 'WAIT 1000' will wait for 1 second. %c\n", 186, 186); printf ("\t%c %c\n", 186, 186); printf ("\t%c GE (c) 2007. %c\n", 186, 186); printf ("\t%c", 200); for (i=0; i<nFrame; i++) { printf ("%c", 205); } printf ("%c\n", 188); };
e9f36e35b7bb67398a4081cd3dbea9c1d47c0542
b2d00d17c53c54e4c5ac9a919aaa001381204826
/webapp/op2/OpDownloader.cpp
8ec830e7f903bcdd72a078a675083c5d48dafe85
[ "NCSA" ]
permissive
wenqingchu/revised-browser
2f8c326cdec1759d4241db4efdfec7164aafb0d0
22aff9d5f7aa2e6628a65802e06228c759f15c8d
refs/heads/master
2021-01-17T06:34:31.021189
2013-08-15T03:29:53
2013-08-15T03:29:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,551
cpp
/*======================================================== **University of Illinois/NCSA **Open Source License ** **Copyright (C) 2007-2008,The Board of Trustees of the University of **Illinois. All rights reserved. ** **Developed by: ** ** Research Group of Professor Sam King in the Department of Computer ** Science The University of Illinois at Urbana-Champaign ** http://www.cs.uiuc.edu/homes/kingst/Research.html ** **Permission is hereby granted, free of charge, to any person obtaining a **copy of this software and associated documentation files (the **¡°Software¡±), to deal with the Software without restriction, including **without limitation the rights to use, copy, modify, merge, publish, **distribute, sublicense, and/or sell copies of the Software, and to **permit persons to whom the Software is furnished to do so, subject to **the following conditions: ** *** Redistributions of source code must retain the above copyright notice, **this list of conditions and the following disclaimers. *** Redistributions in binary form must reproduce the above copyright **notice, this list of conditions and the following disclaimers in the **documentation and/or other materials provided with the distribution. *** Neither the names of <Name of Development Group, Name of Institution>, **nor the names of its contributors may be used to endorse or promote **products derived from this Software without specific prior written **permission. ** **THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, **EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF **MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. **IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR **ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, **TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE **SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE SOFTWARE. **========================================================== */ #include "OpDownloader.h" #include "OpNetwork.h" #include "OpNetworkReply.h" #include <QFileInfo> #include <QNetworkReply> #include <QNetworkRequest> #include <QDataStream> #include <QBuffer> #include <QVariant> int OpDownloader::s_reqId = 0; OpDownloader::OpDownloader(QNetworkReply* reply) : m_reply(reply) , m_reqId(s_reqId++) , m_sent(false) , m_finished(false) , m_bytes(0) { init(); } OpDownloader::OpDownloader(const QNetworkRequest& request) : m_reply(0) , m_reqId(s_reqId++) , m_sent(false) , m_finished(false) , m_bytes(0) { if (!request.url().isEmpty()) m_reply = OPNET::OpNetwork::instance()->networkAccessManager()->get(request); init(); } OpDownloader::~OpDownloader() { } void OpDownloader::init() { m_bytes = 0; if (m_reply == 0) finished(); m_reply->setParent(this); connect(m_reply, SIGNAL(readyRead()), this, SLOT(downloadReadyRead())); connect(m_reply, SIGNAL(metaDataChanged()), this, SLOT(metaDataChanged())); connect(m_reply, SIGNAL(finished()), this, SLOT(finished())); if (m_reply->error() != QNetworkReply::NoError) { finished(); } else { OPNET::OpNetworkReply* opReply = qobject_cast<OPNET::OpNetworkReply*> (m_reply); if (opReply != 0 && opReply->isFinished()) { start(); downloadReadyRead(); finished(); } } } QString OpDownloader::getFileName() { // Move this function into QNetworkReply to also get file name sent from the server QString path; if (m_reply->hasRawHeader("Content-Disposition")) { QString value = QLatin1String(m_reply->rawHeader("Content-Disposition")); int pos = value.indexOf(QLatin1String("filename=")); if (pos != -1) { QString name = value.mid(pos + 9); if (name.startsWith(QLatin1Char('"')) && name.endsWith(QLatin1Char('"'))) name = name.mid(1, name.size() - 2); path = name; } } if (path.isEmpty()) path = m_reply->url().path(); QFileInfo info(path); QString baseName = info.completeBaseName(); QString endName = info.suffix(); if (baseName.isEmpty()) { baseName = QLatin1String("unknown"); } if (!endName.isEmpty()) { endName = QLatin1Char('.') + endName; } else { } QString name = baseName + endName; return name; } void OpDownloader::downloadReadyRead() { QByteArray data = m_reply->readAll(); if (data.size() > 0) { if (!m_sent) { // if we haven't sent the request start(); } m_bytes += data.size(); OPNET::OpNetwork::instance()->sendDownloadRequest(m_reqId, data); } } void OpDownloader::start() { qint64 size = m_reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(); QByteArray bytes; QBuffer buffer(&bytes); buffer.open(QIODevice::ReadWrite); QDataStream out(&buffer); QVariant var; m_filename = getFileName(); var = QVariant(m_filename); out << var; var = QVariant(size); out << var; OPNET::OpNetwork::instance()->sendDownloadRequest(m_reqId, bytes); m_sent = true; } void OpDownloader::metaDataChanged() { } void OpDownloader::finished() { if (m_sent && !m_finished) { OPNET::OpNetwork::instance()->sendDownloadRequest(m_reqId, QByteArray()); } m_finished = true; deleteLater(); }
8baa22a4e06e529c5403afbe495730430bc7def9
9b30032b0c5becd6fb4094203f29f2e54e33680a
/binaryTree/Morris.cpp
3ac2c4f493be93413ab2063b58a587fb1fef8103
[]
no_license
RainyDay7/Algorithm
10b887e0ea765d418220bfc2665e65c13f4b9cca
a234aeed342aeb240db59ef4a0f8f280d597ca89
refs/heads/master
2020-09-04T06:55:52.691492
2020-04-12T10:25:56
2020-04-12T10:25:56
219,680,269
0
0
null
null
null
null
UTF-8
C++
false
false
1,115
cpp
public class MorrisTraval { private TreeNode root = null; public MorrisTraval(TreeNode r) { this.root = r; } public void travel() { TreeNode n = this.root; while (n != null) { if (n.left == null) { System.out.print(n.vaule + " "); n = n.right; } else { TreeNode pre = getPredecessor(n); if (pre.right == null) { pre.right = n; n = n.left; }else if (pre.right == n) { pre.right = null; System.out.print(n.vaule + " "); n = n.right; } } } } private TreeNode getPredecessor(TreeNode n) { TreeNode pre = n; if (n.left != null) { pre = pre.left; while (pre.right != null && pre.right != n) { pre = pre.right; } } return pre; } }
442d113471a2222e50f2fadcbe9814c7a36319e3
52200577bb7a56d108765e4fcb70c9bde27a4ece
/Merge Two Sorted Lists/main.cpp
76b4927a4dd4886f44a6e626fd2ec1176bad86cb
[]
no_license
zjsxzy/Leetcode
59e7da0319b567b5349a97de401a9990ea7a4df8
d540f0e921cae3b17da7c9f4932d4a3e3419c245
refs/heads/master
2023-08-19T08:50:48.874076
2023-08-06T05:22:37
2023-08-06T05:22:37
13,141,035
2
0
null
null
null
null
UTF-8
C++
false
false
1,109
cpp
#include <map> #include <set> #include <list> #include <cmath> #include <queue> #include <stack> #include <bitset> #include <vector> #include <cstdio> #include <string> #include <cassert> #include <climits> #include <sstream> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> using namespace std; #define PB push_back #define MP make_pair #define SZ(v) ((int)(v).size()) #define abs(x) ((x) > 0 ? (x) : -(x)) #define FOREACH(e,x) for(__typeof(x.begin()) e=x.begin();e!=x.end();++e) typedef long long LL; /* * Description: Merge two sorted list. * * Solution: Brute force. * */ struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { ListNode *head = new ListNode(0); ListNode *tail = head; while (l1 && l2) { if (l1->val < l2->val) { tail->next = l1; tail = l1; l1 = l1->next; } else { tail->next = l2; tail = l2; l2 = l2->next; } } tail->next = l1 ? l1 : l2; return head->next; } }; int main() { }
ec8875a2c4151de256d723b830b5b9d2d676f4a2
8a8888bde6f563bfe1a3fc877bc0537875c7c675
/deps_leveldb_table_block_builder.cc
d78d91a141b051833a7df9a86077b1a424535c58
[ "MIT" ]
permissive
DataDog/leveldb
66c826e477fc16bc56bb0bfda6e060c5fe9a9e80
0631e62f1233ef6b823a5ab19a28dc8cd6d229d2
refs/heads/master
2023-08-25T11:31:10.125661
2021-01-22T15:40:18
2021-01-22T15:40:18
66,093,652
4
1
MIT
2023-04-08T10:35:21
2016-08-19T15:46:24
Go
UTF-8
C++
false
false
35
cc
deps/leveldb/table/block_builder.cc
ac17b67262aa25b4a85740feb18b51f1b37b4e1c
7123f4f31f71d31acb5917240e887142e7ea86e1
/Search/test.cpp
3833d046f4dbdb19494ac417ec1ca5cbcadfdb45
[]
no_license
fpk2014/algorithm
27e35262703e270dc8989c8650f1e01ad5f4ab7b
cf5ca1a61db7d1fbe3b9069e308ea20498d7eeab
refs/heads/master
2021-07-10T19:45:04.151555
2017-10-09T16:36:30
2017-10-09T16:36:30
103,735,953
0
0
null
null
null
null
UTF-8
C++
false
false
411
cpp
#include <iostream> using namespace std; typedef struct btnode{ int value; struct btnode *left; struct btnode *right; }node, *btree; void insert(btree t, int value){ node *tmp = NULL; cout << value << endl; tmp = (node *) malloc(sizeof(node)); tmp->left = tmp->right = NULL; tmp->value = value; t = tmp; } int main(){ btree t = NULL; cout << static_cast<const void *>(t) << endl; return 0; }
f0066c2d40b85573f78dcfdebc8fc85d2f18c60c
86bb0710c10e0f26c8a7106d62b7ee7a53bd4b4d
/Source.cpp
d93b2cb0a7446f6720b36a3b80fac9252cb0f549
[]
no_license
Hoaxx9/Triangle
1f536d904af7ad501f08b45cc955ae011719512a
45a12c80e59259d987c471b2c9fb33ba1a96ff15
refs/heads/master
2020-04-23T15:18:30.239420
2019-02-18T10:23:29
2019-02-18T10:23:29
171,260,787
0
0
null
null
null
null
UTF-8
C++
false
false
1,861
cpp
#include <stdlib.h> #include <glut.h> float red = 1.0f, blue = 1.0f, green = 1.0f; float angle = 0.0f; void changeSize(int w, int h) { //обработка изменения размеров окна программы if (h == 0) h = 1; float ratio = w * 1.0 / h; glMatrixMode(GL_PROJECTION); glLoadIdentity(); glViewport(0, 0, w, h); gluPerspective(45.0f, ratio, 0.1f, 100.0f); glMatrixMode(GL_MODELVIEW); } void renderScene(void) { //отрисовка кадра glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); gluLookAt(0.0f, 0.0f, 10.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f); glRotatef(angle, 0.0f, 1.0f, 0.0f); glColor3f(red, green, blue); glBegin(GL_TRIANGLES); glVertex3f(-2.0f, -2.0f, 0.0f); glVertex3f(0.0f, 2.0f, 0.0); glVertex3f(2.0f, -2.0f, 0.0); glEnd(); angle += 0.1f; glutSwapBuffers(); } void processNormalKeys(unsigned char key, int x, int y) { //закрытие окна программы по нажатию Esc if (key == 27) exit(0); } void processSpecialKeys(int key, int x, int y) { //обработка команд с клавиатуры switch (key) { case GLUT_KEY_F1: red = 1.0; green = 0.0; blue = 0.0; break; case GLUT_KEY_F2: red = 0.0; green = 1.0; blue = 0.0; break; case GLUT_KEY_F3: red = 0.0; green = 0.0; blue = 1.0; break; } } int main(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); glutInitWindowPosition(100, 100); glutInitWindowSize(400, 400); glutCreateWindow("Óðîê 4"); glutDisplayFunc(renderScene); glutReshapeFunc(changeSize); glutIdleFunc(renderScene); glutKeyboardFunc(processNormalKeys); glutSpecialFunc(processSpecialKeys); glutMainLoop(); return 0; }
917cba36755bf08913064654a0d846c353ce1a93
b4d2b42f94c72842ef8334ea3b763e56a1fb317f
/tests/lox_tests.cpp
035ee2a986dcee65b610127bd56a90fa5500b688
[ "MIT" ]
permissive
codingpotato/Lox-modern-cpp
8194654b054c021e8103b0adfd22bb5606270600
7ddc0edb95ea171a3dc0baf33ddaab1aeb3a34c5
refs/heads/master
2020-12-04T21:51:26.334972
2020-05-17T09:46:30
2020-05-17T09:46:30
231,911,761
13
6
null
null
null
null
UTF-8
C++
false
false
6,457
cpp
#include <doctest/doctest.h> #include <string> #include "config.h" #include "helper.h" #define LOX_TEST_CASE(filename) \ TEST_CASE("lox: " filename) { \ auto [source, expected] = load(EXAMPLES_DIR "/" filename ".lox"); \ REQUIRE_EQ(run(source), expected); \ } LOX_TEST_CASE("empty_file") LOX_TEST_CASE("precedence") LOX_TEST_CASE("unexpected_character") LOX_TEST_CASE("assignment/associativity") LOX_TEST_CASE("assignment/global") LOX_TEST_CASE("assignment/grouping") LOX_TEST_CASE("assignment/infix_operator") LOX_TEST_CASE("assignment/local") LOX_TEST_CASE("assignment/prefix_operator") LOX_TEST_CASE("assignment/syntax") LOX_TEST_CASE("assignment/undefined") LOX_TEST_CASE("block/empty") LOX_TEST_CASE("block/scope") LOX_TEST_CASE("bool/equality") LOX_TEST_CASE("bool/not") LOX_TEST_CASE("call/bool") LOX_TEST_CASE("call/nil") LOX_TEST_CASE("call/num") LOX_TEST_CASE("call/string") LOX_TEST_CASE("closure/assign_to_closure") LOX_TEST_CASE("closure/assign_to_shadowed_later") LOX_TEST_CASE("closure/close_over_function_parameter") LOX_TEST_CASE("closure/close_over_later_variable") LOX_TEST_CASE("closure/closed_closure_in_function") LOX_TEST_CASE("closure/nested_closure") LOX_TEST_CASE("closure/open_closure_in_function") LOX_TEST_CASE("closure/reference_closure_multiple_times") LOX_TEST_CASE("closure/reuse_closure_slot") LOX_TEST_CASE("closure/shadow_closure_with_local") LOX_TEST_CASE("closure/unused_closure") LOX_TEST_CASE("closure/unused_later_closure") LOX_TEST_CASE("comments/line_at_eof") LOX_TEST_CASE("comments/only_line_comment") LOX_TEST_CASE("comments/only_line_comment_and_line") LOX_TEST_CASE("comments/unicode") LOX_TEST_CASE("expressions/evaluate") LOX_TEST_CASE("for/class_in_body") LOX_TEST_CASE("for/closure_in_body") LOX_TEST_CASE("for/fun_in_body") LOX_TEST_CASE("for/return_closure") LOX_TEST_CASE("for/return_inside") LOX_TEST_CASE("for/scope") LOX_TEST_CASE("for/statement_condition") LOX_TEST_CASE("for/statement_increment") LOX_TEST_CASE("for/statement_initializer") LOX_TEST_CASE("for/syntax") LOX_TEST_CASE("for/var_in_body") LOX_TEST_CASE("function/body_must_be_block") LOX_TEST_CASE("function/empty_body") LOX_TEST_CASE("function/extra_arguments") LOX_TEST_CASE("function/local_mutual_recursion") LOX_TEST_CASE("function/local_recursion") LOX_TEST_CASE("function/missing_arguments") LOX_TEST_CASE("function/missing_comma_in_parameters") LOX_TEST_CASE("function/mutual_recursion") LOX_TEST_CASE("function/parameters") LOX_TEST_CASE("function/print") LOX_TEST_CASE("function/recursion") LOX_TEST_CASE("function/too_many_arguments") LOX_TEST_CASE("function/too_many_parameters") LOX_TEST_CASE("if/class_in_else") LOX_TEST_CASE("if/class_in_then") LOX_TEST_CASE("if/dangling_else") LOX_TEST_CASE("if/else") LOX_TEST_CASE("if/fun_in_else") LOX_TEST_CASE("if/fun_in_then") LOX_TEST_CASE("if/if") LOX_TEST_CASE("if/truth") LOX_TEST_CASE("if/var_in_else") LOX_TEST_CASE("if/var_in_then") LOX_TEST_CASE("limit/loop_too_large") LOX_TEST_CASE("limit/no_reuse_constants") LOX_TEST_CASE("limit/stack_overflow") LOX_TEST_CASE("limit/too_many_constants") LOX_TEST_CASE("limit/too_many_locals") LOX_TEST_CASE("limit/too_many_upvalues") LOX_TEST_CASE("logical_operator/and_truth") LOX_TEST_CASE("logical_operator/and") LOX_TEST_CASE("logical_operator/or_truth") LOX_TEST_CASE("logical_operator/or") LOX_TEST_CASE("nil/literal") LOX_TEST_CASE("number/leading_dot") LOX_TEST_CASE("number/literals") LOX_TEST_CASE("number/nan_equality") LOX_TEST_CASE("operator/add_bool_nil") LOX_TEST_CASE("operator/add_bool_num") LOX_TEST_CASE("operator/add_bool_string") LOX_TEST_CASE("operator/add_nil_nil") LOX_TEST_CASE("operator/add_num_nil") LOX_TEST_CASE("operator/add_string_nil") LOX_TEST_CASE("operator/add") LOX_TEST_CASE("operator/comparison") LOX_TEST_CASE("operator/divide_nonnum_num") LOX_TEST_CASE("operator/divide_num_nonnum") LOX_TEST_CASE("operator/divide") LOX_TEST_CASE("operator/equals") LOX_TEST_CASE("operator/greater_nonnum_num") LOX_TEST_CASE("operator/greater_num_nonnum") LOX_TEST_CASE("operator/greater_or_equal_nonnum_num") LOX_TEST_CASE("operator/greater_or_equal_num_nonnum") LOX_TEST_CASE("operator/less_nonnum_num") LOX_TEST_CASE("operator/less_num_nonnum") LOX_TEST_CASE("operator/less_or_equal_nonnum_num") LOX_TEST_CASE("operator/less_or_equal_num_nonnum") LOX_TEST_CASE("operator/multiply_nonnum_num") LOX_TEST_CASE("operator/multiply_num_nonnum") LOX_TEST_CASE("operator/multiply") LOX_TEST_CASE("operator/negate_nonnum") LOX_TEST_CASE("operator/negate") LOX_TEST_CASE("operator/not_equals") LOX_TEST_CASE("operator/not") LOX_TEST_CASE("operator/subtract_nonnum_num") LOX_TEST_CASE("operator/subtract_num_nonnum") LOX_TEST_CASE("operator/subtract") LOX_TEST_CASE("print/missing_argument") LOX_TEST_CASE("regression/40") LOX_TEST_CASE("return/after_else") LOX_TEST_CASE("return/after_if") LOX_TEST_CASE("return/after_while") LOX_TEST_CASE("return/at_top_level") LOX_TEST_CASE("return/in_function") LOX_TEST_CASE("return/return_nil_if_no_value") LOX_TEST_CASE("string/error_after_multiline") LOX_TEST_CASE("string/literals") LOX_TEST_CASE("string/multiline") LOX_TEST_CASE("string/unterminated") LOX_TEST_CASE("variable/collide_with_parameter") LOX_TEST_CASE("variable/shadow_local") LOX_TEST_CASE("variable/use_global_in_initializer") LOX_TEST_CASE("variable/duplicate_local") LOX_TEST_CASE("variable/redeclare_global") LOX_TEST_CASE("variable/undefined_global") LOX_TEST_CASE("variable/use_local_in_initializer") LOX_TEST_CASE("variable/duplicate_parameter") LOX_TEST_CASE("variable/redefine_global") LOX_TEST_CASE("variable/undefined_local") LOX_TEST_CASE("variable/use_nil_as_var") LOX_TEST_CASE("variable/early_bound") LOX_TEST_CASE("variable/scope_reuse_in_different_blocks") LOX_TEST_CASE("variable/uninitialized") LOX_TEST_CASE("variable/use_this_as_var") LOX_TEST_CASE("variable/in_middle_of_block") LOX_TEST_CASE("variable/shadow_and_local") LOX_TEST_CASE("variable/unreached_undefined") LOX_TEST_CASE("variable/in_nested_block") LOX_TEST_CASE("variable/shadow_global") LOX_TEST_CASE("variable/use_false_as_var") LOX_TEST_CASE("while/class_in_body") LOX_TEST_CASE("while/closure_in_body") LOX_TEST_CASE("while/fun_in_body") LOX_TEST_CASE("while/return_closure") LOX_TEST_CASE("while/return_inside") LOX_TEST_CASE("while/syntax") LOX_TEST_CASE("while/var_in_body")
c274d2781f15a05c807986945d40109423c6d58b
01259e89587631df1f3fbebeced0389284e129a5
/Lab6/MazeReader.cpp
71e7fc21cd4a376df282536c27ee6fab2ec67fe1
[]
no_license
DGSuper/EECS_268
a13773434ab01250acc61fa2a627c2857762bf66
2a328129db60bfa411b3f7f92570c54c7280a195
refs/heads/master
2021-01-19T16:25:17.303694
2017-02-08T17:33:04
2017-02-08T17:33:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,278
cpp
/** * @file MazeReader.cpp * @author Zachary Bruennig * @date 10/22/16 * @brief Attempts to read in a properly formatted file and create a character array from * the parameters and character matrix in the file. The matrix should only contain W, P, and Es. * The file should start with four numbers. The first two are the number of rows and number of columns in * the matrix, respectively. The third and fourth are the starting row column for the maze, respectively. * The size of the matrix should match the first two numbers in the file. If the size is smaller, * anexception will be thrown. If it is larger, it will only read the matrix up to the file's parameters, * namely, up to the first number for rows, and the second number for columns */ #include "MazeReader.h" MazeReader::MazeReader(std::string file) throw (MazeCreationException) { m_inFile.open(file); if(!m_inFile.is_open()) { m_valid = false; throw MazeCreationException("Cannot open file"); } try { readMaze(); } catch(MazeCreationException e) { m_inFile.close(); std::cout << e.what() << '\n'; } m_inFile.close(); } MazeReader::~MazeReader() { if(m_deleteArrays) { for(int i=0; i<m_numRows; i++) delete[] m_maze[i]; delete[] m_maze; } } const char* const* MazeReader::getMaze() const { return m_maze; } int MazeReader::getCols() const { return m_numCols; } int MazeReader::getRows() const { return m_numRows; } int MazeReader::getStartCol() const { return m_startCol; } int MazeReader::getStartRow() const { return m_startRow; } bool MazeReader::isValidMaze() const { return m_valid; } void MazeReader::readMaze() throw (MazeCreationException) { m_inFile >> m_numRows; m_inFile >> m_numCols; m_inFile >> m_startRow; m_inFile >> m_startCol; if(m_numRows<1) { m_valid = false; throw MazeCreationException("Invalid number of rows"); } if(m_numCols<1) { m_valid = false; throw MazeCreationException("Invalid number of columns"); } if(m_startRow>m_numRows || m_startCol>m_numCols || m_startRow<0 || m_startCol<0) { m_valid = false; throw MazeCreationException("Invalid starting position"); } m_maze = new char*[m_numRows]; m_deleteArrays = true; for(int i=0; i<m_numRows; i++) { m_maze[i] = new char[m_numCols]; std::string currentRow; m_inFile >> currentRow; for(int j=0; j<m_numCols; j++) { char curr = currentRow.at(j); if(curr!= 'E' && curr!= 'W' && curr!= 'P') throw MazeCreationException("Unexpected character in maze"); m_maze[i][j] = curr; } } if(m_maze[m_startRow][m_startCol]=='W') { m_valid = false; throw MazeCreationException("Invalid starting position"); } // TEST CODE THAT PRINTS OUT THE ARRAY // for(int i=0; i<m_numRows; i++) // { // for(int j=0; j<m_numCols; j++) // { // std::cout << m_maze[i][j]; // } // std::cout << '\n'; // } }
1af44ec73b049a8239c097134a5d5a66cac757b7
89c7c76bd8ecdd7b9ac521d85e9552d7a351c5e5
/src/rpcserver.h
da3eca1f745c7efd48c5e2681a8d91aba7d17870
[ "MIT" ]
permissive
TheAltcoinBoard/XAB-withoutSecp256k1
74e6f8544e28c1b381a0b554b53c8e65fba64caa
f4a52551a87bf7b52f4db767381ded57c767d913
refs/heads/master
2020-04-02T03:45:48.066874
2016-08-08T09:26:49
2016-08-08T09:26:49
63,477,250
0
0
null
null
null
null
UTF-8
C++
false
false
11,744
h
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef _BITCOINRPC_SERVER_H_ #define _BITCOINRPC_SERVER_H_ 1 #include "uint256.h" #include "rpcprotocol.h" #include <list> #include <map> class CBlockIndex; void StartRPCThreads(); void StopRPCThreads(); /* Type-check arguments; throws JSONRPCError if wrong type given. Does not check that the right number of arguments are passed, just that any passed are the correct type. Use like: RPCTypeCheck(params, boost::assign::list_of(str_type)(int_type)(obj_type)); */ void RPCTypeCheck(const json_spirit::Array& params, const std::list<json_spirit::Value_type>& typesExpected, bool fAllowNull=false); /* Check for expected keys/value types in an Object. Use like: RPCTypeCheck(object, boost::assign::map_list_of("name", str_type)("value", int_type)); */ void RPCTypeCheck(const json_spirit::Object& o, const std::map<std::string, json_spirit::Value_type>& typesExpected, bool fAllowNull=false); /* Run func nSeconds from now. Uses boost deadline timers. Overrides previous timer <name> (if any). */ void RPCRunLater(const std::string& name, boost::function<void(void)> func, int64_t nSeconds); typedef json_spirit::Value(*rpcfn_type)(const json_spirit::Array& params, bool fHelp); class CRPCCommand { public: std::string name; rpcfn_type actor; bool okSafeMode; bool threadSafe; bool reqWallet; }; /** * Bitcoin RPC command dispatcher. */ class CRPCTable { private: std::map<std::string, const CRPCCommand*> mapCommands; public: CRPCTable(); const CRPCCommand* operator[](std::string name) const; std::string help(std::string name) const; /** * Execute a method. * @param method Method to execute * @param params Array of arguments (JSON objects) * @returns Result of the call. * @throws an exception (json_spirit::Value) when an error happens. */ json_spirit::Value execute(const std::string &method, const json_spirit::Array &params) const; }; extern const CRPCTable tableRPC; extern void InitRPCMining(); extern void ShutdownRPCMining(); extern int64_t nWalletUnlockTime; extern int64_t AmountFromValue(const json_spirit::Value& value); extern json_spirit::Value ValueFromAmount(int64_t amount); extern double GetDifficulty(const CBlockIndex* blockindex = NULL); extern double GetPoWMHashPS(); extern double GetPoSKernelPS(); extern std::string HelpRequiringPassphrase(); extern void EnsureWalletIsUnlocked(); // // Utilities: convert hex-encoded Values // (throws error if not hex). // extern uint256 ParseHashV(const json_spirit::Value& v, std::string strName); extern uint256 ParseHashO(const json_spirit::Object& o, std::string strKey); extern std::vector<unsigned char> ParseHexV(const json_spirit::Value& v, std::string strName); extern std::vector<unsigned char> ParseHexO(const json_spirit::Object& o, std::string strKey); extern json_spirit::Value getconnectioncount(const json_spirit::Array& params, bool fHelp); // in rpcnet.cpp extern json_spirit::Value getpeerinfo(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value ping(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value addnode(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getaddednodeinfo(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getnettotals(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value dumpwallet(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value importwallet(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value dumpprivkey(const json_spirit::Array& params, bool fHelp); // in rpcdump.cpp extern json_spirit::Value importprivkey(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value sendalert(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getsubsidy(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getstakesubsidy(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getmininginfo(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getstakinginfo(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value checkkernel(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getwork(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getworkex(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getblocktemplate(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value submitblock(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getnewaddress(const json_spirit::Array& params, bool fHelp); // in rpcwallet.cpp extern json_spirit::Value getaccountaddress(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value setaccount(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getaccount(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getaddressesbyaccount(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value sendtoaddress(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value signmessage(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value verifymessage(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getreceivedbyaddress(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getreceivedbyaccount(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getbalance(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value movecmd(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value sendfrom(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value sendmany(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value addmultisigaddress(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value addredeemscript(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value listreceivedbyaddress(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value listreceivedbyaccount(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value listtransactions(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value listaddressgroupings(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value listaccounts(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value listsinceblock(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value gettransaction(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value backupwallet(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value keypoolrefill(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value walletpassphrase(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value walletpassphrasechange(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value walletlock(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value encryptwallet(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value validateaddress(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getinfo(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value reservebalance(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value checkwallet(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value repairwallet(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value resendtx(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value makekeypair(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value validatepubkey(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getnewpubkey(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getrawtransaction(const json_spirit::Array& params, bool fHelp); // in rcprawtransaction.cpp extern json_spirit::Value searchrawtransactions(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value listunspent(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value createrawtransaction(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value decoderawtransaction(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value decodescript(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value signrawtransaction(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value sendrawtransaction(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getbestblockhash(const json_spirit::Array& params, bool fHelp); // in rpcblockchain.cpp extern json_spirit::Value getblockcount(const json_spirit::Array& params, bool fHelp); // in rpcblockchain.cpp extern json_spirit::Value getdifficulty(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value settxfee(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getrawmempool(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getblockhash(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getblock(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getblockbynumber(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getcheckpoint(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getnewstealthaddress(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value liststealthaddresses(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value importstealthaddress(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value sendtostealthaddress(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value darksend(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value spork(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value masternode(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value smsgenable(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value smsgdisable(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value smsglocalkeys(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value smsgoptions(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value smsgscanchain(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value smsgscanbuckets(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value smsgaddkey(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value smsggetpubkey(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value smsgsend(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value smsgsendanon(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value smsginbox(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value smsgoutbox(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value smsgbuckets(const json_spirit::Array& params, bool fHelp); #endif
a4510aaab4eae72a02ec0a5f80c088be33074040
d1841f83cacc5dd71971a8ebfa4c1e08421b3d07
/MissionaryAndCarnivals/MissionaryAndCarnivals/Harbor.cpp
8f459cea0acaa8828738c84353f947a34fcc4fa7
[]
no_license
dennischa/Articial_Intelligence2016
c91c54edddf17cc8af619fe09e13b57128758a31
f5db5df96d6442c7ab5312c5b36d2860ab0216b8
refs/heads/master
2021-01-11T03:38:36.009190
2016-10-04T20:25:34
2016-10-04T20:25:34
69,971,413
0
0
null
null
null
null
UTF-8
C++
false
false
1,292
cpp
#include <iostream> #include <cmath> using namespace std; enum Direction { Left, Right }; struct Move { int changeOfm, changeOfc; }; class Harbor{ public: int left_m, right_m; int left_c, right_c; Direction dir; int g = 0; int h = 0; Move p[5] = { { 1,1 },{ 1,0 },{ 0,1 },{ 2,0 }, (0,2) }; Harbor(int lm,int lc,int rm,int rc,Direction d) { left_m = lm; left_c = lc; right_m = rm; right_c = rc; dir = d; } Harbor(const Harbor& com) { left_m = com.left_m; left_c = com.left_c; right_m = com.right_m; right_c = com.right_c; dir = com.dir; g = com.g; } // d = left or right, n = 0~4; Harbor move_Harbor(Direction d, int n) { Harbor tmp(*this); tmp.g = tmp.g + 1; Move m = p[n]; if (d == Right) { tmp.left_m -= m.changeOfm; tmp.left_c -= m.changeOfc; tmp.right_m += m.changeOfm; tmp.right_c += m.changeOfc; tmp.dir = Left; } else { tmp.left_m += m.changeOfm; tmp.left_c += m.changeOfc; tmp.right_m -= m.changeOfm; tmp.right_c -= m.changeOfc; tmp.dir = Right; } return tmp; } int heuristic(Harbor goal) { return abs(right_c - goal.right_c) + abs(right_m - goal.right_m); } bool checkDeadEnd() { if (left_m < left_c || right_m < right_c) return true; else return false; } };
fc2607868b405b14d495adee78323f9ba9048fd2
e8282e3ae8aafa07b7f7261c639f206c4e97e0fc
/03 - Online Judges/codeforces/amusingjoke.cpp
b4e96e05ed99b6d8c8210e8d0473f6f55aa42fa1
[]
no_license
irfansofyana/cp-codes
7cad844da49b901ccf678b75c31ed41e2fa9d645
9fa723129088f0e4832ecb7e012fe586b6d59e41
refs/heads/master
2023-04-04T00:48:36.334817
2021-04-12T03:07:06
2021-04-12T03:07:06
218,084,148
0
0
null
null
null
null
UTF-8
C++
false
false
592
cpp
#include <bits/stdc++.h> using namespace std; int main(){ string s1,s2,s3,s4; int n,i,j,min; char temp; cin>>s1; cin>>s2; cin>>s3; s4=s1+s2; for (i=0;i<=s4.length()-1;i++) { min=i; for (j=i+1;j<=s4.length();j++) if (s4[j]<s4[min]) min=j; temp=s4[i]; s4[i]=s4[min]; s4[min]=temp; } for (i=0;i<=s3.length()-1;i++) { min=i; for (j=i+1;j<=s3.length();j++) if (s3[j]<s3[min]) min=j; temp=s3[i]; s3[i]=s3[min]; s3[min]=temp; } if (s4==s3) printf("YES\n"); else printf("NO\n"); return 0; }
f18b67e764d6c812161533ee4a13926ed6a23152
a97425689712304c84a70ae1ceac1ed32ce9230f
/src/LRUCache.cc
c35e73eab82783f1c1465f9eccb3bce90a2bbd0a
[ "MIT" ]
permissive
joaquimserafim/node-lru-native
77dbd1354296595402166d9a87b9ca1bc1e25c46
fab17e20bfc686fcb3c831e1ae20d9aab30a0772
refs/heads/master
2020-12-28T21:50:47.962330
2013-08-27T17:48:28
2013-08-27T17:48:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,295
cc
#include "LRUCache.h" #include <sys/time.h> #include <math.h> #ifndef __APPLE__ #include <unordered_map> #endif using namespace v8; unsigned long getCurrentTime() { timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec * 1000 + tv.tv_usec / 1000; } std::string getStringValue(Handle<Value> value) { String::Utf8Value keyUtf8Value(value); return std::string(*keyUtf8Value); } void LRUCache::init(Handle<Object> exports) { Local<String> className = String::NewSymbol("LRUCache"); Local<FunctionTemplate> constructor = FunctionTemplate::New(New); constructor->SetClassName(className); Handle<ObjectTemplate> instance = constructor->InstanceTemplate(); instance->SetInternalFieldCount(6); Handle<ObjectTemplate> prototype = constructor->PrototypeTemplate(); prototype->Set("get", FunctionTemplate::New(Get)->GetFunction()); prototype->Set("set", FunctionTemplate::New(Set)->GetFunction()); prototype->Set("remove", FunctionTemplate::New(Remove)->GetFunction()); prototype->Set("clear", FunctionTemplate::New(Clear)->GetFunction()); prototype->Set("size", FunctionTemplate::New(Size)->GetFunction()); prototype->Set("stats", FunctionTemplate::New(Stats)->GetFunction()); exports->Set(className, Persistent<Function>::New(constructor->GetFunction())); } Handle<Value> LRUCache::New(const Arguments& args) { LRUCache* cache = new LRUCache(); if (args.Length() > 0 && args[0]->IsObject()) { Local<Object> config = args[0]->ToObject(); Local<Value> maxElements = config->Get(String::NewSymbol("maxElements")); if (maxElements->IsUint32()) cache->maxElements = maxElements->Uint32Value(); Local<Value> maxAge = config->Get(String::NewSymbol("maxAge")); if (maxAge->IsUint32()) cache->maxAge = maxAge->Uint32Value(); Local<Value> maxLoadFactor = config->Get(String::NewSymbol("maxLoadFactor")); if (maxLoadFactor->IsNumber()) cache->data.max_load_factor(maxLoadFactor->NumberValue()); Local<Value> size = config->Get(String::NewSymbol("size")); if (size->IsUint32()) cache->data.rehash(ceil(size->Uint32Value() / cache->data.max_load_factor())); } cache->Wrap(args.This()); return args.This(); } LRUCache::LRUCache() { this->maxElements = 0; this->maxAge = 0; } LRUCache::~LRUCache() { this->disposeAll(); } void LRUCache::disposeAll() { for (HashMap::iterator itr = this->data.begin(); itr != this->data.end(); itr++) { HashEntry* entry = itr->second; entry->value.Dispose(); delete entry; } } void LRUCache::evict() { const HashMap::iterator itr = this->data.find(this->lru.front()); if (itr == this->data.end()) return; HashEntry* entry = itr->second; // Dispose the V8 handle contained in the entry. entry->value.Dispose(); // Remove the entry from the hash and from the LRU list. this->data.erase(itr); this->lru.pop_front(); // Free the entry itself. delete entry; } void LRUCache::remove(const HashMap::const_iterator itr) { HashEntry* entry = itr->second; // Dispose the V8 handle contained in the entry. entry->value.Dispose(); // Remove the entry from the hash and from the LRU list. this->data.erase(itr); this->lru.erase(entry->pointer); // Free the entry itself. delete entry; } Handle<Value> LRUCache::Get(const Arguments& args) { HandleScope scope; LRUCache* cache = ObjectWrap::Unwrap<LRUCache>(args.This()); if (args.Length() != 1) return ThrowException(Exception::RangeError(String::New("Incorrect number of arguments for get(), expected 1"))); std::string key = getStringValue(args[0]); const HashMap::const_iterator itr = cache->data.find(key); // If the specified entry doesn't exist, return undefined. if (itr == cache->data.end()) return scope.Close(Handle<Value>()); HashEntry* entry = itr->second; if (cache->maxAge > 0 && getCurrentTime() - entry->timestamp > cache->maxAge) { // The entry has passed the maximum age, so we need to remove it. cache->remove(itr); // Return undefined. return scope.Close(Handle<Value>()); } else { // Move the value to the end of the LRU list. cache->lru.splice(cache->lru.end(), cache->lru, entry->pointer); // Return the value. return scope.Close(entry->value); } } Handle<Value> LRUCache::Set(const Arguments& args) { HandleScope scope; LRUCache* cache = ObjectWrap::Unwrap<LRUCache>(args.This()); unsigned long now = cache->maxAge == 0 ? 0 : getCurrentTime(); if (args.Length() != 2) return ThrowException(Exception::RangeError(String::New("Incorrect number of arguments for set(), expected 2"))); std::string key = getStringValue(args[0]); Local<Value> value = args[1]; const HashMap::iterator itr = cache->data.find(key); if (itr == cache->data.end()) { // We're adding a new item. First ensure we have space. if (cache->maxElements > 0 && cache->data.size() == cache->maxElements) cache->evict(); // Add the value to the end of the LRU list. KeyList::iterator pointer = cache->lru.insert(cache->lru.end(), key); // Add the entry to the key-value map. HashEntry* entry = new HashEntry(Persistent<Value>::New(value), pointer, now); cache->data.insert(std::make_pair(key, entry)); } else { HashEntry* entry = itr->second; // We're replacing an existing value, so dispose the old V8 handle to ensure it gets GC'd. entry->value.Dispose(); // Replace the value in the key-value map with the new one, and update the timestamp. entry->value = Persistent<Value>::New(value); entry->timestamp = now; // Move the value to the end of the LRU list. cache->lru.splice(cache->lru.end(), cache->lru, entry->pointer); } // Return undefined. return scope.Close(Handle<Value>()); } Handle<Value> LRUCache::Remove(const Arguments& args) { HandleScope scope; LRUCache* cache = ObjectWrap::Unwrap<LRUCache>(args.This()); if (args.Length() != 1) return ThrowException(Exception::RangeError(String::New("Incorrect number of arguments for remove(), expected 1"))); std::string key = getStringValue(args[0]); const HashMap::iterator itr = cache->data.find(key); if (itr != cache->data.end()) cache->remove(itr); return scope.Close(Handle<Value>()); } Handle<Value> LRUCache::Clear(const Arguments& args) { HandleScope scope; LRUCache* cache = ObjectWrap::Unwrap<LRUCache>(args.This()); cache->disposeAll(); cache->data.clear(); cache->lru.clear(); return scope.Close(Handle<Value>()); } Handle<Value> LRUCache::Size(const Arguments& args) { HandleScope scope; LRUCache* cache = ObjectWrap::Unwrap<LRUCache>(args.This()); return scope.Close(Integer::New(cache->data.size())); } Handle<Value> LRUCache::Stats(const Arguments& args) { HandleScope scope; LRUCache* cache = ObjectWrap::Unwrap<LRUCache>(args.This()); Local<Object> stats = Object::New(); stats->Set(String::NewSymbol("size"), Integer::New(cache->data.size())); stats->Set(String::NewSymbol("buckets"), Integer::New(cache->data.bucket_count())); stats->Set(String::NewSymbol("loadFactor"), Number::New(cache->data.load_factor())); stats->Set(String::NewSymbol("maxLoadFactor"), Number::New(cache->data.max_load_factor())); return scope.Close(stats); }
a07efdec6573ce7e8f0b765e6a9865b3f4a3698f
6d2b51b9b35bd954ee4c19181d05b74f60238c28
/ArduinoSer2FastLED/ArduinoSer2FastLED.ino
3ef1d04be570e105f0d0fe569162add4de7f0ae5
[ "MIT" ]
permissive
JoshuaBThompson/lamatrix
77ccdfcd0c11d5a4b6db9d994137bf5ae788ef1f
8d28473d5242afe6ea4e66579fae02543d2e9851
refs/heads/master
2023-04-19T05:03:43.285393
2021-04-25T07:52:07
2021-04-25T07:52:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,962
ino
/** * Firmware to control a LED matrix display * https://github.com/noahwilliamsson/lamatrix * * -- [email protected], 2018 * */ #ifdef TEENSYDUINO #include <TimeLib.h> #endif #include "FastLED.h" #define HOST_SHUTDOWN_PIN 8 #define LEFT_BUTTON_PIN 9 #define RIGHT_BUTTON_PIN 10 #define NUM_LEDS 256 #ifdef TEENSYDUINO #define FastLED_Pin 6 #else #define FastLED_Pin 22 #endif static void put_pixel(int, int, int); static void render_clock(int); #ifdef TEENSYDUINO static time_t getTeensy3Time(); #endif /** * Serial protocol */ enum { FUNC_RESET = 0, /* Initialize display with [pixels & 0xff, (pixels>>8) & 0xff] LEDs */ FUNC_INIT_DISPLAY = 'i', /* Clear display: [dummy byte] */ FUNC_CLEAR_DISPLAY = 'c', /* Update display: [dummy byte] */ FUNC_SHOW_DISPLAY = 's', /* Put pixel at [pixel&0ff, (pixel >> 8) &0xff, R, G, B] */ FUNC_PUT_PIXEL = 'l', /* Set time [t&0xff, (t >> 8) & 0xff, (t >> 16) & 0xff, (t >> 24) & 0xff] */ FUNC_SET_RTC = '@', /* Automatically render time [enable/toggle byte] */ FUNC_AUTO_TIME = 't', /* Suspend host for [seconds & 0xff, (seconds >> 8) & 0xff] */ FUNC_SUSPEND_HOST = 'S', }; /* Computed with pixelfont.py */ static int font_width = 4; static int font_height = 5; static char font_alphabet[] = " %'-./0123456789:?acdefgiklmnoprstwxy"; static unsigned char font_data[] = "\x00\x00\x50\x24\x51\x66\x00\x00\x60\x00\x00\x00\x42\x24\x11\x57\x55\x27\x23\x72\x47\x17\x77\x64\x74\x55\x47\x74\x71\x74\x17\x57\x77\x44\x44\x57\x57\x77\x75\x74\x20\x20\x30\x24\x20\x52\x57\x25\x15\x25\x53\x55\x73\x31\x71\x17\x13\x71\x71\x75\x27\x22\x57\x35\x55\x11\x11\x57\x77\x55\x75\x77\x75\x55\x75\x57\x17\x71\x35\x55\x17\x47\x77\x22\x22\x55\x77\x55\x25\x55\x55\x27\x02"; /* Global states */ int state = 0; int debug_serial = 0; /* Debug state issues */ int last_states[8]; unsigned int last_state_counter = 0; /* Non-zero when automatically rendering the current time */ int show_time = 1; /* Non-zero while the host computer is turned off */ time_t reboot_at = 0; /* Accumulator register for use between loop() calls */ unsigned int acc; unsigned int color; CRGB leds[NUM_LEDS]; static volatile int g_button_state; static int button_down_t; static void button_irq_left(void) { int state = digitalRead(LEFT_BUTTON_PIN); if(state == HIGH) { /* Start counting when the circuit is broken */ button_down_t = millis(); return; } if(!button_down_t) return; int pressed_for_ms = millis() - button_down_t; if(pressed_for_ms > 1500) g_button_state = 4; else if(pressed_for_ms > 500) g_button_state = 2; else if(pressed_for_ms > 100) g_button_state = 1; button_down_t = 0; } static void button_irq_right(void) { int state = digitalRead(RIGHT_BUTTON_PIN); if(state == HIGH) { /* Start counting when the circuit is broken */ button_down_t = millis(); return; } if(!button_down_t) return; int pressed_for_ms = millis() - button_down_t; if(pressed_for_ms > 1500) g_button_state = 64; else if(pressed_for_ms > 500) g_button_state = 32; else if(pressed_for_ms > 100) g_button_state = 16; button_down_t = 0; } void setup() { Serial.begin(460800); /* Initialize FastLED library */ FastLED.addLeds<NEOPIXEL, FastLED_Pin>(leds, NUM_LEDS); /* Configure pin used to shutdown Raspberry Pi (connected to GPIO5 on the Pi) */ pinMode(HOST_SHUTDOWN_PIN, OUTPUT); digitalWrite(HOST_SHUTDOWN_PIN, HIGH); /* Configure pins for the buttons */ pinMode(LEFT_BUTTON_PIN, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(LEFT_BUTTON_PIN), button_irq_left, CHANGE); pinMode(RIGHT_BUTTON_PIN, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(RIGHT_BUTTON_PIN), button_irq_right, CHANGE); #ifdef TEENSYDUINO /* Initialize time library */ setSyncProvider(getTeensy3Time); if (timeStatus() != timeSet) { Serial.println("Unable to sync with the RTC"); } else { Serial.println("RTC has set the system time"); show_time = 1; } Serial.printf("%04d-%02d-%02dT%02d:%02d:%02dZ\n", year(), month(), day(), hour(), minute(), second()); #endif } void loop() { #ifdef TEENSYDUINO time_t now = getTeensy3Time(); #else int now = 0; #endif int button_state = g_button_state; if(button_state) { g_button_state = 0; if(button_state & 1) Serial.println("LEFT_SHRT_PRESS"); else if(button_state & 2) Serial.println("LEFT_LONG_PRESS"); else if(button_state & 4) Serial.println("LEFT_HOLD_PRESS"); if(button_state & 16) Serial.println("RGHT_SHRT_PRESS"); else if(button_state & 32) Serial.println("RGHT_LONG_PRESS"); else if(button_state & 64) Serial.println("RGHT_HOLD_PRESS"); } if(reboot_at && now >= reboot_at) { /* Restart host computer */ digitalWrite(HOST_SHUTDOWN_PIN, LOW); delay(1); digitalWrite(HOST_SHUTDOWN_PIN, HIGH); reboot_at = 0; } if(show_time) { /* Automatically render time */ if(show_time != now || button_state) { render_clock(button_state); show_time = now; } } if (Serial.available() <= 0) return; int val = Serial.read(); last_states[last_state_counter++ % (sizeof(last_states)/sizeof(last_states[0]))] = val; switch(state) { case FUNC_RESET: /** * Pyserial sometimes experience write timeouts so we * use a string of zeroes to resynchronize the state. */ state = val; break; case FUNC_INIT_DISPLAY: acc = val; state++; break; case FUNC_INIT_DISPLAY+1: acc |= val << 8; FastLED.addLeds<NEOPIXEL, FastLED_Pin>(leds, acc); /* fall through */ case FUNC_SET_RTC: acc = val; state++; break; case FUNC_SET_RTC+1: acc |= val << 8; state++; break; case FUNC_SET_RTC+2: acc |= val << 16; state++; break; case FUNC_SET_RTC+3: acc |= val << 24; #ifdef TEENSYDUINO Teensy3Clock.set(acc); // set the RTC setTime(acc); Serial.printf("RTC synchronized: %04d-%02d-%02dT%02d:%02d:%02dZ\n", year(), month(), day(), hour(), minute(), second()); #endif state = FUNC_RESET; break; case FUNC_CLEAR_DISPLAY: for(int i = 0; i < NUM_LEDS; i++) leds[i].setRGB(0,0,0); /* fall through */ case FUNC_SHOW_DISPLAY: FastLED.show(); state = FUNC_RESET; break; case FUNC_SUSPEND_HOST: acc = val; state++; break; case FUNC_SUSPEND_HOST+1: acc |= val << 8; /* TODO: Suspend host computer */ reboot_at = now + acc; if(reboot_at >= 10) { /* Automatically render time while host computer is offline */ show_time = 1; Serial.printf("Shutting down host computer, reboot scheduled in %ds\n", reboot_at); /* Initiate poweroff on Raspberry Pi */ digitalWrite(HOST_SHUTDOWN_PIN, LOW); delay(1); digitalWrite(HOST_SHUTDOWN_PIN, HIGH); } state = FUNC_RESET; break; case FUNC_AUTO_TIME: if(val == '\r' || val == '\n') show_time = !show_time; /* toggle */ else show_time = val; /* Clear display */ for(int i = 0; i < NUM_LEDS; i++) leds[i].setRGB(0,0,0); FastLED.show(); Serial.printf("Automatic rendering of current time: %d\n", show_time); state = FUNC_RESET; break; case FUNC_PUT_PIXEL: acc = val; state++; break; case FUNC_PUT_PIXEL+1: acc |= val << 8; state++; break; case FUNC_PUT_PIXEL+2: color = val; state++; break; case FUNC_PUT_PIXEL+3: color |= val << 8; state++; break; case FUNC_PUT_PIXEL+4: color |= val << 16; leds[(acc % NUM_LEDS)].setRGB(color & 0xff, (color >> 8) & 0xff, (color >> 16) & 0xff); state = FUNC_RESET; break; default: Serial.printf("Unknown func %d with val %d, resetting\n", state, val); for(unsigned int i = 0; i < sizeof(last_states)/sizeof(last_states[0]) && last_state_counter - i > 0; i++) Serial.printf("Previous state %d: %d\n", i, last_states[(last_state_counter-i) % (sizeof(last_states)/sizeof(last_states[0]))]); state = FUNC_RESET; break; } } /* Pretty much a port of LedMatrix.xy_to_phys() */ static void put_pixel(int x, int y, int lit) { /** * The LEDs are laid out in a long string going from north to south, * one step to the east, and then south to north, before the cycle * starts over */ int cycle = 16; int nssn_block = x / 2; int phys_addr = nssn_block * 16; int brightness_scaler = 48; /* use less power */ if(x % 2) phys_addr += cycle - 1 - y; else phys_addr += y; lit &= 0xff; lit /= brightness_scaler; leds[phys_addr % NUM_LEDS].setRGB(lit, lit, lit); } #ifdef TEENSYDUINO /* Wrapper function for Timelib's sync provider */ static time_t getTeensy3Time(void) { return Teensy3Clock.get(); } #endif /* Render time as reported by the RTC */ static int clock_state = 0x2; static void render_clock(int button_state) { char buf[10]; int x_off; size_t len; if(button_state) { clock_state ^= 1 << (button_state-1); for(int i = 0; i < NUM_LEDS; i++) leds[i].setRGB(0,0,0); } #ifdef TEENSYDUINO if((clock_state & 1) == 0) { sprintf(buf, "%02d:%02d", hour(), minute()); if((clock_state & 2) && second() % 2) buf[2] = ' '; } else { sprintf(buf, "%02d.%02d.%02d", day(), month(), year() % 100); } #else sprintf(buf, "00:00"); #endif if((clock_state & 1) == 0) x_off = 8 - clock_state; else x_off = 2; len = strlen(buf); for(size_t i = 0; i < len; i++) { unsigned char digit = buf[i]; size_t offset; /* Kludge to compress colons and dots to two columns */ if(digit == ':' || digit == '.' || digit == ' ' || (i && (buf[i-1] == ':' || buf[i-1] == '.' || buf[i-1] == ' '))) x_off--; for(offset = 0; offset < strlen(font_alphabet); offset++) { if(font_alphabet[offset] == digit) break; } int font_byte = (offset * font_width * font_height) / 8; int font_bit = (offset * font_width * font_height) % 8; for(int y = 0; y < font_height; y++) { for(int x = 0; x < font_width; x++) { if(font_data[font_byte] & (1<<font_bit)) put_pixel(x_off+x, y, 255); else put_pixel(x_off+x, y, 0); if(++font_bit == 8) { font_byte++; font_bit = 0; } } } x_off += font_width; } #ifdef TEENSYDUINO /* Display seconds bar */ if(clock_state == 2) { int height = 1 + second() / 12; for(int y = 0; y < 5; y++) { int color = 0; if(y < height) color = 128; if(y == height-1 && second() % 2) color = 0; put_pixel(x_off+1, 4-y, color); } } /* Display weekdays */ x_off = 2; int today_to_i = (weekday() + 5) % 7; for(int i = 0; i < 7; i++) { int color = i == today_to_i? 255: 64; put_pixel(x_off+4*i+0, 7, color); put_pixel(x_off+4*i+1, 7, color); put_pixel(x_off+4*i+2, 7, color); } #endif FastLED.show(); }
ba857dbe1a24c550d0216fb634cc73bbb9388d0a
a913bf77fd3f1a93766b2b0b4c9e9bf3858b15fb
/src/CameraManager.h
a830c162d2bacabfa8d66ff8a7d33e498065740e
[]
no_license
movezig5/GAM-475-Engine
bb36fb29e3fcea6899f8e97132862c9e994d357c
f2a7d305bdc4e996a90980bff842266892fb0966
refs/heads/master
2020-04-11T01:59:58.399267
2018-12-12T04:33:08
2018-12-12T04:33:08
161,432,526
0
0
null
null
null
null
UTF-8
C++
false
false
509
h
#ifndef CAMERA_MANAGER_H #define CAMERA_MANAGER_H #include "Camera.h" // Singleton class CameraManager { public: static void Add(Camera *pCam); static void Remove(Camera *pCam); static void RemoveAll(); static void Update(); static Camera *getActiveCam(); static Camera *getFirst(); static void setActiveCam(Camera *pCam); static void next(); static void prev(); private: CameraManager(); static CameraManager *privGetInstance(); Camera *pHead; Camera *pTail; Camera *pActiveCam; }; #endif
fb1bb7073259074c8bb57e7d3b75579efedcc9fa
cc2f94ed6006343f743fc6d33aeb4169b24b7368
/src/mangosd/Main.cpp
60acc6ae6094c9ecc662fde7dbabe4b30bc02312
[]
no_license
MichaelFurth/RCore
054711f1298e2f9ea5480e245a4cb1a8b2d0bae6
2699829b9df90df8116ebb1506cba0596bc21be5
refs/heads/master
2021-01-25T12:02:38.746951
2010-12-28T04:53:10
2010-12-28T04:53:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,331
cpp
/* * Copyright (C) 2005-2010 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /// \addtogroup mangosd Mangos Daemon /// @{ /// \file #include "Common.h" #include "Database/DatabaseEnv.h" #include "Config/Config.h" #include "Log.h" #include "Master.h" #include "SystemConfig.h" #include "revision.h" #include "revision_nr.h" #include <openssl/opensslv.h> #include <openssl/crypto.h> #include <ace/Version.h> #include <ace/Get_Opt.h> #ifdef WIN32 #include "ServiceWin32.h" char serviceName[] = "mangosd"; char serviceLongName[] = "MaNGOS world service"; char serviceDescription[] = "Massive Network Game Object Server"; /* * -1 - not in service mode * 0 - stopped * 1 - running * 2 - paused */ int m_ServiceStatus = -1; #endif DatabaseType WorldDatabase; ///< Accessor to the world database DatabaseType CharacterDatabase; ///< Accessor to the character database DatabaseType LoginDatabase; ///< Accessor to the realm/login database uint32 realmID; ///< Id of the realm /// Print out the usage string for this program on the console. void usage(const char *prog) { sLog.outString("Usage: \n %s [<options>]\n" " -v, --version print version and exist\n\r" " -c config_file use config_file as configuration file\n\r" #ifdef WIN32 " Running as service functions:\n\r" " -s run run as service\n\r" " -s install install service\n\r" " -s uninstall uninstall service\n\r" #endif ,prog); } /// Launch the mangos server extern int main(int argc, char **argv) { // - Construct Memory Manager Instance MaNGOS::Singleton<MemoryManager>::Instance(); //char *leak = new char[1000]; // test leak detection ///- Command line parsing char const* cfg_file = _MANGOSD_CONFIG; #ifdef WIN32 char const *options = ":c:s:"; #else char const *options = ":c:"; #endif ACE_Get_Opt cmd_opts(argc, argv, options); cmd_opts.long_option("version", 'v'); int option; while ((option = cmd_opts()) != EOF) { switch (option) { case 'c': cfg_file = cmd_opts.opt_arg(); break; case 'v': printf("%s\n", _FULLVERSION(REVISION_DATE,REVISION_TIME,REVISION_NR,REVISION_ID)); return 0; #ifdef WIN32 case 's': { const char *mode = cmd_opts.opt_arg(); if (!strcmp(mode, "install")) { if (WinServiceInstall()) sLog.outString("Installing service"); return 1; } else if (!strcmp(mode, "uninstall")) { if (WinServiceUninstall()) sLog.outString("Uninstalling service"); return 1; } else if (!strcmp(mode, "run")) WinServiceRun(); else { sLog.outError("Runtime-Error: -%c unsupported argument %s", cmd_opts.opt_opt(), mode); usage(argv[0]); Log::WaitBeforeContinueIfNeed(); return 1; } break; } #endif case ':': sLog.outError("Runtime-Error: -%c option requires an input argument", cmd_opts.opt_opt()); usage(argv[0]); Log::WaitBeforeContinueIfNeed(); return 1; default: sLog.outError("Runtime-Error: bad format of commandline arguments"); usage(argv[0]); Log::WaitBeforeContinueIfNeed(); return 1; } } if (!sConfig.SetSource(cfg_file)) { sLog.outError("Could not find configuration file %s.", cfg_file); Log::WaitBeforeContinueIfNeed(); return 1; } sLog.outString( "%s [world-daemon]", _FULLVERSION(REVISION_DATE,REVISION_TIME,REVISION_NR,REVISION_ID) ); sLog.outString( "<Ctrl-C> to stop.\n\n" ); sLog.outTitle( "XXXXXXXXXXXXXXXX "); sLog.outTitle( "XXXXXXXXXXXXXXXXXx "); sLog.outTitle( "IXXXxxxxxxxxxxxxxxx "); sLog.outTitle( "IXX xxxx "); sLog.outTitle( "IXX. xXX "); sLog.outTitle( "IXX xXX "); sLog.outTitle( "IXX xXX "); sLog.outTitle( "IXX xXX "); sLog.outTitle( "IXX xXX "); sLog.outTitle( "IXX xXX "); sLog.outTitle( "IXX xXX "); sLog.outTitle( "IXX xXX "); sLog.outTitle( "IXXXXXXXXXXXXXXXXXxXX "); sLog.outTitle( "IXXXXXXXXXXXXXXXXXXXX "); sLog.outTitle( "IXXXXXXXXXXXXXXXXXXXX "); sLog.outTitle( "IXXx xxxXX "); sLog.outTitle( "IXXX xxxXX "); sLog.outTitle( "IXXX xXX "); sLog.outTitle( "IXXX xXX "); sLog.outTitle( "IXXX xXXZ Xxx xxX Xxx xxX "); sLog.outTitle( "IXXX xXXZ XXXx xXXX XxxxxX XXXx xXXX "); sLog.outTitle( "IXXX xXXZZ XXx xx xXX XXxxxxXX XXx xx xXX "); sLog.outTitle( "IXXX xXXZZZ XXx xx xXX XX XX XXx xx xXX "); sLog.outTitle( "IXXX xxXXXZ XXx xx xXX XX XX XXx xx xXX "); sLog.outTitle( "XXXX xXXXXZ XXx xx xXX XX XX XXx xx xXX "); sLog.outTitle( "XXXXXXX xXXXXZZ XXxxxxxxxxXX XXxxxxXX XXxxxxxxxxXX "); sLog.outTitle( "XXXXXXX xXXXXZZ XXxXXXXXXxXX xxxxxx XXxXXXXXXxXX "); sLog.outString("Using configuration file %s.", cfg_file); DETAIL_LOG("%s (Library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION)); if (SSLeay() < 0x009080bfL ) { DETAIL_LOG("WARNING: Outdated version of OpenSSL lib. Logins to server may not work!"); DETAIL_LOG("WARNING: Minimal required version [OpenSSL 0.9.8k]"); } DETAIL_LOG("Using ACE: %s", ACE_VERSION); ///- and run the 'Master' /// \todo Why do we need this 'Master'? Can't all of this be in the Main as for Realmd? return sMaster.Run(); // at sMaster return function exist with codes // 0 - normal shutdown // 1 - shutdown at error // 2 - restart command used, this code can be used by restarter for restart mangosd } /// @}
461efbda075a4f9d773a8d99d88cd5e473a9f6ef
72f359a49c96d7cb72218780877af6d3cca319c5
/cfd_test/solverSOR.h
9a6278129db28adbccf3cd834c4b65e5d61b4006
[]
no_license
janvonrickenbach/Cfd_fundamentals
cb85bc55512772bc8ca6bdd50318ed2db5bf62ab
078c85887d2107d3cb7de8273d0c04d0de9e5e58
refs/heads/master
2020-12-24T15:22:45.559501
2014-05-14T23:02:11
2014-05-14T23:02:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
352
h
/* * solverSOR.h * * Created on: Apr 5, 2014 * Author: jan */ #ifndef SOLVERSOR_H_ #define SOLVERSOR_H_ #include "solver.h" class equation; class solverSOR: public solver { public: solverSOR(double tolerance,grid* grid, double omega); virtual int solve(); virtual ~solverSOR(); protected: double _omega; }; #endif /* SOLVERSOR_H_ */
[ "jan" ]
jan
96298460415b1deb62fd3b9395137ac251b251b5
f46514f494f27d071f812bc0f36dd37a2c2073d1
/src/ga1-core/graphics/ga_animation_component.cpp
d814f08f01dc273886b9621e88737c3fed22e5b9
[ "MIT" ]
permissive
Game-Architecture/final-repository-AnthonyVeschi
3bec2dce9e6b902de1a2f2df5dc369803abc414f
e2aaf6cba6d798df5de87b6432be1fc0762d9c98
refs/heads/main
2023-04-18T15:03:10.672014
2021-05-03T15:48:39
2021-05-03T15:48:39
361,569,047
0
0
null
null
null
null
UTF-8
C++
false
false
2,084
cpp
/* ** RPI Game Architecture Engine ** ** Portions adapted from: ** Viper Engine - Copyright (C) 2016 Velan Studios - All Rights Reserved ** ** This file is distributed under the MIT License. See LICENSE.txt. */ #include "ga_animation_component.h" #include "ga_animation.h" #include "ga_debug_geometry.h" #include "ga_geometry.h" #include "entity/ga_entity.h" #include <cassert> ga_animation_component::ga_animation_component(ga_entity* ent, ga_model* model) : ga_component(ent) { _skeleton = model->_skeleton; assert(_skeleton != 0); } ga_animation_component::~ga_animation_component() { _skeleton = 0; if (_playing) { delete _playing; } } void ga_animation_component::update(ga_frame_params* params) { if (_playing) { _playing->_time += std::chrono::duration_cast<std::chrono::milliseconds>(params->_delta_time); float local_time = (_playing->_time.count() % 1000) / 1000.0f; uint32_t frame = (uint32_t)(local_time * _playing->_animation->_rate); // Safety. frame = frame % _playing->_animation->_rate; // For now, no interpolation. Select the closest frame. for (uint32_t joint_index = 0; joint_index < _skeleton->_joints.size(); ++joint_index) { ga_joint* j = _skeleton->_joints[joint_index]; ga_mat4f parent_matrix; parent_matrix.make_identity(); if (j->_parent < INT_MAX) { parent_matrix = _skeleton->_joints[j->_parent]->_world; } j->_world = _playing->_animation->_poses[frame]._transforms[joint_index] * parent_matrix; j->_skin = j->_inv_bind * j->_world; #if DEBUG_DRAW_SKELETON ga_dynamic_drawcall drawcall; draw_debug_sphere(0.4f, j->_world * get_entity()->get_transform(), &drawcall); while (params->_dynamic_drawcall_lock.test_and_set(std::memory_order_acquire)) {} params->_dynamic_drawcalls.push_back(drawcall); params->_dynamic_drawcall_lock.clear(std::memory_order_release); #endif } } } void ga_animation_component::play(ga_animation* animation) { _playing = new ga_animation_playback(); _playing->_animation = animation; _playing->_time == std::chrono::milliseconds::zero(); }
[ "66690702+github-classroom[bot]@users.noreply.github.com" ]
66690702+github-classroom[bot]@users.noreply.github.com
deaee4bfd4d2300f2d1470992e4a9c0eeab409b6
c633b5e7517f24d56159bf1a3b827bb02f76301b
/src/app/jni/src/Decoder.h
a702d51ae895d92c383a56683ec88f14da2fe546
[ "BSD-2-Clause" ]
permissive
Helios-vmg/CopperRat
cd6b98c55febc1135096da1e4e99476a4a7768a4
86722197cb4c8732848c132e855c2b206c2e86de
refs/heads/master
2021-07-24T12:57:32.041297
2021-04-04T05:15:18
2021-04-04T05:15:18
19,263,286
3
1
null
null
null
null
UTF-8
C++
false
false
2,723
h
/* Copyright (c), Helios All rights reserved. Distributed under a permissive license. See COPYING.txt for details. */ #pragma once #include "AudioTypes.h" #include "Metadata.h" #include "AudioBuffer.h" #include "Exception.h" #include "CommonFunctions.h" #ifndef HAVE_PRECOMPILED_HEADERS #include <limits> #endif class AudioStream; class Decoder{ audio_position_t current_position; audio_position_t length; double seconds_length; protected: AudioStream &parent; std::wstring path; //OggMetadata metadata; virtual audio_buffer_t read_more_internal() = 0; virtual sample_count_t get_pcm_length_internal() = 0; virtual double get_seconds_length_internal() = 0; public: Decoder(AudioStream &parent, const std::wstring &path): parent(parent), //metadata(path), path(path), current_position(0), length(invalid_sample_count), seconds_length(-1){} virtual ~Decoder(){} virtual AudioFormat get_audio_format() const = 0; virtual bool lazy_filter_allocation(){ return 0; } audio_buffer_t read(); static Decoder *create(AudioStream &, const std::wstring &path); virtual bool seek(audio_position_t) = 0; virtual bool fast_seek(audio_position_t p, audio_position_t &new_position){ bool ret = this->seek(p); if (ret) new_position = p; return ret; } virtual bool fast_seek_seconds(double p, audio_position_t &new_position){ return 0; } sample_count_t get_pcm_length(){ if (this->length != invalid_sample_count) return this->length; return this->length = this->get_pcm_length_internal(); } double get_seconds_length(){ if (this->seconds_length >= 0) return this->seconds_length; return this->seconds_length = this->get_seconds_length_internal(); } virtual bool fast_seek_takes_seconds() const{ return 0; } }; class DecoderException : public CR_Exception{ public: DecoderException(const std::string &description): CR_Exception(description){} virtual ~DecoderException(){} virtual CR_Exception *clone() const{ return new CR_Exception(*this); } }; class DecoderInitializationException : public DecoderException{ public: DecoderInitializationException(const std::string &description): DecoderException(description){ } virtual CR_Exception *clone() const{ return new DecoderInitializationException(*this); } }; class FileNotFoundException : public DecoderInitializationException{ public: FileNotFoundException(const std::string &description): DecoderInitializationException("File not found: " + description){ } virtual CR_Exception *clone() const{ return new FileNotFoundException(*this); } }; void filter_list_by_supported_formats(std::vector<std::wstring> &dst, const std::vector<std::wstring> &src); bool format_is_supported(const std::wstring &);
bd579c0cba92e9b266ab80829108fe4c212431a6
41db71010ff664ecd163710019dde3db9d8e2e09
/thrift/lib/cpp2/async/RocketClientChannel.cpp
7af09610e292d618b295aca4602d8c6fcb0a370e
[ "Apache-2.0" ]
permissive
jahau/fbthrift
069c4203ccbe55f84b439b700f94cdd1f0d1311e
2c73323d9e31fc99ea7a3b73ce8a201b3b8715d0
refs/heads/master
2022-04-21T04:31:43.313556
2020-02-15T05:53:32
2020-02-15T05:55:05
240,657,490
1
0
null
2020-02-15T06:37:02
2020-02-15T06:37:01
null
UTF-8
C++
false
false
17,146
cpp
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thrift/lib/cpp2/async/RocketClientChannel.h> #include <memory> #include <utility> #include <folly/ExceptionString.h> #include <folly/GLog.h> #include <folly/Likely.h> #include <folly/Memory.h> #include <folly/Try.h> #include <folly/compression/Compression.h> #include <folly/fibers/FiberManager.h> #include <folly/io/IOBuf.h> #include <folly/io/IOBufQueue.h> #include <folly/io/async/AsyncTransport.h> #include <folly/io/async/EventBase.h> #include <folly/io/async/Request.h> #include <thrift/lib/cpp/transport/THeader.h> #include <thrift/lib/cpp2/async/HeaderChannel.h> #include <thrift/lib/cpp2/async/RequestChannel.h> #include <thrift/lib/cpp2/async/ResponseChannel.h> #include <thrift/lib/cpp2/protocol/CompactProtocol.h> #include <thrift/lib/cpp2/transport/core/EnvelopeUtil.h> #include <thrift/lib/cpp2/transport/core/RpcMetadataUtil.h> #include <thrift/lib/cpp2/transport/core/ThriftClientCallback.h> #include <thrift/lib/cpp2/transport/core/TryUtil.h> #include <thrift/lib/cpp2/transport/rocket/PayloadUtils.h> #include <thrift/lib/cpp2/transport/rocket/RocketException.h> #include <thrift/lib/cpp2/transport/rocket/client/RocketClient.h> #include <thrift/lib/cpp2/transport/rocket/client/RocketClientWriteCallback.h> #include <thrift/lib/cpp2/transport/rsocket/YarplStreamImpl.h> #include <thrift/lib/thrift/gen-cpp2/RpcMetadata_types.h> using namespace apache::thrift::transport; namespace apache { namespace thrift { namespace { class OnWriteSuccess final : public rocket::RocketClientWriteCallback { public: explicit OnWriteSuccess(RequestClientCallback& requestCallback) : requestCallback_(requestCallback) {} void onWriteSuccess() noexcept override { requestCallback_.onRequestSent(); } private: RequestClientCallback& requestCallback_; }; void deserializeMetadata(ResponseRpcMetadata& dest, const rocket::Payload& p) { CompactProtocolReader reader; reader.setInput(p.buffer()); dest.read(&reader); if (reader.getCursorPosition() > p.metadataSize()) { folly::throw_exception<std::out_of_range>("underflow"); } } } // namespace rocket::SetupFrame RocketClientChannel::makeSetupFrame( RequestSetupMetadata meta) { CompactProtocolWriter compactProtocolWriter; folly::IOBufQueue paramQueue; compactProtocolWriter.setOutput(&paramQueue); meta.write(&compactProtocolWriter); // Serialize RocketClient's major/minor version (which is separate from the // rsocket protocol major/minor version) into setup metadata. auto buf = folly::IOBuf::createCombined( sizeof(int32_t) + meta.serializedSize(&compactProtocolWriter)); folly::IOBufQueue queue; queue.append(std::move(buf)); folly::io::QueueAppender appender(&queue, /* do not grow */ 0); // Serialize RocketClient's major/minor version (which is separate from the // rsocket protocol major/minor version) into setup metadata. appender.writeBE<uint16_t>(0); // Thrift RocketClient major version appender.writeBE<uint16_t>(1); // Thrift RocketClient minor version // Append serialized setup parameters to setup frame metadata appender.insert(paramQueue.move()); return rocket::SetupFrame( rocket::Payload::makeFromMetadataAndData(queue.move(), {})); } RocketClientChannel::RocketClientChannel( folly::AsyncTransportWrapper::UniquePtr socket, RequestSetupMetadata meta) : evb_(socket->getEventBase()), rclient_(rocket::RocketClient::create( *evb_, std::move(socket), std::make_unique<rocket::SetupFrame>( makeSetupFrame(std::move(meta))))) {} RocketClientChannel::~RocketClientChannel() { unsetOnDetachable(); closeNow(); } void RocketClientChannel::setFlushList(FlushList* flushList) { if (rclient_) { rclient_->setFlushList(flushList); } } RocketClientChannel::Ptr RocketClientChannel::newChannel( folly::AsyncTransportWrapper::UniquePtr socket, RequestSetupMetadata meta) { return RocketClientChannel::Ptr( new RocketClientChannel(std::move(socket), std::move(meta))); } void RocketClientChannel::sendRequestResponse( RpcOptions& rpcOptions, std::unique_ptr<folly::IOBuf> buf, std::shared_ptr<transport::THeader> header, RequestClientCallback::Ptr cb) { sendThriftRequest( rpcOptions, RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, std::move(buf), std::move(header), std::move(cb)); } void RocketClientChannel::sendRequestNoResponse( RpcOptions& rpcOptions, std::unique_ptr<folly::IOBuf> buf, std::shared_ptr<transport::THeader> header, RequestClientCallback::Ptr cb) { sendThriftRequest( rpcOptions, RpcKind::SINGLE_REQUEST_NO_RESPONSE, std::move(buf), std::move(header), std::move(cb)); } void RocketClientChannel::sendRequestStream( RpcOptions& rpcOptions, std::unique_ptr<folly::IOBuf> buf, std::shared_ptr<THeader> header, StreamClientCallback* clientCallback) { DestructorGuard dg(this); auto metadata = detail::makeRequestRpcMetadata( rpcOptions, RpcKind::SINGLE_REQUEST_STREAMING_RESPONSE, static_cast<ProtocolId>(protocolId_), timeout_, *header, getPersistentWriteHeaders()); std::chrono::milliseconds firstResponseTimeout; if (!preSendValidation( metadata, rpcOptions, buf, clientCallback, firstResponseTimeout)) { return; } return rclient_->sendRequestStream( rocket::makePayload(metadata, std::move(buf)), firstResponseTimeout, rpcOptions.getChunkTimeout(), rpcOptions.getChunkBufferSize(), clientCallback); } void RocketClientChannel::sendRequestSink( RpcOptions& rpcOptions, std::unique_ptr<folly::IOBuf> buf, std::shared_ptr<transport::THeader> header, SinkClientCallback* clientCallback) { DestructorGuard dg(this); auto metadata = detail::makeRequestRpcMetadata( rpcOptions, RpcKind::SINK, static_cast<ProtocolId>(protocolId_), timeout_, *header, getPersistentWriteHeaders()); std::chrono::milliseconds firstResponseTimeout; if (!preSendValidation( metadata, rpcOptions, buf, clientCallback, firstResponseTimeout)) { return; } return rclient_->sendRequestSink( rocket::makePayload(metadata, std::move(buf)), firstResponseTimeout, clientCallback); } void RocketClientChannel::sendThriftRequest( RpcOptions& rpcOptions, RpcKind kind, std::unique_ptr<folly::IOBuf> buf, std::shared_ptr<transport::THeader> header, RequestClientCallback::Ptr cb) { DestructorGuard dg(this); auto metadata = detail::makeRequestRpcMetadata( rpcOptions, kind, static_cast<ProtocolId>(protocolId_), timeout_, *header, getPersistentWriteHeaders()); std::chrono::milliseconds timeout; if (!preSendValidation(metadata, rpcOptions, buf, cb, timeout)) { return; } // compress the request if needed if (autoCompressSizeLimit_.hasValue() && *autoCompressSizeLimit_ < int(buf->computeChainDataLength())) { if (negotiatedCompressionAlgo_.hasValue()) { rocket::compressRequest(metadata, buf, *negotiatedCompressionAlgo_); } } switch (kind) { case RpcKind::SINGLE_REQUEST_NO_RESPONSE: sendSingleRequestNoResponse(metadata, std::move(buf), std::move(cb)); break; case RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE: sendSingleRequestSingleResponse( metadata, timeout, std::move(buf), std::move(cb)); break; case RpcKind::SINGLE_REQUEST_STREAMING_RESPONSE: // should no longer reach here anymore, use sendRequestStream DCHECK(false); break; default: folly::assume_unreachable(); } } void RocketClientChannel::sendSingleRequestNoResponse( const RequestRpcMetadata& metadata, std::unique_ptr<folly::IOBuf> buf, RequestClientCallback::Ptr cb) { auto& cbRef = *cb; auto sendRequestFunc = [&cbRef, rclientGuard = folly::DelayedDestruction::DestructorGuard(rclient_.get()), rclientPtr = rclient_.get(), requestPayload = rocket::makePayload(metadata, std::move(buf))]() mutable { OnWriteSuccess writeCallback(cbRef); return rclientPtr->sendRequestFnfSync( std::move(requestPayload), &writeCallback); }; auto finallyFunc = [cb = std::move(cb), g = inflightGuard()](folly::Try<void>&& result) mutable { if (result.hasException()) { cb.release()->onResponseError(std::move(result.exception())); } else { // onRequestSent is already called by the writeCallback. cb.release(); } }; if (cbRef.isSync() && folly::fibers::onFiber()) { finallyFunc(folly::makeTryWith(std::move(sendRequestFunc))); } else { auto& fm = getFiberManager(); fm.addTaskFinally( std::move(sendRequestFunc), [finallyFunc = std::move(finallyFunc)]( folly::Try<folly::Try<void>>&& arg) mutable { finallyFunc(collapseTry(std::move(arg))); }); } } void RocketClientChannel::sendSingleRequestSingleResponse( const RequestRpcMetadata& metadata, std::chrono::milliseconds timeout, std::unique_ptr<folly::IOBuf> buf, RequestClientCallback::Ptr cb) { auto& cbRef = *cb; auto sendRequestFunc = [&cbRef, timeout, rclientGuard = folly::DelayedDestruction::DestructorGuard(rclient_.get()), rclientPtr = rclient_.get(), requestPayload = rocket::makePayload(metadata, std::move(buf))]() mutable { OnWriteSuccess writeCallback(cbRef); return rclientPtr->sendRequestResponseSync( std::move(requestPayload), timeout, &writeCallback); }; auto finallyFunc = [cb = std::move(cb), g = inflightGuard()]( folly::Try<rocket::Payload>&& response) mutable { if (UNLIKELY(response.hasException())) { cb.release()->onResponseError(std::move(response.exception())); return; } auto tHeader = std::make_unique<transport::THeader>(); tHeader->setClientType(THRIFT_ROCKET_CLIENT_TYPE); std::unique_ptr<folly::IOBuf> uncompressedResponse; if (response.value().hasNonemptyMetadata()) { ResponseRpcMetadata responseMetadata; try { deserializeMetadata(responseMetadata, response.value()); detail::fillTHeaderFromResponseRpcMetadata(responseMetadata, *tHeader); if (auto compress = responseMetadata.compression_ref()) { folly::io::CodecType codec; switch (*compress) { case CompressionAlgorithm::ZSTD: codec = folly::io::CodecType::ZSTD; break; case CompressionAlgorithm::ZLIB: codec = folly::io::CodecType::ZLIB; break; case CompressionAlgorithm::NONE: codec = folly::io::CodecType::NO_COMPRESSION; break; } uncompressedResponse = folly::io::getCodec(codec)->uncompress( std::move(response.value()).data().get()); } else { uncompressedResponse = std::move(response.value()).data(); } } catch (const std::exception& e) { FB_LOG_EVERY_MS(ERROR, 10000) << "Exception on deserializing metadata: " << folly::exceptionStr(e); cb.release()->onResponseError( folly::exception_wrapper(std::current_exception(), e)); return; } } else { uncompressedResponse = std::move(response.value()).data(); } cb.release()->onResponse(ClientReceiveState( static_cast<uint16_t>(-1), std::move(uncompressedResponse), std::move(tHeader), nullptr)); }; if (cbRef.isSync() && folly::fibers::onFiber()) { finallyFunc(folly::makeTryWith(std::move(sendRequestFunc))); } else { auto& fm = getFiberManager(); fm.addTaskFinally( std::move(sendRequestFunc), [finallyFunc = std::move(finallyFunc)]( folly::Try<folly::Try<rocket::Payload>>&& arg) mutable { finallyFunc(collapseTry(std::move(arg))); }); } } void onResponseError( RequestClientCallback::Ptr& cb, folly::exception_wrapper ew) { cb.release()->onResponseError(std::move(ew)); } void onResponseError(StreamClientCallback* cb, folly::exception_wrapper ew) { cb->onFirstResponseError(std::move(ew)); } void onResponseError(SinkClientCallback* cb, folly::exception_wrapper ew) { cb->onFirstResponseError(std::move(ew)); } template <typename CallbackPtr> bool RocketClientChannel::preSendValidation( RequestRpcMetadata& metadata, RpcOptions& rpcOptions, std::unique_ptr<folly::IOBuf>& buf, CallbackPtr& cb, std::chrono::milliseconds& firstResponseTimeout) { if (!EnvelopeUtil::stripEnvelope(&metadata, buf)) { onResponseError( cb, folly::make_exception_wrapper<TTransportException>( TTransportException::CORRUPTED_DATA, "Unexpected problem stripping envelope")); return false; } metadata.seqId_ref().reset(); DCHECK(metadata.kind_ref().has_value()); if (!rclient_ || !rclient_->isAlive()) { onResponseError( cb, folly::make_exception_wrapper<TTransportException>( TTransportException::NOT_OPEN, "Connection is not open")); return false; } if (inflightRequestsAndStreams() >= maxInflightRequestsAndStreams_) { TTransportException ex( TTransportException::NETWORK_ERROR, "Too many active requests on connection"); // Might be able to create another transaction soon ex.setOptions(TTransportException::CHANNEL_IS_VALID); onResponseError(cb, std::move(ex)); return false; } firstResponseTimeout = std::chrono::milliseconds(metadata.clientTimeoutMs_ref().value_or(0)); if (rpcOptions.getClientOnlyTimeouts()) { metadata.clientTimeoutMs_ref().reset(); metadata.queueTimeoutMs_ref().reset(); } return true; } ClientChannel::SaturationStatus RocketClientChannel::getSaturationStatus() { DCHECK(evb_ && evb_->isInEventBaseThread()); return ClientChannel::SaturationStatus( inflightRequestsAndStreams(), maxInflightRequestsAndStreams_); } void RocketClientChannel::closeNow() { DCHECK(!evb_ || evb_->isInEventBaseThread()); rclient_.reset(); } void RocketClientChannel::setCloseCallback(CloseCallback* closeCallback) { if (rclient_) { rclient_->setCloseCallback([closeCallback] { if (closeCallback) { closeCallback->channelClosed(); } }); } } folly::AsyncTransportWrapper* FOLLY_NULLABLE RocketClientChannel::getTransport() { if (!rclient_) { return nullptr; } auto* transportWrapper = rclient_->getTransportWrapper(); return transportWrapper ? transportWrapper->getUnderlyingTransport<folly::AsyncTransportWrapper>() : nullptr; } bool RocketClientChannel::good() { DCHECK(!evb_ || evb_->isInEventBaseThread()); return rclient_ && rclient_->isAlive(); } size_t RocketClientChannel::inflightRequestsAndStreams() const { return shared_->inflightRequests + (rclient_ ? rclient_->streams() : 0); } void RocketClientChannel::setTimeout(uint32_t timeoutMs) { DCHECK(!evb_ || evb_->isInEventBaseThread()); if (auto* transport = getTransport()) { transport->setSendTimeout(timeoutMs); } timeout_ = std::chrono::milliseconds(timeoutMs); } void RocketClientChannel::attachEventBase(folly::EventBase* evb) { DCHECK(evb->isInEventBaseThread()); if (rclient_) { rclient_->attachEventBase(*evb); } evb_ = evb; } void RocketClientChannel::detachEventBase() { DCHECK(isDetachable()); DCHECK(getDestructorGuardCount() == 0); if (rclient_) { rclient_->detachEventBase(); } evb_ = nullptr; } bool RocketClientChannel::isDetachable() { DCHECK(!evb_ || evb_->isInEventBaseThread()); auto* transport = getTransport(); return !evb_ || !transport || !rclient_ || rclient_->isDetachable(); } void RocketClientChannel::setOnDetachable( folly::Function<void()> onDetachable) { DCHECK(rclient_); ClientChannel::setOnDetachable(std::move(onDetachable)); rclient_->setOnDetachable([this] { if (isDetachable()) { notifyDetachable(); } }); } void RocketClientChannel::unsetOnDetachable() { ClientChannel::unsetOnDetachable(); if (rclient_) { rclient_->setOnDetachable(nullptr); } } constexpr std::chrono::milliseconds RocketClientChannel::kDefaultRpcTimeout; } // namespace thrift } // namespace apache
5601724cb625298df6ad2bb26a822a5bcaa838c0
ac5bc5e28bccad07fa84b7b6d80cda85ffdb09f0
/final/pc2/pc2_leung.cpp
c1d40d7283a981953be2490cc98b41dfc06f6dbe
[]
no_license
chadwickleung/CS-10A
9c748ab5d3eeb99c36dca7a4e98af258a7bdcfac
a6b4a87b33ed8c39117eecfee4d7cb5dcb624674
refs/heads/master
2020-09-21T21:24:56.963005
2019-11-29T23:59:15
2019-11-29T23:59:15
224,936,962
0
0
null
null
null
null
UTF-8
C++
false
false
4,058
cpp
// // pc2_leung.cpp // final question 43, 2D array Operation program, SID: 0475 // // This program would operate the initialize 2D array // // Created by Chadwick Leung on 12/19/18. // Copyright © 2018 Chadwick Leung. All rights reserved. //****************** this line is 70 characters long ********** #include <iostream> #include <iomanip> #include <cstdlib> #include <ctime> using namespace std; //global variables const int row=4, col=5; //function prorotypes void showArray(int [][col]); void getRandomNumberInput(int [][col]); void getTotal(int [][col]); void getAverage(int [][col]); void getRowTotal(int [][col], /*in*/ int); void getHighestInColumn(int [][col], /*in*/ int); int main() { int first_array[row][col] = {{2,3,4,1,6},{5,6,7,8,4},{4,5,6,3,8}, {3,3,4,4,5}}; int second_array[row][col]; cout << "Showing the first_array" <<endl; showArray(first_array); cout << endl; cout << "Showing the random array" <<endl; getRandomNumberInput(second_array); cout << endl; cout << "Showing the total of the first_array" <<endl; getTotal(first_array); cout << endl; cout << "Showing the average of the first_array" <<endl; getAverage(first_array); cout << endl; cout << "Showing the row total of the first row of the first_array" <<endl; getRowTotal(first_array, 0); cout << endl; cout << "Showing the highest value of the first column of the first_array" <<endl; getHighestInColumn(first_array,0); cout << endl; return 0; } void showArray(int array[][col]) // pre: array assigned //post: display the array { for (int rcount=0; rcount<row; rcount++) { for (int ccount=0; ccount<col; ccount++) { cout << array[rcount][ccount]; cout << " "; } cout << endl; } } void getRandomNumberInput(int array[][col]) // pre: array assigned //post: display the random array { srand(time(NULL)); for (int rcount=0; rcount<row; rcount++) { for (int ccount=0; ccount<col; ccount++) { array[rcount][ccount] = 2+rand()%((9+1)-2); } } for (int rcount=0; rcount<row; rcount++) { for (int ccount=0; ccount<col; ccount++) { cout << array[rcount][ccount]; cout << " "; } cout << endl; } } void getTotal(int array[][col]) // pre: array assigned //post: show the total of all values { int sum=0; for (int rcount=0; rcount<row; rcount++) { for (int ccount=0; ccount<col; ccount++) { sum = sum + array[rcount][ccount]; } } cout << "The sum of all the values in the array is " << sum; cout << endl; } void getAverage(int array[][col]) // pre: array assigned //post: show the average of all values { int sum=0, count=0, average=0; for (int rcount=0; rcount<row; rcount++) { for (int ccount=0; ccount<col; ccount++) { sum = sum + array[rcount][ccount]; count++; } } average = sum/count; cout << "The average of all the values in the array is "<< average; cout <<endl; } void getRowTotal(int array[][col], int rowselected) // pre: array assigned //post: show the row total of the selected row { int rowsum=0; for (int ccount=0; ccount<col; ccount++) { rowsum = rowsum + array[rowselected][ccount]; } cout << "The row total of row " << rowselected+1 << " is "<< rowsum; cout <<endl; } void getHighestInColumn(int array[][col], int columnselected) // pre: array assigned //post: show the highest of the column selected { int colhighest=0; for (int rcount=0; rcount<row; rcount++) { if (array[rcount][columnselected]>colhighest) { colhighest = array[rcount][columnselected]; } } cout << "The highest value in column " << columnselected+1 << " is " << colhighest; }
a217cf83f77842c7a52547be7117ad2e0a01478f
01837a379a09f74f7ef43807533093fa716e71ac
/src/utils/xulrunner-sdk/nsIUpdateTimerManager.h
1bf18833d3292c638140ccae591d72788c30da36
[]
no_license
lasuax/jorhy-prj
ba2061d3faf4768cf2e12ee2484f8db51003bd3e
d22ded7ece50fb36aa032dad2cc01deac457b37f
refs/heads/master
2021-05-05T08:06:01.954941
2014-01-13T14:03:30
2014-01-13T14:03:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,992
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-m-rel-xr_w32_bld-000000000/build/toolkit/mozapps/update/nsIUpdateTimerManager.idl */ #ifndef __gen_nsIUpdateTimerManager_h__ #define __gen_nsIUpdateTimerManager_h__ #ifndef __gen_nsISupports_h__ #include "nsISupports.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif class nsITimerCallback; /* forward declaration */ /* starting interface: nsIUpdateTimerManager */ #define NS_IUPDATETIMERMANAGER_IID_STR "0765c92c-6145-4253-9db4-594d8023087e" #define NS_IUPDATETIMERMANAGER_IID \ {0x0765c92c, 0x6145, 0x4253, \ { 0x9d, 0xb4, 0x59, 0x4d, 0x80, 0x23, 0x08, 0x7e }} class NS_NO_VTABLE nsIUpdateTimerManager : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IUPDATETIMERMANAGER_IID) /* void registerTimer (in AString id, in nsITimerCallback callback, in unsigned long interval); */ NS_IMETHOD RegisterTimer(const nsAString & id, nsITimerCallback *callback, uint32_t interval) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIUpdateTimerManager, NS_IUPDATETIMERMANAGER_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIUPDATETIMERMANAGER \ NS_IMETHOD RegisterTimer(const nsAString & id, nsITimerCallback *callback, uint32_t interval); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIUPDATETIMERMANAGER(_to) \ NS_IMETHOD RegisterTimer(const nsAString & id, nsITimerCallback *callback, uint32_t interval) { return _to RegisterTimer(id, callback, interval); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIUPDATETIMERMANAGER(_to) \ NS_IMETHOD RegisterTimer(const nsAString & id, nsITimerCallback *callback, uint32_t interval) { return !_to ? NS_ERROR_NULL_POINTER : _to->RegisterTimer(id, callback, interval); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsUpdateTimerManager : public nsIUpdateTimerManager { public: NS_DECL_ISUPPORTS NS_DECL_NSIUPDATETIMERMANAGER nsUpdateTimerManager(); private: ~nsUpdateTimerManager(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsUpdateTimerManager, nsIUpdateTimerManager) nsUpdateTimerManager::nsUpdateTimerManager() { /* member initializers and constructor code */ } nsUpdateTimerManager::~nsUpdateTimerManager() { /* destructor code */ } /* void registerTimer (in AString id, in nsITimerCallback callback, in unsigned long interval); */ NS_IMETHODIMP nsUpdateTimerManager::RegisterTimer(const nsAString & id, nsITimerCallback *callback, uint32_t interval) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIUpdateTimerManager_h__ */
342cb24c7a0f3f0c4cef0f8b72e417344bd4a9a4
56bfccc8424b3756187076b59323b4dfde42ce23
/Tests/Cam/v5/cam.cc
3c1669ac05c1747ef923892fb930e0570351ab39
[]
no_license
Vernacular1988/Switch_SoC
2d553498d9ebd45a4e2255c1a56a158688847c3b
365c00f7ed40643cf8a7c4a20f6e46cfa4d70fcc
refs/heads/master
2018-01-08T10:39:50.279858
2016-02-24T03:58:36
2016-02-24T03:58:36
52,413,009
1
0
null
null
null
null
UTF-8
C++
false
false
6,806
cc
// cam.cc #include "cam.h" // 0 1 or 2 #define DEBUG 2 void amem::exe_command() { // We need to make copies of all the inputs to allow us to do math/logic // Note: One can do math on sc_ types but not sc_signals of those same types am_word comp; am_word mask; am_word wdata; am_word rdata; sc_uint<AMSZ> add; command_type cmd; bool any; // Array deep "or" for match operation done = true; // Initalize as ready to receive instructions // Loop forever waiting for commands while(true) { comp = compin; // Make copies of signals for logical ops mask = maskin; wdata = writedata; rdata = readdata; add = address; cmd = command; // See if we can accept a command, and if we have one to work on if (start && done) { // Tell the world you are working, and wait for the next clock done = false; match = false; if (DEBUG) cout << "AM Command is: " << cmd << endl; wait(); // Now do the work based on the command op code switch (cmd) { ///////////////////////////////////////////////////////// // NOTE Compare and Hamming are NOT enabled by TAG. // Probably we do want it enabled by TAG // as IS TRUE for AREAD and AWRITE. // This would allow for concatinated seaches. // But then we would need to do a SETTAG operation // before starting most searches. // Any (match) should be computed all the time. // (it would be a big OR gate). // And we should add count responders. case COMPARE: // Compare with broadcast comparand and mask // mask[i] == 1 means ignore bit i of comparand if(DEBUG) cout << "Compare Operation" << endl; any = false; for(int i = 0 ; i<CAM_ARRAY_SIZE; i++) { if (((am_array[i].word ^ comp) & ~mask) == 0) { am_array[i].tag = 1; any = true; if(DEBUG>1) cout << "match at "<< i <<endl; } else { am_array[i].tag = 0; if(DEBUG>1) cout << "no match at "<< i <<endl; } if(DEBUG>1) cout << am_array[i] << comp << endl<< mask << endl << endl; } match = any; break; ///////////////////////////////////////////////////////// case AREAD: // Associative Read // Reads from last word with tag set (could be OR of words) if(DEBUG) cout << "Read operation" << endl; for(int i = 0 ; i<CAM_ARRAY_SIZE; i++) { if(am_array[i].tag == '1') { rdata = am_array[i].word; } if(DEBUG) cout << am_array[i] << rdata << " was read " << endl << endl; } readdata = rdata; break; ///////////////////////////////////////////////////////// case AWRITE: //Associative Write // Writes to ALL words with tag set, masked by mask if(DEBUG) cout << "Write Operation" << endl; for(int i = 0 ; i<CAM_ARRAY_SIZE; i++) { if(am_array[i].tag == '1') { am_array[i].word = ((am_array[i].word & mask) | (wdata & ~mask)); } if(DEBUG>1) cout << am_array[i] << endl; } break; ///////////////////////////////////////////////////////// case READ: // RAM Read // Reads from one word at address if(DEBUG) cout << "Read Operation" << endl; rdata = am_array[add].word; if(DEBUG>1) for(int i = 0 ; i<CAM_ARRAY_SIZE; i++) cout << am_array[i] << endl; readdata = rdata; break; ///////////////////////////////////////////////////////// case WRITE: // RAM Write // Writes to one word at address, masked by mask if(DEBUG) cout << "Write Operation" << endl; am_array[add].word = ((am_array[add].word & mask) | (wdata & ~mask)); if(DEBUG>1) for(int i = 0 ; i<CAM_ARRAY_SIZE; i++) cout << am_array[i] << endl; break; ///////////////////////////////////////////////////////// case SETTAG: // Set all Tags if(DEBUG) cout << "Set All Tags" << endl; for(int i = 0 ; i<CAM_ARRAY_SIZE; i++) { am_array[i].tag = '1'; if(DEBUG>1) cout << am_array[i] << endl; } break; ///////////////////////////////////////////////////////// case CLEARTAG: // Clear all Tags and Degree of Match counters if(DEBUG) cout << "Clear All Tags" << endl; for(int i = 0 ; i<CAM_ARRAY_SIZE; i++) { am_array[i].tag = '0'; am_array[i].dom = 0; if(DEBUG>1) cout << am_array[i] << endl; } break; ///////////////////////////////////////////////////////// case COMPTAG: // Clear all Tags if(DEBUG) cout << "Complement All Tags" << endl; for(int i = 0 ; i<CAM_ARRAY_SIZE; i++) { am_array[i].tag = ~am_array[i].tag; if(DEBUG>1) cout << am_array[i] << endl; } break; ///////////////////////////////////////////////////////// case SELFIRST: // Select the First Tag (pick one) if(DEBUG) cout << "Select First Tag" << endl; { bool found = 0; for(int i = 0 ; i<CAM_ARRAY_SIZE; i++) { if(am_array[i].tag == 1) { // if this is not the first, reset it if (found) am_array[i].tag = '0'; // if it was the first, remember we found one found = 1; } if(DEBUG>1) cout << am_array[i] << endl; } } break; ///////////////////////////////////////////////////////// case HAMMING: // Calculate Hamming Distance in DoM counters if(DEBUG) cout << "Calculate Hammng Distance" << endl; // Loop over words and then bits in each word to count bit matches for(int i = 0; i<CAM_ARRAY_SIZE; i++) { for(int j = 0; j<CAM_WORD_WIDTH; j++) { if (((am_array[i].word[j] ^ comp[j]) & ~mask[j]) == 0) { am_array[i].dom++; } } if(DEBUG>1) cout << am_array[i] << endl; } break; ///////////////////////////////////////////////////////// case WTA: // Winner Take All (find largest DoM counter) if(DEBUG) cout << "Winner take all" << endl; // Loop over words and set tag on first best matching word // Word can be read out with AREAD // Do we want to output the DoM value itself? { int best = 0; bool found = 0; for(int i = 0; i<CAM_ARRAY_SIZE; i++) { if (am_array[i].dom > best) { best = am_array[i].dom; } } // Have to set tag on second pass to avoid local max problem for(int i = 0; i<CAM_ARRAY_SIZE; i++) { if ((am_array[i].dom == best) && !found) { am_array[i].tag = '1'; found = '1'; } else { am_array[i].tag = '0'; } if(DEBUG>1) cout << am_array[i] << endl; } } break; ///////////////////////////////////////////////////////// case KNN: //find k nearest neighbors based on counts not just best if(DEBUG) cout << "Find K nearest neigbors" << endl; find_knn = true; wait(); find_knn = false; break; ///////////////////////////////////////////////////////// default: // Undefined command if(DEBUG) cout << "Error bad command" << endl; break; } // end of switch // tell the world you are done done = true; } // end of if(start && done) wait(); // must always be one wait in an infinite loop } // end of loop }
cbc55cc8a59233a4a90ffdb34fda220967687d96
f353a1d545d77e22d31219c36a7a6b2e03c6a863
/NativeLibrary/MethodHeader.h
2e14bc99a0ad273bb07f0be277128e9169c78be9
[ "MIT" ]
permissive
zaimpauzi/CSharpCpp_InteropTemplate
98714df7567cc28da3ef79e64fa5f49d9a7a2ddb
42e49f8bafac111298d8b1d6e8262a6d925fe989
refs/heads/master
2020-04-20T21:13:41.241168
2019-02-07T08:01:52
2019-02-07T08:01:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
331
h
//#pragma once #ifndef METHODHEADER_H #define METHODHEADER_H #include <iostream> #include <string> //using namespace std; namespace methodNamespace { class methodClass { public: methodClass(); ~methodClass(); void stringMethod(char *inputString); double doubleMethod(double *inputDouble); }; } #endif //METHODHEADER_H
c1c95ee9f75e44d7b3d963f953f163553198ce25
302e50891d70be0035df04fe7e0fb9545f9c0ea2
/arduinoIntro/ardDigOut/ardDigOut.ino
d7a666aa6f3c9626521c487198fc6816cabaa87f
[]
no_license
SoyUnCitrico/expandiendoCanvas
3d2983bdebd2800d09b6624b29806a8b1d31b1a8
d9bd29cb23abba2db286f637f9652a0f02ec13f8
refs/heads/master
2021-02-13T10:24:26.421082
2020-03-22T12:41:10
2020-03-22T12:41:10
244,687,893
0
0
null
null
null
null
UTF-8
C++
false
false
1,600
ino
// Variabes de salida para el control de LEDs // Cada uno de los LED's se encuentra conectado directamente a esos pines // en el NODEMCU mediante la placa de circuito electrico "PCB" #define ROJO D5 #define VERDE D6 #define AZUL D7 // Codigo de configuracion de incio, solo se ejecuta la primera vez al encender el NODEMCU void setup() { // Declaracion de la funcion de los pines pinMode(ROJO, OUTPUT); pinMode(VERDE, OUTPUT); pinMode(AZUL, OUTPUT); // Se asegura de que los LEDs comiencen apagados digitalWrite(ROJO, LOW); digitalWrite(VERDE, LOW); digitalWrite(AZUL, LOW); } void loop() { // Pon el pin que esta conectado al led ROJO en un valor alto 'HIGH' digitalWrite(ROJO, HIGH); // Deten el funcionamiento por 500 milisegundos delay(500); // Pon el pin ROJO en un valor bajo 'LOW' digitalWrite(ROJO, LOW); // Deten el funcionamiento por 500 milisegundos delay(500); // Ahora la misma secuencia con el LED verde digitalWrite(VERDE, HIGH); delay(500); digitalWrite(VERDE, LOW); delay(500); // Ahora la misma secuencia con el LED azul digitalWrite(AZUL, HIGH); delay(500); digitalWrite(AZUL, LOW); delay(500); // Ahora la misma secuencia con los LEDs rojo y verde // La mezcla produce un color amarillo digitalWrite(ROJO, HIGH); digitalWrite(VERDE, HIGH); delay(500); digitalWrite(ROJO, LOW); digitalWrite(VERDE, LOW); delay(500); }
0cb52197fcb39f5eb8fe3b31265392233e7fbd1c
5d116461831e99db951e7f6e478c2eb26072d5ab
/src/game/Ball.cpp
e795cb729a683c06fa832c3bbd7f8a3116d060fa
[]
no_license
Smeky/Brick-Breaker
d6dd4014f5a4943eecca9116657bc6209da49889
c21a9102765159c0f8e2f9a90c62bbcffb0b66fe
refs/heads/master
2021-01-10T15:42:12.311756
2016-01-14T22:21:13
2016-01-14T22:21:13
48,491,962
0
0
null
null
null
null
UTF-8
C++
false
false
514
cpp
#include "Ball.hpp" namespace bb { Ball::Ball() : m_velocity( 0.0 ) , m_isFired( false ) {} void Ball::setVelocity( float velocity ) { m_velocity = velocity; } float Ball::getVelocity() const { return m_velocity; } void Ball::setDirVelocity( const Vec2f& velocity ) { m_dirVelocity = velocity; } Vec2f Ball::getDirVelocity() const { return m_dirVelocity; } void Ball::setFired( bool fired ) { m_isFired = fired; } bool Ball::isFired() const { return m_isFired; } } // namespace bb
f02b24918cbebe4e5f7720bc826ac6dc76fe9793
6a55fc908497a0d4ada6eae74d64a057b609c261
/ngraph/src/ngraph/runtime/tensor.cpp
03c553056351140884ff7cf7a95cdc2e1c6b6b8f
[ "Apache-2.0" ]
permissive
anton-potapov/openvino
9f24be70026a27ea55dafa6e7e2b6b18c6c18e88
84119afe9a8c965e0a0cd920fff53aee67b05108
refs/heads/master
2023-04-27T16:34:50.724901
2020-06-10T11:13:08
2020-06-10T11:13:08
271,256,329
1
0
Apache-2.0
2021-04-23T08:22:48
2020-06-10T11:16:29
null
UTF-8
C++
false
false
2,824
cpp
//***************************************************************************** // Copyright 2017-2020 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include "tensor.hpp" #include "ngraph/descriptor/layout/tensor_layout.hpp" #include "ngraph/log.hpp" #include "ngraph/runtime/aligned_buffer.hpp" #include "ngraph/type/element_type.hpp" using namespace ngraph; using namespace std; const Shape& runtime::Tensor::get_shape() const { return m_descriptor->get_shape(); } const PartialShape& runtime::Tensor::get_partial_shape() const { return m_descriptor->get_partial_shape(); } Strides runtime::Tensor::get_strides() const { return m_descriptor->get_tensor_layout()->get_strides(); } const element::Type& runtime::Tensor::get_element_type() const { return m_descriptor->get_element_type(); } shared_ptr<descriptor::layout::TensorLayout> runtime::Tensor::get_tensor_layout() const { return m_descriptor->get_tensor_layout(); } void runtime::Tensor::set_tensor_layout(const shared_ptr<descriptor::layout::TensorLayout>& layout) { m_descriptor->set_tensor_layout(layout); } size_t runtime::Tensor::get_element_count() const { return shape_size(m_descriptor->get_shape()); } size_t runtime::Tensor::get_size_in_bytes() const { return m_descriptor->size(); } const std::string& runtime::Tensor::get_name() const { return m_descriptor->get_name(); } bool runtime::Tensor::get_stale() const { return m_stale; } void runtime::Tensor::set_stale(bool val) { m_stale = val; } void runtime::Tensor::copy_from(const ngraph::runtime::Tensor& source) { if (get_element_count() != source.get_element_count()) { throw invalid_argument("runtime::Tensor::copy_from element count must match"); } if (get_element_type() != source.get_element_type()) { throw invalid_argument("runtime::Tensor::copy_from element types must match"); } // This is potentially inefficient but is supplied only to get things going // This is be replaced with more optimial implementations in later PRs auto size = get_size_in_bytes(); AlignedBuffer buffer{size, 64}; source.read(buffer.get_ptr(), size); write(buffer.get_ptr(), size); }
fb11aa72929a7ce77ff4fcfde3f2ce884ee1f925
421081432705e9e6d1c0dcc7b6c7c0bf295d0dcc
/RPI-Security Server/src/ServoMoteur.cpp
7330212c917d23d349c62fb16a86f37ea2cce1c1
[]
no_license
Mistgun-Dev/RPI-Security
f2f4e53aae624420716d2f6b24063c280112cc0c
d64678bf6c4892cfb3f55538bb2b3782a99cc410
refs/heads/master
2020-06-01T01:13:20.001947
2019-06-06T13:11:30
2019-06-06T13:11:30
190,572,935
0
0
null
null
null
null
UTF-8
C++
false
false
2,034
cpp
/* * Fichier ServoMoteur.cpp * Date : 04/06/2019 * Auteurs : Nehari Mohamed et Yassine Tabet * Classe permettant la gestion des servoMoteurs. */ #include "ServoMoteur.h" #include <iostream> #include <wiringPi.h> // Constructeur initialisant les entrées des servomoteurs ServoMoteur::ServoMoteur(unsigned char u8PinServo) { if (wiringPiSetupGpio () == -1) return; this->u8PinServo = u8PinServo; pinMode(this->u8PinServo, PWM_OUTPUT); this->u8Speed = 3; this->u8PositionCourante = ROT_MIDDLE; } ServoMoteur::~ServoMoteur() { } // Fonction placant le sermomoteur à une position de démarrage void ServoMoteur::vdPositionDemarrage() { this->u8PositionCourante = ROT_MIDDLE; pwmSetMode(PWM_MODE_MS); pwmSetClock(375); pwmSetRange(1024); pwmWrite(this->u8PinServo, this->u8PositionCourante); } // Fonction permettant la rotation du servomoteur à droite ou à gauche en fonction de la direction passée en paramètre void ServoMoteur::vdRotation(char direction, bool servoHorizontal) { pwmSetMode(PWM_MODE_MS); pwmSetClock(375); pwmSetRange(1024); if(direction == DIRECTION_RIGHT) { if(servoHorizontal == true) this->u8PositionCourante = 5; else if((this->u8PositionCourante - u8Speed) <= ROT_MIN+3) this->u8PositionCourante = ROT_MIN+3; else this->u8PositionCourante -= u8Speed; } else if(direction == DIRECTION_LEFT) { if(servoHorizontal == true) this->u8PositionCourante = -5; else if((this->u8PositionCourante + u8Speed) >= ROT_MAX-3) this->u8PositionCourante = ROT_MAX-3; else this->u8PositionCourante += u8Speed; } else return; if(servoHorizontal == true) { pwmWrite(this->u8PinServo, this->u8PositionCourante); delay(100); pwmWrite(this->u8PinServo,0); } else pwmWrite(this->u8PinServo, this->u8PositionCourante); } // Fonction permettant la rotation du servomoteur à un angle définit void ServoMoteur::vdSetRotation(char rot) { pwmSetMode(PWM_MODE_MS); pwmSetClock(375); pwmSetRange(1024); pwmWrite(this->u8PinServo , rot); }
691bbdb0997ec8e88d47ac8204ea5a9ac2ee7688
1b06a6aeb4680dd1f458ed4eef079abb7df6638d
/choosescene.cpp
7c2f927f77e535a342bc3b45023b14993501a572
[]
no_license
gnef-718/test
dd157fdd2ad68f3ebb21670372b84d80ed226628
8412ac96e0d3f0d2cec0cef58975f52a2752029a
refs/heads/master
2022-11-14T11:34:51.694616
2020-07-15T13:18:46
2020-07-15T13:18:46
279,855,396
0
0
null
null
null
null
UTF-8
C++
false
false
12,375
cpp
#include "choosescene.h" #include"mypushbutton.h" #include<QTimer> #include"playscene.h" #include<QPainter> #include <QtMultimedia/QSound> #include <QMediaPlaylist> #include <QMediaPlayer> ChooseScene::ChooseScene(QWidget *parent) : QMainWindow(parent) { this->setFixedSize(1200,1000); this->setWindowIcon(QIcon(":/image/06.jpg")); this->setWindowTitle("Choose Mode"); this->setAttribute(Qt::WA_DeleteOnClose); myPushButton* backbtn=new myPushButton(":/image/icons8-back-100.png"); backbtn->setParent(this); backbtn->move(backbtn->width()-100,this->height()-backbtn->height()-5); connect(backbtn,&myPushButton::clicked,[=](){ QMediaPlayer *clickplayer = new QMediaPlayer; clickplayer->setMedia(QUrl("E:/Qt/LinkGame/image/click.wav")); clickplayer->play(); backbtn->jumpdown(); backbtn->jumpup(); QTimer::singleShot(400,this,[=](){ emit back(); delete clickplayer; }); }); myPushButton* levelbtn1=new myPushButton(":/image/icons8-1st-100.png",":/image/icons8-level-1-100 (1).png"); myPushButton* levelbtn2=new myPushButton(":/image/icons8-circled-2-100.png",":/image/icons8-circled-2-c-100.png"); myPushButton* levelbtn3=new myPushButton(":/image/icons8-circled-3-100.png",":/image/icons8-circled-3-c-100.png"); myPushButton* levelbtn4=new myPushButton(":/image/icons8-circled-4-100.png",":/image/icons8-circled-4-c-100.png"); myPushButton* levelbtn5=new myPushButton(":/image/icons8-circled-5-100.png",":/image/icons8-circled-5-c-100.png"); myPushButton* levelbtn6=new myPushButton(":/image/icons8-circled-6-100.png",":/image/icons8-circled-6-c-100.png"); myPushButton* levelbtn7=new myPushButton(":/image/icons8-circled-7-100.png",":/image/icons8-circled-7-c-100.png"); myPushButton* levelbtn8=new myPushButton(":/image/icons8-circled-8-100.png",":/image/icons8-circled-8-c-100.png"); myPushButton* levelbtn9=new myPushButton(":/image/icons8-circled-9-100.png",":/image/icons8-circled-9-c-100.png"); levelbtn1->setParent(this); levelbtn2->setParent(this); levelbtn3->setParent(this); levelbtn4->setParent(this); levelbtn5->setParent(this); levelbtn6->setParent(this); levelbtn7->setParent(this); levelbtn8->setParent(this); levelbtn9->setParent(this); levelbtn1->move(400,350); levelbtn2->move(550,350); levelbtn3->move(700,350); levelbtn4->move(400,525); levelbtn5->move(550,525); levelbtn6->move(700,525); levelbtn7->move(400,700); levelbtn8->move(550,700); levelbtn9->move(700,700); connect(levelbtn1,&myPushButton::clicked,[=](){ QMediaPlayer *clickplayer = new QMediaPlayer; clickplayer->setMedia(QUrl("E:/Qt/LinkGame/image/click.wav")); clickplayer->play(); levelbtn1->jumpdown(); levelbtn1->jumpup(); PlayScene* ps=new PlayScene(this,1); QTimer::singleShot(400,this,[=](){ this->hide(); ps->show(); delete clickplayer; }); connect(ps,&PlayScene::home,[=](){ ps->hide(); QTimer::singleShot(400,this,[=](){ delete ps; }); emit back(); }); connect(ps,&PlayScene::back,[=](){ ps->hide(); QTimer::singleShot(400,this,[=](){ delete ps; }); this->show(); }); connect(ps,&PlayScene::musicstop,[=](){ emit musics(); }); connect(ps,&PlayScene::musicplay,[=](){ emit musicp(); }); }); connect(levelbtn2,&myPushButton::clicked,[=](){ QMediaPlayer *clickplayer = new QMediaPlayer; clickplayer->setMedia(QUrl("E:/Qt/LinkGame/image/click.wav")); clickplayer->play(); levelbtn2->jumpdown(); levelbtn2->jumpup(); PlayScene* ps=new PlayScene(this,2); QTimer::singleShot(400,this,[=](){ this->hide(); ps->show(); delete clickplayer; }); connect(ps,&PlayScene::home,[=](){ ps->hide(); QTimer::singleShot(400,this,[=](){ delete ps; }); emit back(); }); connect(ps,&PlayScene::back,[=](){ ps->hide(); QTimer::singleShot(400,this,[=](){ delete ps; }); this->show(); }); connect(ps,&PlayScene::musicstop,[=](){ emit musics(); }); connect(ps,&PlayScene::musicplay,[=](){ emit musicp(); }); }); connect(levelbtn3,&myPushButton::clicked,[=](){ QMediaPlayer *clickplayer = new QMediaPlayer; clickplayer->setMedia(QUrl("E:/Qt/LinkGame/image/click.wav")); clickplayer->play(); levelbtn3->jumpdown(); levelbtn3->jumpup(); PlayScene* ps=new PlayScene(this,3); QTimer::singleShot(400,this,[=](){ this->hide(); ps->show(); delete clickplayer; }); connect(ps,&PlayScene::home,[=](){ ps->hide(); QTimer::singleShot(400,this,[=](){ delete ps; }); emit back(); }); connect(ps,&PlayScene::back,[=](){ ps->hide(); QTimer::singleShot(400,this,[=](){ delete ps; }); this->show(); }); connect(ps,&PlayScene::musicstop,[=](){ emit musics(); }); connect(ps,&PlayScene::musicplay,[=](){ emit musicp(); }); }); connect(levelbtn4,&myPushButton::clicked,[=](){ QMediaPlayer *clickplayer = new QMediaPlayer; clickplayer->setMedia(QUrl("E:/Qt/LinkGame/image/click.wav")); clickplayer->play(); levelbtn4->jumpdown(); levelbtn4->jumpup(); PlayScene* ps=new PlayScene(this,4); QTimer::singleShot(400,this,[=](){ this->hide(); ps->show(); delete clickplayer; }); connect(ps,&PlayScene::home,[=](){ ps->hide(); QTimer::singleShot(400,this,[=](){ delete ps; }); emit back(); }); connect(ps,&PlayScene::back,[=](){ ps->hide(); QTimer::singleShot(400,this,[=](){ delete ps; }); this->show(); }); connect(ps,&PlayScene::musicstop,[=](){ emit musics(); }); connect(ps,&PlayScene::musicplay,[=](){ emit musicp(); }); }); connect(levelbtn5,&myPushButton::clicked,[=](){ QMediaPlayer *clickplayer = new QMediaPlayer; clickplayer->setMedia(QUrl("E:/Qt/LinkGame/image/click.wav")); clickplayer->play(); levelbtn5->jumpdown(); levelbtn5->jumpup(); PlayScene* ps=new PlayScene(this,5); QTimer::singleShot(400,this,[=](){ this->hide(); ps->show(); delete clickplayer; }); connect(ps,&PlayScene::home,[=](){ ps->hide(); QTimer::singleShot(400,this,[=](){ delete ps; }); emit back(); }); connect(ps,&PlayScene::back,[=](){ ps->hide(); QTimer::singleShot(400,this,[=](){ delete ps; }); this->show(); }); connect(ps,&PlayScene::musicstop,[=](){ emit musics(); }); connect(ps,&PlayScene::musicplay,[=](){ emit musicp(); }); }); connect(levelbtn6,&myPushButton::clicked,[=](){ QMediaPlayer *clickplayer = new QMediaPlayer; clickplayer->setMedia(QUrl("E:/Qt/LinkGame/image/click.wav")); clickplayer->play(); levelbtn6->jumpdown(); levelbtn6->jumpup(); PlayScene* ps=new PlayScene(this,6); QTimer::singleShot(400,this,[=](){ this->hide(); ps->show(); delete clickplayer; }); connect(ps,&PlayScene::home,[=](){ ps->hide(); QTimer::singleShot(400,this,[=](){ delete ps; }); emit back(); }); connect(ps,&PlayScene::back,[=](){ ps->hide(); QTimer::singleShot(400,this,[=](){ delete ps; }); this->show(); }); connect(ps,&PlayScene::musicstop,[=](){ emit musics(); }); connect(ps,&PlayScene::musicplay,[=](){ emit musicp(); }); }); connect(levelbtn7,&myPushButton::clicked,[=](){ QMediaPlayer *clickplayer = new QMediaPlayer; clickplayer->setMedia(QUrl("E:/Qt/LinkGame/image/click.wav")); clickplayer->play(); levelbtn7->jumpdown(); levelbtn7->jumpup(); PlayScene* ps=new PlayScene(this,7); QTimer::singleShot(400,this,[=](){ this->hide(); ps->show(); delete clickplayer; }); connect(ps,&PlayScene::home,[=](){ ps->hide(); QTimer::singleShot(400,this,[=](){ delete ps; }); emit back(); }); connect(ps,&PlayScene::back,[=](){ ps->hide(); QTimer::singleShot(400,this,[=](){ delete ps; }); this->show(); }); connect(ps,&PlayScene::musicstop,[=](){ emit musics(); }); connect(ps,&PlayScene::musicplay,[=](){ emit musicp(); }); }); connect(levelbtn8,&myPushButton::clicked,[=](){ QMediaPlayer *clickplayer = new QMediaPlayer; clickplayer->setMedia(QUrl("E:/Qt/LinkGame/image/click.wav")); clickplayer->play(); levelbtn8->jumpdown(); levelbtn8->jumpup(); PlayScene* ps=new PlayScene(this,8); QTimer::singleShot(400,this,[=](){ this->hide(); ps->show(); delete clickplayer; }); connect(ps,&PlayScene::home,[=](){ ps->hide(); QTimer::singleShot(400,this,[=](){ delete ps; }); emit back(); }); connect(ps,&PlayScene::back,[=](){ ps->hide(); QTimer::singleShot(400,this,[=](){ delete ps; }); this->show(); }); connect(ps,&PlayScene::musicstop,[=](){ emit musics(); }); connect(ps,&PlayScene::musicplay,[=](){ emit musicp(); }); }); connect(levelbtn9,&myPushButton::clicked,[=](){ QMediaPlayer *clickplayer = new QMediaPlayer; clickplayer->setMedia(QUrl("E:/Qt/LinkGame/image/click.wav")); clickplayer->play(); levelbtn9->jumpdown(); levelbtn9->jumpup(); PlayScene* ps=new PlayScene(this,9); QTimer::singleShot(400,this,[=](){ this->hide(); ps->show(); delete clickplayer; }); connect(ps,&PlayScene::home,[=](){ ps->hide(); QTimer::singleShot(400,this,[=](){ delete ps; }); emit back(); }); connect(ps,&PlayScene::back,[=](){ ps->hide(); QTimer::singleShot(400,this,[=](){ delete ps; }); this->show(); }); connect(ps,&PlayScene::musicstop,[=](){ emit musics(); }); connect(ps,&PlayScene::musicplay,[=](){ emit musicp(); }); }); } void ChooseScene::paintEvent(QPaintEvent *) { QPainter painter(this); QPixmap pix; pix.load(":/image/choose.jpg"); painter.drawPixmap(0,0,this->width(),this->height(),pix); }
828807ef65a16bc226f3f703cf37050f176e9bd5
89d9ab09f1dc43e660a63947fbe4c20a81ddff49
/Pl_CheckBox.cpp
f68ec0085a5d6596189254d39b3467ed8ff50b0e
[]
no_license
aurusov/rdo_explorer
a8a80cb79bea31faf2a27d9893266e2770c4ea7f
9ff5856e74aabdc488394496ece95aea326079d6
refs/heads/master
2021-01-23T02:58:49.464355
2004-01-26T08:11:19
2004-01-26T08:11:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,427
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "Pl_CheckBox.h" //--------------------------------------------------------------------------- #pragma package(smart_init) //--------------------------------------------------------------------------- __fastcall TPaulCheckBox::TPaulCheckBox(TComponent* Owner) : TWinControl(Owner), FChecked(false) { canvas = new TControlCanvas(); canvas->Control = this; if (dynamic_cast<TWinControl*>(Owner)) Parent = (TWinControl*)Owner; ControlStyle << csSetCaption << csOpaque << csDoubleClicks; SetBounds(0, 0, 97, 17); TabStop = true; } //--------------------------------------------------------------------------- __fastcall TPaulCheckBox::~TPaulCheckBox(void) { delete canvas; } //--------------------------------------------------------------------------- void __fastcall TPaulCheckBox::SetEnabled(const bool Value) { TControl::SetEnabled(Value); Repaint(); } //--------------------------------------------------------------------------- void __fastcall TPaulCheckBox::WndProc(Messages::TMessage &Message) { switch (Message.Msg) { case WM_LBUTTONDOWN : case WM_LBUTTONDBLCLK : if (Enabled) { SetFocus(); Repaint(); } break; case WM_SETFOCUS : case WM_KILLFOCUS : Repaint(); break; case CM_TEXTCHANGED : case CM_SYSCOLORCHANGE: case CM_FONTCHANGE : case WM_SIZE : case WM_PAINT : TWinControl::WndProc(Message); Repaint(); return; case WM_KEYUP : if (Message.WParam == VK_SPACE) { Click(); Repaint(); break; } } TWinControl::WndProc(Message); } //--------------------------------------------------------------------------- void __fastcall TPaulCheckBox::SetDisabledColor(const TColor Value) { if (FDisabledColor != Value) { FDisabledColor = Value; Repaint(); } } //--------------------------------------------------------------------------- void __fastcall TPaulCheckBox::SetBackColor(const TColor Value) { if (FBackColor != Value) { FBackColor = Value; Repaint(); } } //--------------------------------------------------------------------------- void __fastcall TPaulCheckBox::SetChecked(const bool Value) { if (FChecked != Value) { FChecked = Value; Repaint(); } } //--------------------------------------------------------------------------- void __fastcall TPaulCheckBox::Click(void) { if (Enabled) { FChecked = !FChecked; Repaint(); TWinControl::Click(); } } //--------------------------------------------------------------------------- void __fastcall TPaulCheckBox::Repaint(void) { TRect rect = ClientRect; TRect focusrect = rect; focusrect.left = rect.left + 18; canvas->Font->Assign(Font); canvas->Brush->Color = FBackColor; canvas->Brush->Style = bsSolid; canvas->FillRect(rect); AnsiString name = "IDB_CHECK"; if (FChecked) name += "CHECKED"; if (!Enabled) name += "D"; Graphics::TBitmap* bmp = NULL; int offset; try { bmp = new Graphics::TBitmap(); bmp->LoadFromResourceName(0, name); int x = 0; canvas->Draw(x, 1, bmp); offset = x + bmp->Width + 4; delete bmp; bmp = NULL; } catch (Exception& e) { if (bmp) delete bmp; } rect.left += offset; rect.right -= 2; if (!Enabled) { canvas->Font->Color = FDisabledColor; TFontStyles fs; fs.Clear(); canvas->Font->Style = fs; } TRect calcrect = rect; DrawText(canvas->Handle, Caption.c_str(), Caption.Length(), &calcrect, DT_LEFT | DT_END_ELLIPSIS | DT_SINGLELINE | DT_VCENTER | DT_CALCRECT); DrawText(canvas->Handle, Caption.c_str(), Caption.Length(), &rect, DT_LEFT | DT_END_ELLIPSIS | DT_SINGLELINE | DT_VCENTER); InflateRect(&focusrect, 0, -1); focusrect.right = focusrect.left + calcrect.right - calcrect.left + 2; TControlCanvas* cnv = NULL; if (Focused()) { try { cnv = new TControlCanvas(); cnv->Control = this; DrawFocusRect(cnv->Handle, &focusrect); delete cnv; cnv = NULL; } catch (Exception& e) { if (cnv) delete cnv; DrawFocusRect(canvas->Handle, &focusrect); } } }
2158a2518e4d41324eb63ee63581c8d1c4389af2
4c1d515719425db127ba5285b5be4f03af10d5a1
/UVa-Judge/UVa_00278.cpp
c2c68df590d03c6662868456555e7c67a7545c6b
[]
no_license
matheusmtta/Competitive-Programming
26e51741332aed223b9231da33749940f5a1b977
e254b80090cc75bc213aad0a7957875842e90f1a
refs/heads/master
2023-04-28T18:08:51.417470
2023-04-24T21:09:00
2023-04-24T21:09:00
223,605,672
7
0
null
null
null
null
UTF-8
C++
false
false
385
cpp
#include <bits/stdc++.h> using namespace std; int main(){ int n; cin >> n; while (n--){ char type; int n, m; cin >> type >> n >> m; if (type == 'r') cout << min(n, m) << endl; else if (type == 'k') cout << ceil(((float)n*(float)m)/2) << endl; else if (type == 'Q') cout << min(n, m) << endl; else if (type == 'K') cout << (int)(ceil(n/2.0)*ceil(m/2.0)) << endl; } }
f5e01099593748904e289aa79903dc3b4c056cbb
8797457e4f6dadb0ed31e3a2116a8df2d924f72c
/RC4Algorithm.ino
ecfb8437e85c98d4318b8cd7ab63c38173b9e461
[ "BSD-3-Clause" ]
permissive
tinoest/ATMegaCode
2f6ab650e67920d082cd2b04b8df6123ef2b29b0
838375a76db0ddd06d6ed07c23e34930bc01101d
refs/heads/master
2021-01-19T01:59:20.893616
2017-01-15T23:24:27
2017-01-15T23:24:27
18,113,145
0
0
null
null
null
null
UTF-8
C++
false
false
3,198
ino
/* Copyright (c) 2016, tino, http://tinoest.co.uk 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. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 <string.h> // https://github.com/adamvr/arduino-base64 #include <Base64.h> void setup() { Serial.begin(9600); char key[] = "SecureKey"; char data[] = "Data to be encrypted"; Serial.print("Data : "); Serial.println(data); // Store dataLen for use in base64_encode as can't trust strlen due to possible null bytes in string int dataLen = strlen(data); int encodedLen = base64_enc_len(dataLen); char encoded[encodedLen]; // Input string is overwritten with encrypted data rc4(key,strlen(key),data,dataLen); Serial.print("Encrypted : "); Serial.println(data); base64_encode(encoded, data, dataLen); Serial.print("Encoded : "); Serial.println(encoded); int decodedLen = base64_dec_len(encoded, strlen(encoded)); char decoded[decodedLen]; base64_decode(decoded, encoded, strlen(encoded)); // Decoded is overwritted with decrypted string rc4(key,strlen(key),decoded,decodedLen); Serial.print("Decrypted : "); Serial.println(decoded); Serial.println(strlen(decoded)); } void loop() { } void rc4(char *key, uint16_t keySize, char *data, uint16_t dataSize) { uint8_t S[256]; for (uint16_t i = 0; i < 256; i++){ S[i] = i; } uint16_t j = 0; for (uint16_t i = 0; i < 256; i++){ j = (j + S[i] + key[i % keySize] ) % 256; // Start Swap uint8_t temp = S[i]; S[i] = S[j]; S[j] = temp; // Completed Swap } j = 0; uint16_t k = 0; for (uint16_t i = 0; i < dataSize; i++) { k = ( k + 1 ) % 256; j = ( j + S[k] ) % 256; //Start Swap uint8_t temp = S[k]; S[k] = S[j]; S[j] = temp; // Completed Swap data[i] = data[i] ^ S[(S[k]+S[j]) % 256]; } }
f902fd70d36e78ca4a575b3ef413886931b01f23
3c518dc9576291dbc4f44c0ebc9b1e27cf38df6b
/libs/ofxSvgLoader/src/ofxSvgBase.cpp
cca71ad612e55df548f828770e883f3bfa813513
[ "MIT" ]
permissive
moebiussurfing/ofxSCENE-SVG
031a60d31f60c80552e4da6c550ef31cc0df98d2
347c74ffcb7fc9f74942ba634be78e3defb9e36a
refs/heads/master
2023-08-18T10:44:29.637858
2023-08-06T06:26:26
2023-08-06T06:26:26
341,477,968
1
0
null
null
null
null
UTF-8
C++
false
false
12,987
cpp
// // ofxSvgBase.cpp // // Created by Nick Hardeman on 7/31/15. // #include "ofxSvgBase.h" map< string, ofxSvgText::Font > ofxSvgText::fonts; ofTrueTypeFont ofxSvgText::defaultFont; #pragma mark - ofxSvgBase //-------------------------------------------------------------- string ofxSvgBase::getTypeAsString() { switch (type) { case OFX_SVG_TYPE_GROUP: return "Group"; break; case OFX_SVG_TYPE_RECTANGLE: return "Rectangle"; break; case OFX_SVG_TYPE_IMAGE: return "Image"; break; case OFX_SVG_TYPE_ELLIPSE: return "Ellipse"; break; case OFX_SVG_TYPE_CIRCLE: return "Circle"; break; case OFX_SVG_TYPE_PATH: return "Path"; break; case OFX_SVG_TYPE_TEXT: return "Text"; break; default: break; } return "Unknown"; } //-------------------------------------------------------------- string ofxSvgBase::toString( int nlevel ) { string tstr = ""; for( int k = 0; k < nlevel; k++ ) { tstr += " "; } tstr += getTypeAsString() + " - " + getName() + "\n"; return tstr; } #pragma mark - ofxSvgText //-------------------------------------------------------------- void ofxSvgText::create() { meshes.clear(); // now lets sort the text based on meshes that we need to create // vector< TextSpan > tspans = textSpans; map< string, map< int, vector<TextSpan> > > tspanFonts; for( int i = 0; i < tspans.size(); i++ ) { if( tspanFonts.count( tspans[i].fontFamily ) == 0 ) { map< int, vector<TextSpan> > tmapap; tspanFonts[ tspans[i].fontFamily ] = tmapap; } map< int, vector<TextSpan> >& spanMap = tspanFonts[ tspans[i].fontFamily ]; if( spanMap.count(tspans[i].fontSize) == 0 ) { vector< TextSpan > tvec; spanMap[ tspans[i].fontSize ] = tvec; } spanMap[ tspans[i].fontSize ].push_back( tspans[i] ); } bool bHasFontDirectory = false; // cout << "checking directory: " << fdirectory+"/fonts/" << endl; string fontsDirectory = ofToDataPath("", true); if( fdirectory != "" ) { fontsDirectory = fdirectory;//+"/fonts/"; } if( ofFile::doesFileExist( fontsDirectory )) { bHasFontDirectory = true; } map< string, map< int, vector<TextSpan> > >::iterator mainIt; for( mainIt = tspanFonts.begin(); mainIt != tspanFonts.end(); ++mainIt ) { if( fonts.count(mainIt->first) == 0 ) { Font tafont; tafont.fontFamily = mainIt->first; fonts[ mainIt->first ] = tafont; } // now create a mesh for the family // // map< string, map<int, ofMesh> > meshes; if( meshes.count(mainIt->first) == 0 ) { map< int, ofMesh > tempMeshMap; meshes[ mainIt->first ] = tempMeshMap; } Font& tfont = fonts[ mainIt->first ]; map< int, ofMesh >& meshMap = meshes[ mainIt->first ]; map< int, vector<TextSpan> >::iterator vIt; for( vIt = mainIt->second.begin(); vIt != mainIt->second.end(); ++vIt ) { vector<TextSpan>& spanSpans = vIt->second; bool bFontLoadOk = true; if (tfont.sizes.count(vIt->first) == 0) { // string _filename, int _fontSize, bool _bAntiAliased, bool _bFullCharacterSet, bool _makeContours, float _simplifyAmt, int _dpi // first let's see if the fonts are provided. Some system fonts are .dfont that have several of the faces // in them, but OF isn't setup to parse them, so we need each bold, regular, italic, etc to be a .ttf font // string tfontPath = tfont.fontFamily; if (bHasFontDirectory) { cout << "ofxSvgBase :: starting off searching directory : " << fontsDirectory << endl; string tNewFontPath = ""; bool bFoundTheFont = _recursiveFontDirSearch(fontsDirectory, tfont.fontFamily, tNewFontPath); if (bFoundTheFont) { tfontPath = tNewFontPath; } /*ofDirectory tfDir; tfDir.listDir( fontsDirectory ); for( int ff = 0; ff < tfDir.size(); ff++ ) { ofFile tfFile = tfDir.getFile(ff); if( tfFile.getExtension() == "ttf" || tfFile.getExtension() == "otf" ) { cout << ff << " - font family: " << tfont.fontFamily << " file name: " << tfFile.getBaseName() << endl; if( ofToLower(tfFile.getBaseName()) == ofToLower(tfont.fontFamily) ) { ofLogNotice(" >> ofxSvgText found font file for " ) << tfont.fontFamily; tfontPath = tfFile.getAbsolutePath(); break; } } }*/ } cout << "Trying to load font from: " << tfontPath << endl; if (tfontPath == "") { bFontLoadOk = false; } else { // load(const std::string& _filename, int _fontSize, bool _bAntiAliased, bool _bFullCharacterSet, bool _makeContours, float _simplifyAmt, int _dpi) bFontLoadOk = tfont.sizes[vIt->first].load(tfontPath, vIt->first, true, true, false, 0.5, 72); } if(bFontLoadOk) { // tfont.sizes[ vIt->first ].setSpaceSize( 0.57 ); // tfont.sizes[ vIt->first ] = datFontTho; tfont.textures[ vIt->first ] = tfont.sizes[ vIt->first ].getFontTexture(); } else { ofLogError("ofxSvgLoader - error loading font family: ") << tfont.fontFamily << " size: " << vIt->first; tfont.sizes.erase(vIt->first); } } if( !bFontLoadOk ) continue; if( meshMap.count(vIt->first) == 0 ) { meshMap[ vIt->first ] = ofMesh(); } ofMesh& tmesh = meshMap[ vIt->first ]; if( !tfont.sizes.count( vIt->first ) ) { ofLogError("ofxSvgLoader - ") << "Could not find that font size in the map: " << vIt->first << endl; continue; } ofTrueTypeFont& ttfont = tfont.sizes[ vIt->first ]; for( int i = 0; i < spanSpans.size(); i++ ) { // create a mesh here // TextSpan& cspan = spanSpans[i]; if( cspan.text == "" ) continue; // cout << "font family: " << cspan.fontFamily << " size: " << cspan.fontSize << " text: " << cspan.text << endl; // const ofMesh& stringMesh = ttfont.getStringMesh( "please work", 20, 20 ); ofRectangle tempBounds = ttfont.getStringBoundingBox( cspan.text, 0, 0 ); float tffontx = bCentered ? cspan.rect.x - tempBounds.width/2 : cspan.rect.x; // const ofMesh& stringMesh = ttfont.getStringMesh( cspan.text, tffontx-ogPos.x, cspan.rect.y-ogPos.y ); const ofMesh& stringMesh = ttfont.getStringMesh( cspan.text, tffontx, cspan.rect.y ); int offsetIndex = tmesh.getNumVertices(); vector<ofIndexType> tsIndices = stringMesh.getIndices(); for( int k = 0; k < tsIndices.size(); k++ ) { tsIndices[k] = tsIndices[k] + offsetIndex; } ofFloatColor tcolor = cspan.color; vector< ofFloatColor > tcolors; tcolors.assign( stringMesh.getVertices().size(), tcolor ); tmesh.addIndices( tsIndices ); tmesh.addVertices( stringMesh.getVertices() ); tmesh.addTexCoords( stringMesh.getTexCoords() ); tmesh.addColors( tcolors ); } } } // now loop through and set the width and height of the text spans // for( int i = 0; i < textSpans.size(); i++ ) { TextSpan& tempSpan = textSpans[i]; ofTrueTypeFont& tfont = tempSpan.getFont(); if( tfont.isLoaded() ) { ofRectangle tempBounds = tfont.getStringBoundingBox( tempSpan.text, 0, 0 ); tempSpan.rect.width = tempBounds.width; tempSpan.rect.height = tempBounds.height; tempSpan.lineHeight = tfont.getStringBoundingBox("M", 0, 0).height; // tempSpan.rect.x = tempSpan.rect.x - ogPos.x; // tempSpan.rect.y = tempSpan.rect.x - ogPos.x; //tempSpan.rect.y -= tempSpan.lineHeight; } } } //-------------------------------------------------------------- void ofxSvgText::draw() { if( !isVisible() ) return; // map< string, map<int, ofMesh> > meshes; ofSetColor( 255, 255, 255, 255.f * alpha ); map< string, map<int, ofMesh> >::iterator mainIt; ofPushMatrix(); { // ofSetColor( 255, 0, 0 ); // ofDrawCircle(pos, 6); // ofNoFill(); // ofSetColor( 0, 0, 224 ); // ofDrawCircle( ogPos, 10); // ofDrawRectangle(getRectangle()); // ofFill(); ofTranslate( pos.x, pos.y ); // ofSetColor( 255, 255, 255, 255.f * alpha ); if( rotation > 0 ) ofRotateZDeg( rotation ); ofTexture* tex = NULL; for( mainIt = meshes.begin(); mainIt != meshes.end(); ++mainIt ) { string fontFam = mainIt->first; map< int, ofMesh >::iterator mIt; for( mIt = meshes[ fontFam ].begin(); mIt != meshes[ fontFam ].end(); ++mIt ) { int fontSize = mIt->first; // let's check to make sure that the texture is there, so that we can bind it // bool bHasTexture = false; // static map< string, Font > fonts; if( fonts.count( fontFam ) ) { if( fonts[ fontFam ].textures.count( fontSize ) ) { bHasTexture = true; tex = &fonts[ fontFam ].textures[ fontSize ]; } } if( bHasTexture ) tex->bind(); ofMesh& tMeshMesh = mIt->second; vector< ofFloatColor >& tcolors = tMeshMesh.getColors(); for( auto& tc : tcolors ) { if( bOverrideColor ) { tc = _overrideColor; } else { tc.a = alpha; } } tMeshMesh.draw(); if( bHasTexture ) tex->unbind(); } } } ofPopMatrix(); } //-------------------------------------------------------------- bool ofxSvgText::_recursiveFontDirSearch(string afile, string aFontFamToLookFor, string& fontpath) { if (fontpath != "") { return true; } ofFile tfFile( afile, ofFile::Reference ); if (tfFile.isDirectory()) { cout << "ofxSvgText :: searching in directory : " << afile << " | " << ofGetFrameNum() << endl; ofDirectory tdir; tdir.listDir(afile); for (int i = 0; i < tdir.size(); i++) { bool youGoodOrWhat = _recursiveFontDirSearch(tdir.getPath(i), aFontFamToLookFor, fontpath); if( youGoodOrWhat ) { return true; } } } else { if ( tfFile.getExtension() == "ttf" || tfFile.getExtension() == "otf") { if (ofToLower( tfFile.getBaseName() ) == ofToLower(aFontFamToLookFor)) { ofLogNotice("ofxSvgText found font file for ") << aFontFamToLookFor; fontpath = tfFile.getAbsolutePath(); return true; } string tAltFileName = ofToLower(tfFile.getBaseName()); ofStringReplace(tAltFileName, " ", "-"); if (tAltFileName == ofToLower(aFontFamToLookFor)) { ofLogNotice("ofxSvgText found font file for ") << aFontFamToLookFor; fontpath = tfFile.getAbsolutePath(); return true; } } } return false; } // must return a reference for some reason here // //-------------------------------------------------------------- ofTrueTypeFont& ofxSvgText::TextSpan::getFont() { if( ofxSvgText::fonts.count( fontFamily ) ) { Font& tfont = fonts[ fontFamily ]; if( tfont.sizes.count(fontSize) ) { ofTrueTypeFont& tempFont = tfont.sizes[ fontSize ]; return tempFont; } } return defaultFont; } // get the bounding rect for all of the text spans in this svg'ness // should be called after create // //-------------------------------------------------------------- ofRectangle ofxSvgText::getRectangle() { ofRectangle temp( 0, 0, 1, 1 ); for( int i = 0; i < textSpans.size(); i++ ) { ofRectangle trect = textSpans[i].rect; trect.x = trect.x;// - ogPos.x; trect.y = trect.y;// - ogPos.y; trect.y -= textSpans[i].lineHeight; if( i == 0 ) { temp = trect; } else { temp.growToInclude( trect ); } } temp.x += pos.x; temp.y += pos.y; return temp; }
b875fd52ff706b70876571e608e5f40811d77a41
375d22f69216ed0bd039efabad258246a5e3210b
/src/FFTWave.hpp
d621b0b55ac24aca9fec0afad758f235f461553f
[]
no_license
nasymt/exGois_visual
b93c62d435cc5ca74194f9dc1f22693fc62ae021
5e5d37983c4d4dcc1d9c4e6be8fa107dbed00247
refs/heads/master
2016-09-13T05:39:10.909716
2016-04-16T11:34:13
2016-04-16T11:34:13
56,380,386
0
0
null
null
null
null
UTF-8
C++
false
false
841
hpp
// // FFTWave.hpp // vjTest_OSC01 // // Created by 松岡正 on 2015/12/05. // // #ifndef FFTWave_hpp #define FFTWave_hpp #include "ofMain.h" #define WAVE_NUM 1000 #define LIGHT_NUM 20 #endif /* FFTWave_hpp */ class FFTWave{ public: void setup(); void update(float * buf,int i); void draw(int i); void light(int i,bool b); void triRotation(); float buffer[WAVE_NUM]; float pre_buffer,val,pre_val; float ave_range; float new_val; ofTexture texture; ofPoint pos1; ofPoint pos2; ofPoint pos3; ofPoint pos4; ofVec3f lightColor; int MAXLightSize; int lightSize; bool bLight; int alpha; int scene; //--------triangle int tri_angle; ofVec3f triPos; int triPosLeft_Right; int triPos2; float speed; ofVec3f targetPos; };
8ecac3ffd0a2cef89a6480238971621fbf615396
42c9b0ffa6c1a8225be32e2caf6cd238fe9a245b
/Client/ShopWnd.h
64e2442a23fc6ef66d310b90c3caa0c9487fff48
[]
no_license
hjyu94/talesweaver
fd9f5fc5ff6a9a33cf445a0bb03dac63406c285d
71ee67ca9dfc663ccc8a79f1da039009530a8be7
refs/heads/master
2022-11-22T20:34:01.133203
2020-07-28T06:34:58
2020-07-28T06:34:58
283,120,242
0
2
null
null
null
null
UHC
C++
false
false
917
h
#pragma once #include "WndUI.h" #include "Item.h" class CNpc; class CShopWnd : public CWndUI { public: CShopWnd(); virtual ~CShopWnd(); public: // CWndUI을(를) 통해 상속됨 virtual void Update_World_Matrix(void); virtual void Update_State(void); virtual HRESULT Initialize(void) override; virtual int Progress(void) override; virtual void Render(void) override; virtual void Release(void) override; public: void Set_Owner(CNpc* pNpc); public: enum SCROLLID { S_UP, S_SCROLL_MIN, S_SCROLL_MAX, S_DOWN, S_END }; private: D3DXVECTOR3 m_vImgPos[12]; RECT m_ImgRect[12]; D3DXVECTOR3 m_vNamePos[12]; // Left-top RECT m_NameRect[12]; D3DXVECTOR3 m_vCostPos[12]; // Left-top RECT m_CostRect[12]; vector<CItem*>* m_pShopInven; bool m_bScrollNeed = false; int m_iScrollStart = 0; D3DXVECTOR3 m_vecScroll[S_END]; RECT m_rcScroll[S_END]; float m_fClickTime = 0.f; };
91f2e34d340293df9c99435ec86fdc82de319a56
bac7267590c6267b489178c8717e42a1865bb46b
/WildMagic5/SampleGraphics/ShadowMaps/SMShadowEffect.cpp
3a66a67302b6fc49b733da9a5b053d13784d0e33
[]
no_license
VB6Hobbyst7/GeometricTools-Apple
1e53f260e84f8942e12adf7591b83ba2dd46a7f1
07b9764871a9dbe1240b6181039dd703e118a628
refs/heads/master
2021-02-11T11:17:56.813941
2013-11-26T15:25:10
2013-11-26T15:25:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,499
cpp
// Geometric Tools, LLC // Copyright (c) 1998-2013 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // // File Version: 5.0.0 (2010/01/01) #include "SMShadowEffect.h" #include "Wm5WMatrixConstant.h" using namespace Wm5; WM5_IMPLEMENT_RTTI(Wm5, GlobalEffect, SMShadowEffect); WM5_IMPLEMENT_STREAM(SMShadowEffect); WM5_IMPLEMENT_FACTORY(SMShadowEffect); //---------------------------------------------------------------------------- SMShadowEffect::SMShadowEffect (const std::string& effectName, ShaderFloat* lightPVMatrix) { VisualEffect* effect = VisualEffect::LoadWMFX(effectName); mInstance = new0 VisualEffectInstance(effect, 0); mInstance->SetVertexConstant(0, 0, new0 WMatrixConstant()); mInstance->SetVertexConstant(0, 1, lightPVMatrix); } //---------------------------------------------------------------------------- SMShadowEffect::~SMShadowEffect () { } //---------------------------------------------------------------------------- void SMShadowEffect::Draw (Renderer* renderer, const VisibleSet& visibleSet) { const int numVisible = visibleSet.GetNumVisible(); for (int j = 0; j < numVisible; ++j) { // Replace the object's effect instance by the shadow-effect instance. Visual* visual = (Visual*)visibleSet.GetVisible(j); VisualEffectInstancePtr save = visual->GetEffectInstance(); visual->SetEffectInstance(mInstance); // Draw the object using the shadow effect. renderer->Draw(visual); // Restore the object's effect instance. visual->SetEffectInstance(save); } } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // Name support. //---------------------------------------------------------------------------- Object* SMShadowEffect::GetObjectByName (const std::string& name) { Object* found = GlobalEffect::GetObjectByName(name); if (found) { return found; } WM5_GET_OBJECT_BY_NAME(mInstance, name, found); return 0; } //---------------------------------------------------------------------------- void SMShadowEffect::GetAllObjectsByName (const std::string& name, std::vector<Object*>& objects) { GlobalEffect::GetAllObjectsByName(name, objects); WM5_GET_ALL_OBJECTS_BY_NAME(mInstance, name, objects); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // Streaming support. //---------------------------------------------------------------------------- SMShadowEffect::SMShadowEffect (LoadConstructor value) : GlobalEffect(value) { } //---------------------------------------------------------------------------- void SMShadowEffect::Load (InStream& source) { WM5_BEGIN_DEBUG_STREAM_LOAD(source); GlobalEffect::Load(source); source.ReadPointer(mInstance); WM5_END_DEBUG_STREAM_LOAD(SMShadowEffect, source); } //---------------------------------------------------------------------------- void SMShadowEffect::Link (InStream& source) { GlobalEffect::Link(source); source.ResolveLink(mInstance); } //---------------------------------------------------------------------------- void SMShadowEffect::PostLink () { GlobalEffect::PostLink(); } //---------------------------------------------------------------------------- bool SMShadowEffect::Register (OutStream& target) const { if (GlobalEffect::Register(target)) { target.Register(mInstance); return true; } return false; } //---------------------------------------------------------------------------- void SMShadowEffect::Save (OutStream& target) const { WM5_BEGIN_DEBUG_STREAM_SAVE(target); GlobalEffect::Save(target); target.WritePointer(mInstance); WM5_END_DEBUG_STREAM_SAVE(SMShadowEffect, target); } //---------------------------------------------------------------------------- int SMShadowEffect::GetStreamingSize () const { int size = GlobalEffect::GetStreamingSize(); size += WM5_POINTERSIZE(mInstance); return size; } //----------------------------------------------------------------------------
[ "tprepscius" ]
tprepscius
1d4abe13437937775b31aad74ceb3751c532be99
25a94f26f9af2b8f7a83f7d5aa20416b5482f32b
/Hard/Spiral Matrix.cpp
13a7f23d71fd03a0be796e030ab9ae49b89aa871
[]
no_license
deeparac/Algorithms
83f6c1b8d1f2719c5026ec5f52c861c226df5922
b61ba4c928f7c36178e1e31a06e91f98ada7cbf1
refs/heads/master
2021-05-12T10:43:02.078868
2018-02-13T04:11:49
2018-02-13T04:11:49
117,357,730
0
0
null
null
null
null
UTF-8
C++
false
false
1,069
cpp
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { int m = matrix.size(); if (m == 0) { return vector<int>(); } int n = matrix[0].size(); vector<int> rst; int i = 0; int j = 0; int dir = 0; int dx[] = {0, 1, 0, -1}; int dy[] = {1, 0, -1, 0}; while (rst.size() != m * n) { if (checker(matrix, i, j, dir)) { rst.push_back(matrix[i][j]); matrix[i][j] = INT_MAX; } else { i -= dx[dir % 4]; j -= dy[dir % 4]; ++dir; } i += dx[dir % 4]; j += dy[dir % 4]; cout << rst.back(); } return rst; } private: bool checker(vector<vector<int>>& matrix, int i, int j, int dir) { if (i < 0 || i >= matrix.size() || j < 0 || j >= matrix[0].size() || matrix[i][j] == INT_MAX) { return false; } return true; } };
c8f535e3c8dc40d85cfc1b98c5fb1456deaabede
338bbf8f09fd21a8a163a10163f96f77308400ba
/Ssm/SsmConditionBase.h
c61bc277eda7453aee19888a6bc08735b94c3911
[]
no_license
ToddHoff/fgen
c7a2d52f26f94d1e1154aad9e051404c002d539c
8a28574e0289c05c97447cc009e56b06af87ed16
refs/heads/master
2021-01-24T13:19:31.069130
2018-02-27T19:01:10
2018-02-27T19:01:10
123,171,415
1
0
null
null
null
null
UTF-8
C++
false
false
3,415
h
#ifndef _SsmConditionBase_h_ #define _SsmConditionBase_h_ #include "Util/Typeable.h" // USES typeable #include "Util/LnStream.h" // USES streams #include "Util/Dumpable.h" // ISA dumpable class SsmDependencyBase; /** * SsmConditionBase is a base class for conditions in Ssm. Classes * are expected to derive from this class and implement specific * condition behaviour. */ class SsmConditionBase : public Dumpable { public: // LIFECYLCE /** * Destroy the object. It's virtual so all derived classes will be * deleted as well. */ virtual ~SsmConditionBase(); // OPERATORS /** * Output object to a given stream. * * @param s The output stream to write to. * @param o The object to print. * * @return The stream written to. */ friend ostream& operator << (ostream& s, const SsmConditionBase& o); /** * Output the object to a stream. Because this method * is virtual the most derived class is dumped. Derived class should override * this method to dump actor specific state. Remeber to chain the dump * methods together. * * @param s The output stream to write to. * @param fmt The format of the output to write to the stream. * @param depth The indentation level this object should be output at. * * @return The stream written to. * * @see Module#Dump */ virtual ostream& Dump(ostream& s, DumpType fmt= DUMP_DEBUG , int depth= 0) const; // ACTIONS /** * An event arrived for the condition. It's up to the condition * to understand the event and determine if the * * @param pEvent The event for the condition to evaluate. * Memory: BORROWED. */ virtual LnStatus InjectEvent(Typeable* pEvent) = 0; /** * Is the condition satisfied? * * @return true if this condition has been satisfied. */ virtual bool IsSatisfied(void) const = 0; /** * Set the condition to false. */ virtual void Clear(void) = 0; /** * Return true if this condition should have its initial condition * determined. * * @return true If this condition should have its initial condition * determined. */ virtual bool IsResolveInitial(void) const = 0; /** * Return the dependency associated with the condition. * * @return Return the dependency associated with the condition. */ virtual SsmDependencyBase& Dependency(void) = 0; /** * Get this initial condition for this condition. It will block * until the condition is resolved or a non-recoverable failure * has occured. * * @return LN_OK if the condition was determined, LN_FAIL if * the condition could not be determined. * * @exception ComExecption * @exception TBD */ virtual LnStatus DetermineInitialCondition(void) = 0; /** * Description of the condition. It should be some string that can * be used to know which condition it is. Mainly used for debugging. * * @return A description of the condition. */ virtual const char* Description(void) const = 0; /** * Get the condition name. */ virtual const char* GetConditionName(void) const = 0; /** * Get the source ID. */ virtual uint32 GetSourceId(void) const = 0; private: }; #endif // _SsmConditionBase_h_
1434b26196a2dd17ccd8b1edd92078715375db96
5ab7336dbeccc84cb6a12418b06bd8a8f1310633
/cutted-segments.cpp
f7e0455a77a3cd1097ae3835fd8c8594a5edce89
[]
no_license
MrStrange124/gfg-coding-questions
6895ef70bf987cc699ca72f7568b4d62af345d74
39187624da05827d0802978d9853ac2fa2327cf1
refs/heads/main
2023-08-28T02:24:40.327971
2021-10-08T17:19:26
2021-10-08T17:19:26
385,684,805
0
0
null
null
null
null
UTF-8
C++
false
false
1,081
cpp
// { Driver Code Starts #include <bits/stdc++.h> using namespace std; // } Driver Code Ends class Solution { public: //Function to find the maximum number of cuts. int maximizeTheCuts(int n, int x, int y, int z) { int dp[n + 1]; memset(dp, 0, sizeof(dp)); for (int i = x; i <= n; i += x) dp[i] = dp[i - x] + 1; for (int i = y; i <= n; i++) if (dp[i - y] || i == y) dp[i] = max(dp[i], dp[i - y] + 1); for (int i = z; i <= n; i++) if (dp[i - z] || i == z) dp[i] = max(dp[i], dp[i - z] + 1); return dp[n]; } }; // { Driver Code Starts. int main() { //taking testcases int t; cin >> t; while (t--) { //taking length of line segment int n; cin >> n; //taking types of segments int x, y, z; cin >> x >> y >> z; Solution obj; //calling function maximizeTheCuts() cout << obj.maximizeTheCuts(n, x, y, z) << endl; } return 0; } // } Driver Code Ends
dd6041f1fbb73afc5cbf952a8f9537e518410400
6bac2ab062408e5fa75acb909161cea2d04e3194
/Model.cpp
e3a2e017d4b6363a6c387565eb1d9a1f9bdf3ac2
[]
no_license
atomsfat/arduino-timer
02856d19f52ae8da4485c20a65b69257bba90afb
7e0f05630bbead2b58c2cf2b73429aada7691cff
refs/heads/master
2020-05-18T16:33:32.173434
2013-08-27T03:01:47
2013-08-27T03:01:47
2,339,407
0
0
null
null
null
null
UTF-8
C++
false
false
896
cpp
/* * File: Model.cpp * Author: atoms * * Created on March 8, 2010, 11:28 PM */ #include "Model.h" Model::Model() { // this->hora = hora; this->boilerOn = false; this->howTimeOn = 0; this->whenItStarted = 0; this->whenToturnOff = 0; for(int i=0;i<2;i++){ this->programs[i].hourPG1 = 0; this->programs[i].minutePG1 = 0; this->programs[i].minutesOnPG1 = 0; this->programs[i].dayPG1 = 0; if(this->programs[i].hourPG1 > 24 || this->programs[i].minutePG1> 60){ this->programs[i].hourPG1= 0; this->programs[i].minutePG1= 0; this->programs[i].minutesOnPG1 = 0; } if(this->programs[i].dayPG1>127){ this->programs[i].dayPG1 = 0; } } } Model::~Model() { } void Model::savePG1(){ // EEPROM.write(1,this-> hourPG1 ); // EEPROM.write(2,this->minutePG1 ); // EEPROM.write(3,this->minutesOnPG1 ); // EEPROM.write(4,this->dayPG1 ); }
f9ac8a993ff2bf7d2140672d54e6033dad3eb2e8
bd5a2ede51bbcdcfbee9654b234464f63244abfb
/src/luanode_constants.cpp
66fe5464578e6006626302a0b8d98a2425550715
[ "MIT" ]
permissive
sysnajar/LuaNode
eceed1ab72fe4578f11e8bc9be6de4e3b4fda184
35339c278023de9c12dcf8c7c32ea60f2686123a
refs/heads/master
2021-01-15T10:25:47.043514
2014-11-17T15:01:44
2014-11-17T15:01:44
29,317,745
1
0
null
2015-01-15T20:54:20
2015-01-15T20:54:19
null
UTF-8
C++
false
false
3,165
cpp
#include "stdafx.h" #include "luanode.h" #include "luanode_constants.h" #include <errno.h> #define SET_BOOST_ERR_FIELD(e, v) lua_pushinteger(L, boost::asio::error::e); lua_setfield(L, t, #v); #if defined (_WIN32) # define SET_ERR_FIELD(e) lua_pushinteger(L, WSA ## e); lua_setfield(L, t, #e); #else # define SET_ERR_FIELD(e) lua_pushinteger(L, e); lua_setfield(L, t, #e); #endif void LuaNode::DefineConstants(lua_State* L) { lua_newtable(L); int t = lua_gettop(L); lua_pushinteger(L, boost::asio::error::eof); lua_setfield(L, t, "EOF"); SET_BOOST_ERR_FIELD(access_denied, EACCES); SET_BOOST_ERR_FIELD(address_family_not_supported, EAFNOSUPPORT); SET_BOOST_ERR_FIELD(address_in_use, EADDRINUSE); SET_BOOST_ERR_FIELD(already_connected, EISCONN); SET_BOOST_ERR_FIELD(already_started, EALREADY); SET_BOOST_ERR_FIELD(broken_pipe, EPIPE); SET_BOOST_ERR_FIELD(connection_aborted, ECONNABORTED); SET_BOOST_ERR_FIELD(connection_refused, ECONNREFUSED); SET_BOOST_ERR_FIELD(connection_reset, ECONNRESET); SET_BOOST_ERR_FIELD(bad_descriptor, EBADF); SET_BOOST_ERR_FIELD(fault, EFAULT); SET_BOOST_ERR_FIELD(host_unreachable, EHOSTUNREACH); SET_BOOST_ERR_FIELD(in_progress, EINPROGRESS); SET_BOOST_ERR_FIELD(interrupted, EINTR); SET_BOOST_ERR_FIELD(invalid_argument, EINVAL); SET_BOOST_ERR_FIELD(message_size, EMSGSIZE); SET_BOOST_ERR_FIELD(name_too_long, ENAMETOOLONG); SET_BOOST_ERR_FIELD(network_down, ENETDOWN); SET_BOOST_ERR_FIELD(network_reset, ENETRESET); SET_BOOST_ERR_FIELD(network_unreachable, ENETUNREACH); SET_BOOST_ERR_FIELD(no_descriptors, EMFILE); SET_BOOST_ERR_FIELD(no_buffer_space, ENOBUFS); SET_BOOST_ERR_FIELD(no_memory, ENOMEM); SET_BOOST_ERR_FIELD(no_permission, EPERM); SET_BOOST_ERR_FIELD(no_protocol_option, ENOPROTOOPT); SET_BOOST_ERR_FIELD(not_connected, ENOTCONN); SET_BOOST_ERR_FIELD(not_socket, ENOTSOCK); SET_BOOST_ERR_FIELD(operation_aborted, ECANCELED); SET_BOOST_ERR_FIELD(operation_not_supported, EOPNOTSUPP); SET_BOOST_ERR_FIELD(shut_down, ESHUTDOWN); SET_BOOST_ERR_FIELD(timed_out, ETIMEDOUT); SET_BOOST_ERR_FIELD(try_again, EAGAIN); SET_BOOST_ERR_FIELD(would_block, EWOULDBLOCK); SET_BOOST_ERR_FIELD(host_not_found, HOST_NOT_FOUND); SET_BOOST_ERR_FIELD(host_not_found_try_again, TRY_AGAIN); SET_BOOST_ERR_FIELD(no_data, NO_DATA); SET_BOOST_ERR_FIELD(no_recovery, NO_RECOVERY); #ifdef EPROCLIM SET_ERR_FIELD(EPROCLIM); #endif #ifdef WSAEPROCLIM SET_ERR_FIELD(EPROCLIM); #endif #ifdef EDESTADDRREQ SET_ERR_FIELD(EDESTADDRREQ); #endif #ifdef EPROTOTYPE SET_ERR_FIELD(EPROTOTYPE); #endif #ifdef EPROTONOSUPPORT SET_ERR_FIELD(EPROTONOSUPPORT); #endif #if defined(ESOCKTNOSUPPORT) || defined(WSAESOCKTNOSUPPORT) SET_ERR_FIELD(ESOCKTNOSUPPORT); #endif #if defined(EPFNOSUPPORT) || defined(WSAEPFNOSUPPORT) SET_ERR_FIELD(EPFNOSUPPORT); #endif #ifdef EADDRNOTAVAIL SET_ERR_FIELD(EADDRNOTAVAIL); #endif #if defined(EHOSTDOWN) || defined(WSAEHOSTDOWN) SET_ERR_FIELD(EHOSTDOWN); #endif #if defined(EDISCON) || defined(WSAEDISCON) SET_ERR_FIELD(EDISCON); #endif } #undef SET_ERR_FIELD
abb3159a96fb9e478f518caeb61880b02df87665
56f2125486b51061833ba71d20529c5dfb7cd6a3
/mitsuba/include/mitsuba/render/imageproc.h
33b77706a5c63b0db5ac087c5fb32fc451a4f961
[]
no_license
xycruise/3D_Hair_Rendering
666f67174330476330b3af425a6dc40fc2c9a2e5
54b40453a450f06e31087d654caf5148513aba40
refs/heads/master
2020-05-29T21:19:20.122583
2012-11-08T12:59:38
2012-11-08T12:59:38
6,596,455
0
1
null
null
null
null
UTF-8
C++
false
false
2,327
h
/* This file is part of Mitsuba, a physically based rendering system. Copyright (c) 2007-2011 by Wenzel Jakob and others. Mitsuba is free software; 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. Mitsuba 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 along with this program. If not, see <http://www.gnu.org/licenses/>. */ #if !defined(__IMAGEPROC_H) #define __IMAGEPROC_H #include <mitsuba/core/sched.h> MTS_NAMESPACE_BEGIN /** * Abstract parallel process, which performs a certain task (to be defined by * the subclass) on the pixels of an image where work on adjacent pixels * is independent. For preview purposes, a spiraling pattern of square * pixel blocks is generated. * * \ingroup librender */ class MTS_EXPORT_RENDER BlockedImageProcess : public ParallelProcess { public: // ====================================================================== //! @{ \name Implementation of the ParallelProcess interface // ====================================================================== virtual EStatus generateWork(WorkUnit *unit, int worker); //! @} // ====================================================================== MTS_DECLARE_CLASS() protected: /** * Initialize the image process * * \param offset * Integer offset of the image region to be processed * \param size * Size of the image region to be processed * \param blockSize * Size of the generated square pixel blocks */ void init(const Point2i &offset, const Vector2i &size, int blockSize); /// Protected constructor inline BlockedImageProcess() { } /// Virtual destructor virtual ~BlockedImageProcess() { } protected: enum EDirection { ERight = 0, EDown, ELeft, EUp }; Point2i m_offset; Vector2i m_size, m_numBlocks; Point2i m_curBlock; int m_direction, m_numSteps; int m_stepsLeft, m_numBlocksTotal; int m_numBlocksGenerated; int m_blockSize; }; MTS_NAMESPACE_END #endif /* __IMAGEPROC_H */
c34348a31ec66b2f205a52bd518ead69e0bb93b9
f60dab30f8a7b97c1136cec336b60613a9bf32e1
/AbstractHardware/Registers/GD32VF103/FieldValues/i2c0fieldvalues.hpp
01f32c0b38f0283f9fa91a281f6b082c10e40004
[ "MIT" ]
permissive
lamer0k/GD32VF103
49bf4c9df9a1f600ee2d7c9f94797b3ee96e45ae
fd90f459037a502b2e8e9dcb79ae0107a35c0977
refs/heads/master
2022-12-12T04:36:45.110796
2020-09-01T17:37:53
2020-09-01T17:37:53
290,263,836
3
0
null
2020-08-25T16:30:21
2020-08-25T16:17:12
C++
UTF-8
C++
false
false
16,789
hpp
/******************************************************************************* * Filename : i2c0fieldvalues.hpp * * Details : Enumerations related with I2C0 peripheral. This header file is * auto-generated for GD32VF103 device. * * *******************************************************************************/ #if !defined(I2C0ENUMS_HPP) #define I2C0ENUMS_HPP #include "fieldvalue.hpp" //for FieldValues template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_CTL0_SRESET_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_CTL0_SRESET_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_CTL0_SRESET_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_CTL0_SALT_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_CTL0_SALT_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_CTL0_SALT_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_CTL0_PECTRANS_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_CTL0_PECTRANS_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_CTL0_PECTRANS_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_CTL0_POAP_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_CTL0_POAP_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_CTL0_POAP_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_CTL0_ACKEN_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_CTL0_ACKEN_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_CTL0_ACKEN_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_CTL0_STOP_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_CTL0_STOP_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_CTL0_STOP_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_CTL0_START_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_CTL0_START_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_CTL0_START_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_CTL0_SS_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_CTL0_SS_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_CTL0_SS_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_CTL0_GCEN_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_CTL0_GCEN_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_CTL0_GCEN_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_CTL0_PECEN_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_CTL0_PECEN_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_CTL0_PECEN_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_CTL0_ARPEN_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_CTL0_ARPEN_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_CTL0_ARPEN_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_CTL0_SMBSEL_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_CTL0_SMBSEL_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_CTL0_SMBSEL_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_CTL0_SMBEN_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_CTL0_SMBEN_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_CTL0_SMBEN_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_CTL0_I2CEN_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_CTL0_I2CEN_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_CTL0_I2CEN_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_CTL1_DMALST_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_CTL1_DMALST_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_CTL1_DMALST_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_CTL1_DMAON_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_CTL1_DMAON_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_CTL1_DMAON_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_CTL1_BUFIE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_CTL1_BUFIE_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_CTL1_BUFIE_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_CTL1_EVIE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_CTL1_EVIE_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_CTL1_EVIE_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_CTL1_ERRIE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_CTL1_ERRIE_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_CTL1_ERRIE_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_CTL1_I2CCLK_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_SADDR0_ADDFORMAT_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_SADDR0_ADDFORMAT_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_SADDR0_ADDFORMAT_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_SADDR0_ADDRESS9_8_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_SADDR0_ADDRESS9_8_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_SADDR0_ADDRESS9_8_Values, BaseType, 1U> ; using Value2 = FieldValue<I2C0_SADDR0_ADDRESS9_8_Values, BaseType, 2U> ; using Value3 = FieldValue<I2C0_SADDR0_ADDRESS9_8_Values, BaseType, 3U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_SADDR0_ADDRESS7_1_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_SADDR0_ADDRESS0_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_SADDR0_ADDRESS0_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_SADDR0_ADDRESS0_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_SADDR1_ADDRESS2_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_SADDR1_DUADEN_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_SADDR1_DUADEN_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_SADDR1_DUADEN_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_DATA_TRB_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_STAT0_SMBALT_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_STAT0_SMBALT_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_STAT0_SMBALT_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_STAT0_SMBTO_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_STAT0_SMBTO_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_STAT0_SMBTO_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_STAT0_PECERR_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_STAT0_PECERR_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_STAT0_PECERR_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_STAT0_OUERR_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_STAT0_OUERR_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_STAT0_OUERR_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_STAT0_AERR_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_STAT0_AERR_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_STAT0_AERR_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_STAT0_LOSTARB_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_STAT0_LOSTARB_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_STAT0_LOSTARB_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_STAT0_BERR_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_STAT0_BERR_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_STAT0_BERR_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_STAT0_TBE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_STAT0_TBE_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_STAT0_TBE_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_STAT0_RBNE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_STAT0_RBNE_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_STAT0_RBNE_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_STAT0_STPDET_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_STAT0_STPDET_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_STAT0_STPDET_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_STAT0_ADD10SEND_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_STAT0_ADD10SEND_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_STAT0_ADD10SEND_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_STAT0_BTC_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_STAT0_BTC_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_STAT0_BTC_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_STAT0_ADDSEND_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_STAT0_ADDSEND_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_STAT0_ADDSEND_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_STAT0_SBSEND_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_STAT0_SBSEND_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_STAT0_SBSEND_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_STAT1_PECV_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_STAT1_DUMODF_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_STAT1_DUMODF_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_STAT1_DUMODF_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_STAT1_HSTSMB_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_STAT1_HSTSMB_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_STAT1_HSTSMB_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_STAT1_DEFSMB_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_STAT1_DEFSMB_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_STAT1_DEFSMB_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_STAT1_RXGC_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_STAT1_RXGC_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_STAT1_RXGC_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_STAT1_TR_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_STAT1_TR_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_STAT1_TR_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_STAT1_I2CBSY_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_STAT1_I2CBSY_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_STAT1_I2CBSY_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_STAT1_MASTER_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_STAT1_MASTER_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_STAT1_MASTER_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_CKCFG_FAST_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_CKCFG_FAST_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_CKCFG_FAST_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_CKCFG_DTCY_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<I2C0_CKCFG_DTCY_Values, BaseType, 0U> ; using Value1 = FieldValue<I2C0_CKCFG_DTCY_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_CKCFG_CLKC_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct I2C0_RT_RISETIME_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; #endif //#if !defined(I2C0ENUMS_HPP)
b8ffb4c34fbcd6e7ee329f81cf83e6ec559d2c36
d71fad53d1149313e44c99e0be9d0c4f6a62a6f6
/ChaosEngine/Source/ChaosCore/include/ChaosCore/Multithreading/Functions/FunctionWrapper.h
9de9f3cd914e6a7b71d094897319fb3a93edb685
[]
no_license
W1lliam/ChaosEngine
217e3d5f77447b5c3b1323be52f0cfc2e52fc9ae
2ed45d79c4546894b1276d8f09823d51540383ad
refs/heads/master
2020-06-04T19:00:52.880249
2019-06-16T06:30:08
2019-06-16T06:30:08
192,155,302
2
0
null
null
null
null
UTF-8
C++
false
false
997
h
#pragma once #include "ChaosCore/chaos_core_pch.h" namespace Chaos::Functions { class FunctionWrapper { struct FuncBase { virtual void Call() = 0; virtual ~FuncBase() = default; }; template<typename F> struct FuncType : FuncBase { F f; FuncType(F&& f_) : f(std::move(f_)) {} void Call() override { f(); } }; public: FunctionWrapper() = default; explicit FunctionWrapper(FunctionWrapper&& other) noexcept : m_func(std::move(other.m_func)) {} template<typename F> FunctionWrapper(F&& f) : m_func(new FuncType<F>(std::move(f))) {} FunctionWrapper& operator=(FunctionWrapper&& other) noexcept { m_func = std::move(other.m_func); return *this; } void operator()() const { m_func->Call(); } FunctionWrapper(const FunctionWrapper&) = delete; FunctionWrapper(const FunctionWrapper&&) = delete; FunctionWrapper& operator=(const FunctionWrapper&) = delete; private: std::unique_ptr<FuncBase> m_func; }; }
1d31f6d11a200c03476b32a7c8fd8aef31ce5abc
7e167301a49a7b7ac6ff8b23dc696b10ec06bd4b
/prev_work/opensource/fMRI/FSL/fsl/extras/include/boost/boost/mpl/bool.hpp
ba1b35200f5d4ded9e99abe1113fd0be7a44fb05
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Sejik/SignalAnalysis
6c6245880b0017e9f73b5a343641065eb49e5989
c04118369dbba807d99738accb8021d77ff77cb6
refs/heads/master
2020-06-09T12:47:30.314791
2019-09-06T01:31:16
2019-09-06T01:31:16
193,439,385
5
4
null
null
null
null
UTF-8
C++
false
false
1,038
hpp
#ifndef BOOST_MPL_BOOL_HPP_INCLUDED #define BOOST_MPL_BOOL_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-2004 // // 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) // // See http://www.boost.org/libs/mpl for documentation. // $Source: /usr/local/share/sources/boost/boost/mpl/bool.hpp,v $ // $Date: 2007/06/12 15:03:23 $ // $Revision: 1.1.1.1 $ #include <boost/mpl/bool_fwd.hpp> #include <boost/mpl/integral_c_tag.hpp> #include <boost/mpl/aux_/config/static_constant.hpp> BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_OPEN template< bool C_ > struct bool_ { BOOST_STATIC_CONSTANT(bool, value = C_); typedef integral_c_tag tag; typedef bool_ type; typedef bool value_type; operator bool() const { return this->value; } }; #if !defined(BOOST_NO_INCLASS_MEMBER_INITIALIZATION) template< bool C_ > bool const bool_<C_>::value; #endif BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_CLOSE #endif // BOOST_MPL_BOOL_HPP_INCLUDED
5ef827120a5ecd04c7e3e49a4873682079050c98
c91df180908d48155f259f1a94c7b1a0389d3d73
/arkanoid/include/Level.h
3cfac57177f9cc5a7f247459f6c6a9dd3a0663f5
[]
no_license
signmotion/arkanoid
f3d3803162685696ded7b0f445f8740e95f90419
95aebe93a9aaa98c9f3828406236f56d9bc39c73
refs/heads/master
2021-01-21T02:36:40.297125
2014-03-31T08:36:42
2014-03-31T08:36:42
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
942
h
#pragma once #include "configure.h" #include "structure.h" namespace arkanoid { class World; class Level { public: // # Воспользуемся тем, что каждый ряд карты представлен в виде строки. typedef std::string row_t; typedef std::vector< row_t > map_t; public: /** * Номер уровня. */ const size_t current; public: Level( size_t current ); virtual ~Level(); /** * @return Есть уровень с заданным номером. */ static bool has( size_t level ); private: /** * @see Комм. в media/1.level */ AboutBackground mAboutBackground; AboutPlatform mAboutPlatform; AboutRacket mAboutRacket; typelib::size2Int_t mCell; aboutSetSign_t mAboutSetSign; map_t mMap; friend World; }; } // arkanoid
6749683a52e59496ba46726d4cbbd8abf47716b5
d0fb46aecc3b69983e7f6244331a81dff42d9595
/devops-rdc/include/alibabacloud/devops-rdc/model/GetPipelineInstanceGroupStatusResult.h
c7f02f5fe8565a6749d35a7a6a3a5718f1d4241b
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-cpp-sdk
3d8d051d44ad00753a429817dd03957614c0c66a
e862bd03c844bcb7ccaa90571bceaa2802c7f135
refs/heads/master
2023-08-29T11:54:00.525102
2023-08-29T03:32:48
2023-08-29T03:32:48
115,379,460
104
82
NOASSERTION
2023-09-14T06:13:33
2017-12-26T02:53:27
C++
UTF-8
C++
false
false
2,169
h
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ALIBABACLOUD_DEVOPS_RDC_MODEL_GETPIPELINEINSTANCEGROUPSTATUSRESULT_H_ #define ALIBABACLOUD_DEVOPS_RDC_MODEL_GETPIPELINEINSTANCEGROUPSTATUSRESULT_H_ #include <string> #include <vector> #include <utility> #include <alibabacloud/core/ServiceResult.h> #include <alibabacloud/devops-rdc/Devops_rdcExport.h> namespace AlibabaCloud { namespace Devops_rdc { namespace Model { class ALIBABACLOUD_DEVOPS_RDC_EXPORT GetPipelineInstanceGroupStatusResult : public ServiceResult { public: struct Object { struct Group { struct Stage { struct Component { std::string status; std::string jobId; std::string name; }; std::vector<Stage::Component> components; std::string status; std::string sign; }; std::string status; std::vector<Group::Stage> stages; std::string name; }; std::string status; std::vector<Group> groups; }; GetPipelineInstanceGroupStatusResult(); explicit GetPipelineInstanceGroupStatusResult(const std::string &payload); ~GetPipelineInstanceGroupStatusResult(); Object getObject()const; std::string getErrorCode()const; std::string getErrorMessage()const; bool getSuccess()const; protected: void parse(const std::string &payload); private: Object object_; std::string errorCode_; std::string errorMessage_; bool success_; }; } } } #endif // !ALIBABACLOUD_DEVOPS_RDC_MODEL_GETPIPELINEINSTANCEGROUPSTATUSRESULT_H_
cc9aa18c8ffe417d5fe94916771df2c9300c876c
fa2c619d4e6d5d6f08b23c6cbb012a2cdf82b706
/cocos3d/Engine/libcocos3d/Controls/Joystick.cpp
eb12defac64e5249ffc55112125da951addea03f
[]
no_license
playbar/cocos3d-x
12fc3c85eb02b6db59e2be0cb4b26ec98a5f32f8
7891a59aad45314ccdad10736903dc0d0bc49450
refs/heads/master
2021-05-31T13:57:55.832920
2016-05-31T12:00:35
2016-05-31T12:00:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,555
cpp
/* * Cocos3D-X 1.0.0 * Author: Bill Hollings * Copyright (c) 2010-2014 The Brenwill Workshop Ltd. All rights reserved. * http://www.brenwill.com * * Copyright (c) 2014-2015 Jason Wong * http://www.cocos3dx.org/ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * http://en.wikipedia.org/wiki/MIT_License */ #include "cocos3d.h" NS_COCOS3D_BEGIN /** The time it takes the thumb to spring back to center once the user lets go. */ #define kThumbSpringBackDuration 1.0 #define kJoystickEventPriority 0 static inline CCSize ccNodeScaledSize( CCNode* aNode ) { if ( aNode ) { CCSize contentSize = aNode->getContentSize(); float scaleX = aNode->getScaleX(); float scaleY = aNode->getScaleY(); return CCSizeMake( contentSize.width * scaleX, contentSize.height * scaleY ); } return CCSizeZero; } Joystick::Joystick() { m_pThumbNode = NULL; m_isTracking = false; } CCPoint Joystick::getVelocity() { return m_velocity; } AngularPoint Joystick::getAngularVelocity() { return m_angularVelocity; } void Joystick::initWithThumb( CCNode* aNode, const CCSize& size ) { CCAssert(aNode, "Thumb node must not be nil"); if ( super::init() ) { initializeEvents(); m_isTracking = false; m_velocity = CCPointZero; m_angularVelocity = AngularPointZero; ignoreAnchorPointForPosition( false ); setAnchorPoint( ccp(0.5f, 0.5f) ); // Add thumb node as a child and position it at the center // Must do following in this order: add thumb / set size / get anchor point m_pThumbNode = aNode; m_pThumbNode->setAnchorPoint( ccp(0.5f, 0.5f) ); addChild( m_pThumbNode, 1 ); setContentSize( size ); m_pThumbNode->setPosition( getAnchorPointInPoints() ); } } void Joystick::initializeEvents() { setTouchEnabled( true ); setTouchPriority( kJoystickEventPriority ); } Joystick* Joystick::joystickWithThumb( CCNode* aNode, const CCSize& size ) { Joystick* pVal = new Joystick; pVal->initWithThumb( aNode, size ); pVal->autorelease(); return pVal; } void Joystick::initWithThumb( CCNode* aNode, CCNode* bgNode ) { initWithThumb( aNode, ccNodeScaledSize(bgNode) ); if (bgNode) { // Position the background node at the center and behind the thumb node bgNode->setAnchorPoint( ccp(0.5f, 0.5f) ); bgNode->setPosition( getAnchorPointInPoints() ); addChild( bgNode ); } } Joystick* Joystick::joystickWithThumb( CCNode* thumbNode, CCNode* backgroundNode ) { Joystick* pVal = new Joystick; pVal->initWithThumb( thumbNode, backgroundNode ); pVal->autorelease(); return pVal; } void Joystick::setContentSize( const CCSize& newSize ) { super::setContentSize( newSize ); m_travelLimit = ccpMult(ccpSub(ccpFromSize(getContentSize()), ccpFromSize(ccNodeScaledSize(m_pThumbNode))), 0.5); } void Joystick::onEnter() { super::onEnter(); resetVelocity(); } void Joystick::registerWithTouchDispatcher() { CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate( this, kJoystickEventPriority, true ); } int Joystick::getTouchPriority() { return kJoystickEventPriority; } bool Joystick::ccTouchBegan( CCTouch* touch, CCEvent* event ) { return processTouchDownAt( convertTouchToNodeSpace( touch ) ); } void Joystick::ccTouchEnded( CCTouch* touch, CCEvent* event ) { CCAssert(m_isTracking, "Touch ended that was never begun"); resetVelocity(); } void Joystick::ccTouchCancelled( CCTouch* touch, CCEvent* event ) { CCAssert(m_isTracking, "Touch cancelled that was never begun"); resetVelocity(); } void Joystick::ccTouchMoved( CCTouch* touch, CCEvent* event ) { CCAssert(m_isTracking, "Touch moved that was never begun"); trackVelocity( convertTouchToNodeSpace( touch ) ); } bool Joystick::processTouchDownAt( const CCPoint& localPoint ) { if(m_isTracking) return false; CCSize cs = getContentSize(); CCRect nodeBounds = CCRectMake(0, 0, cs.width, cs.height); if ( nodeBounds.containsPoint( localPoint ) ) { m_isTracking = true; m_pThumbNode->stopAllActions(); trackVelocity( localPoint ); return true; } return false; } void Joystick::trackVelocity( const CCPoint& nodeTouchPoint ) { CCPoint ankPt = getAnchorPointInPoints(); // Get the touch point relative to the joystick home (anchor point) CCPoint relPoint = ccpSub(nodeTouchPoint, ankPt); // Determine the raw unconstrained velocity vector CCPoint rawVelocity = CCPointMake(relPoint.x / m_travelLimit.x, relPoint.y / m_travelLimit.y); // If necessary, normalize the velocity vector relative to the travel limits float rawVelLen = ccpLength(rawVelocity); m_velocity = (rawVelLen <= 1.0) ? rawVelocity : ccpMult(rawVelocity, 1.0f/rawVelLen); // Calculate the vector in angular coordinates // ccpToAngle returns counterclockwise positive relative to X-axis. // We want clockwise positive relative to the Y-axis. float angle = 90.0f - CC_RADIANS_TO_DEGREES(ccpToAngle(m_velocity)); if ( angle > 180.0f ) angle -= 360.0f; m_angularVelocity.radius = ccpLength(m_velocity); m_angularVelocity.heading = angle; // Update the thumb's position, clamping it within the contentSize of the Joystick if ( m_pThumbNode ) m_pThumbNode->setPosition( ccpAdd(ccpCompMult(m_velocity, m_travelLimit), ankPt) ); } void Joystick::resetVelocity() { m_isTracking = false; m_velocity = CCPointZero; m_angularVelocity = AngularPointZero; if ( m_pThumbNode ) m_pThumbNode->runAction( CCActionEaseElasticOut::create( CCActionMoveTo::create( kThumbSpringBackDuration, getAnchorPointInPoints() ) ) ); } NS_COCOS3D_END
abee45bd8444a4ac5479a0b016c6d8f796c2976c
ee84554c6a42ba095939bb69749dffbe568af5b4
/task81.cpp
0ffa23f213e513fe5103383c9db31d42f0c9dcd0
[]
no_license
Rustem222/practice1
6d3b77d70b8accedb87b1169c1313bef36521f85
d26c2202cf22fb4f290044f0ddbc2902e8b48c8d
refs/heads/master
2020-09-13T02:18:45.395494
2020-05-24T17:21:21
2020-05-24T17:21:21
222,631,522
0
0
null
null
null
null
UTF-8
C++
false
false
162
cpp
#include <iostream> using namespace std; int main(){ for(int i = 0; i<25; i++){ if(i<24) cout<<100-4*i<<", "; else cout<<100-4*i<<"."; } return 0; }
04984bb628a7a7d08ea996dee91b4ffa0a21b1e3
243be2632686abd5cf08e15cac11adf518099602
/openXsensor/oXs_out_multiplex.h
5c1eaa1dca81a718f24ad6d2eaccb96c55b017e1
[]
no_license
kcaldwel/openXsensor
3b9a8f838da17e8b8181fa84601d40ae98f7f390
05db29655c344acd3d21c1438260c97759b028ee
refs/heads/master
2021-01-16T22:30:17.304912
2016-02-09T18:35:36
2016-02-09T18:35:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,475
h
#ifndef OXS_OUT_MULTIPLEX_h #define OXS_OUT_MULTIPLEX_h #include "oXs_config.h" #include "oXs_ms5611.h" // we need the variodata struct #include "oXs_4525.h" // we need the airspeeddata struct #include "oXs_curr.h" // we need the currentdata struct #include "oXs_voltage.h" // we need the arduinodata struct //#include <Arduino.h> #include "oXs_general.h" #include "oXs_gps.h" #if defined(PROTOCOL) && (PROTOCOL == MULTIPLEX) struct t_mbOneData { uint8_t volatile active; uint8_t volatile response[3]; } ; struct t_mbAllData { struct t_mbOneData mbData[16] ; } ; #define MB_CMD_RESET 0x5A #define MB_CMD_RESERVED_MIN 0x80 #define MB_CMD_RESERVED_MAX 0x8F #define MB_NOVALUE 0x8000 #define MB_MAX_ADRESS 15 //list of all telemetry units supported by Multiplex protocol #define MU_ALT 0x08 // 1m (-500 2000) #define MU_VSPD 0x03 // 0,1 m/s (-500 500) #define MU_CURR 0x02 // 0,1 A (-1000 1000) #define MU_VOLT 0x01 // 0,1 V (-600 600) #define MU_TEMP 0x06 // 0,1 C (-250 7000) #define MU_RPM 0x05 // 100t/m?? ou 10t/min #define MU_MAH 0x0B // 1mAh (-16000 16000) #define MU_ASPD 0x04 // 0,1km/h (0-6000) #define MU_LEVEL 0x09 // 1% (0-100) #define MU_DIR 0x07 // 0,1 degrés (0 3600) #define MU_LIQUID 0x0C // 1ml (0-16000) #define MU_DIST 0x0D // 0,1 km (0-16000) // End of list of all telemetry units supported by Multiplex protocol #define MULTIPLEX_UNITS MU_LEVEL , MU_ALT , MU_VSPD , MU_LEVEL , MU_ALT , MU_VOLT , MU_VOLT , MU_VOLT , MU_VOLT , MU_VOLT ,\ MU_VOLT , MU_CURR , MU_MAH , MU_DIR , MU_ASPD , MU_ALT , MU_RPM , MU_DIST , MU_DIR , MU_LEVEL ,\ MU_ALT , MU_ASPD , MU_VSPD , MU_LEVEL , MU_LEVEL , MU_VSPD , MU_LEVEL , MU_LEVEL , MU_LEVEL , MU_VSPD , \ MU_ALT , MU_ALT , MU_VOLT , MU_VOLT , MU_VOLT , MU_VOLT , MU_VOLT , MU_VOLT , MU_VOLT , MU_VOLT , \ MU_ALT // This is the list of codes for each available measurements #define ALTIMETER 1 #define VERTICAL_SPEED 2 #define SENSITIVITY 3 #define ALT_OVER_10_SEC 4 // DEFAULTFIELD can NOT be used ; this is the difference of altitude over the last 10 sec (kind of averaging vertical speed) #define VOLT_1 5 #define VOLT_2 6 #define VOLT_3 7 #define VOLT_4 8 #define VOLT_5 9 #define VOLT_6 10 #define CURRENTMA 11 #define MILLIAH 12 #define GPS_COURSE 13 #define GPS_SPEED 14 #define GPS_ALTITUDE 15 #define RPM 16 #define GPS_DISTANCE 17 #define GPS_BEARING 18 #define SENSITIVITY_2 19 #define ALT_OVER_10_SEC_2 20 #define AIR_SPEED 21 #define PRANDTL_COMPENSATION 22 #define PPM_VSPEED 23 #define PPM 24 #define PRANDTL_DTE 25 #define TEST_1 26 #define TEST_2 27 #define TEST_3 28 #define VERTICAL_SPEED_A 29 #define REL_ALTIMETER 30 #define REL_ALTIMETER_2 31 #define CELL_1 32 #define CELL_2 33 #define CELL_3 34 #define CELL_4 35 #define CELL_5 36 #define CELL_6 37 #define CELL_MIN 38 #define CELL_TOT 39 #define ALTIMETER_MAX 40 // to do : add alt min, alt max , rpm max? , current max (not sure that it is neaded because it can be calculated on TX side // End of list of type of available measurements #define UNKNOWN false #define KNOWN true /***************************************************************************************/ /* Transmission status */ /***************************************************************************************/ #define TO_LOAD 0 #define LOADED 1 #define SENDING 2 #define SEND 3 class OXS_OUT { public: #ifdef DEBUG OXS_OUT(uint8_t pinTx,HardwareSerial &print); #else OXS_OUT(uint8_t pinTx); #endif VARIODATA* varioData ; VARIODATA* varioData_2 ; AIRSPEEDDATA* airSpeedData ; CURRENTDATA* currentData ; VOLTAGEDATA* voltageData ; void setup(); void sendData(); private: // used by both protocols uint8_t _pinTx; #ifdef DEBUG HardwareSerial* printer; #endif void formatAllMultiplexData() ; uint8_t formatOneValue ( uint8_t currentFieldToSend ) ; void setMultiplexNewData( uint16_t id, int32_t value , uint8_t alarm) ; }; //extern int ppm ; //extern bool ppmAvailable ; extern struct ONE_MEASUREMENT ppm ; extern struct ONE_MEASUREMENT mainVspeed ; // used to transmit the main Vspeed(calculated based on all set up in config) extern struct ONE_MEASUREMENT compensatedClimbRate ; // used to transmit the compensated Vspeed extern struct ONE_MEASUREMENT switchVSpeed ; // used to transmit the selected Vspeed extern struct ONE_MEASUREMENT averageVSpeed ; // used to transmit the average Vspeed extern struct ONE_MEASUREMENT vSpeedImu ; // used to transmit the Vspeedcalculated based on IMU extern struct ONE_MEASUREMENT test1 ; extern struct ONE_MEASUREMENT test2 ; extern struct ONE_MEASUREMENT test3 ; extern struct ONE_MEASUREMENT gliderRatio ; extern uint8_t selectedVario ; #ifdef MEASURE_RPM extern volatile uint16_t RpmValue ; extern bool RpmAvailable ; #endif // MEASURE_RPM extern volatile uint8_t debug01 ; extern volatile uint8_t debug02 ; extern volatile uint8_t debug03 ; extern volatile uint8_t debug04 ; void setMultiplexNewData( struct t_sportData * volatile pdata, uint16_t id, uint32_t value ) ; void initMultiplexUart( struct t_mbAllData * volatile pdata ) ; extern volatile bool RpmSet ; extern volatile uint16_t RpmValue ; extern int32_t GPS_lon; // longitude in degree with 7 decimals, (neg for S) extern int32_t GPS_lat; // latitude in degree with 7 decimals, (neg for ?) extern bool GPS_latAvailable; extern int32_t GPS_altitude; // altitude in mm extern uint16_t GPS_speed_3d; // speed in cm/s extern uint16_t GPS_speed_2d; // speed in cm/s extern uint32_t GPS_ground_course ; // degrees with 5 decimals extern uint8_t GPS_numSat ; extern uint8_t GPS_fix_type ; extern int16_t GPS_distance ; extern int16_t GPS_bearing ; // UART's state. #define IDLE 0 // Idle state, both transmit and receive possible. #define TRANSMIT 1 // Transmitting byte. #define TRANSMIT_STOP_BIT 2 // Transmitting stop bit. #define RECEIVE 3 // Receiving byte. #define TxPENDING 4 #define WAITING 5 //This section chooses the correct timer values for Multiplex protocol = 38400 baud. // Assumes a 16MHz clock //#define TICKS2COUNT (278*6) // Ticks between two bits. //#define TICKS2WAITONE (278*6) // Wait one bit period. //#define TICKS2WAITONE_HALF (416*6) // Wait one and a half bit period. #if F_CPU == 20000000L // 20MHz clock // Sinan: Not tested #define TICKS2COUNTMULTIPLEX (521) // Ticks between two bits. #define TICKS2WAITONEMULTIPLEX (521) // Wait one bit period. #define TICKS2WAITONE_HALFMULTIPLEX (781) // Wait one and a half bit period. #elif F_CPU == 16000000L // 16MHz clock #define TICKS2COUNTMULTIPLEX (417) // Ticks between two bits. #define TICKS2WAITONEMULTIPLEX (417) // Wait one bit period. #define TICKS2WAITONE_HALFMULTIPLEX (625) // Wait one and a half bit period. #elif F_CPU == 8000000L // 8MHz clock #define TICKS2COUNTMULTIPLEX (208) // Ticks between two bits. #define TICKS2WAITONEMULTIPLEX (208) // Wait one bit period. #define TICKS2WAITONE_HALFMULTIPLEX (313) // Wait one and a half bit period. #else #error Unsupported clock speed #endif //#define INTERRUPT_EXEC_CYCL 90 // Cycles to execute interrupt routines from interrupt. //#define INTERRUPT_EARLY_BIAS 32 // Cycles to allow of other interrupts. // INTERRUPT_EARLY_BIAS is to bias the sample point a bit early in case // the Timer 0 interrupt (5.5uS) delays the start bit detection #if F_CPU == 20000000L // 20MHz clock #define INTERRUPT_EXEC_CYCL 90 // Cycles to execute interrupt routines from interrupt. #define INTERRUPT_EARLY_BIAS 32 // Cycles to allow of other interrupts. #elif F_CPU == 16000000L // 16MHz clock #define INTERRUPT_EXEC_CYCL 90 // Cycles to execute interrupt routines from interrupt. #define INTERRUPT_EARLY_BIAS 32 // Cycles to allow of other interrupts. #elif F_CPU == 8000000L // 8MHz clock #define INTERRUPT_EXEC_CYCL 90 // Cycles to execute interrupt routines from interrupt. #define INTERRUPT_EARLY_BIAS 32 // Cycles to allow of other interrupts. #else #error Unsupported clock speed #endif #define INTERRUPT_ENTRY_TRANSMIT 59 // Cycles in ISR before sending first bit from first byte; Without this correction, first bit is sent 7.4 usec to late at 8 Mhz (so it takes 59 cycles = 7.4 usec * 8) #define INTERRUPT_BETWEEN_TRANSMIT 64 // Cycles in ISR before sending first bit from 2d, 3rd... bytes; Without this correction, first bit is sent 4 usec to late at 16 Mhz (so it takes 64 cycles = 4 usec * 16) // this section define some delays used ; values can be used by any protocol #if F_CPU == 20000000L // 20MHz clock #define DELAY_4000 ((uint16_t)4000.0 * 20.0 /16.0 ) #define DELAY_3500 ((uint16_t)3500.0 * 20.0 /16.0 ) #define DELAY_2000 ((uint16_t)2000.0 * 20.0 /16.0 ) #define DELAY_1600 ((uint16_t)1600.0 * 20.0 /16.0 ) #define DELAY_400 ((uint16_t)400.0 * 20.0 /16.0 ) #define DELAY_100 ((uint16_t)100.0 * 20.0 /16.0 ) #elif F_CPU == 16000000L // 16MHz clock #define DELAY_4000 ((uint16_t) (4000L * 16) ) #define DELAY_3500 ((uint16_t) (3500L * 16) ) #define DELAY_2000 ((uint16_t) (2000L * 16) ) #define DELAY_1600 ((uint16_t) (1600L * 16) ) #define DELAY_400 ((uint16_t) (400 * 16) ) #define DELAY_100 ((uint16_t) (100 * 16) ) #elif F_CPU == 8000000L // 8MHz clock #define DELAY_4000 ((uint16_t)4000L * 8 ) #define DELAY_3500 ((uint16_t)3500L * 8 ) #define DELAY_2000 ((uint16_t)2000 * 8 ) #define DELAY_1600 ((uint16_t)1600 * 8 ) #define DELAY_400 ((uint16_t)400 * 8 ) #define DELAY_100 ((uint16_t)100 * 8 ) #else #error Unsupported clock speed #endif #define TCCR TCCR1A //!< Timer/Counter Control Register #define TCCR_P TCCR1B //!< Timer/Counter Control (Prescaler) Register #define OCR OCR1A //!< Output Compare Register #define EXT_IFR EIFR //!< External Interrupt Flag Register #define EXT_ICR EICRA //!< External Interrupt Control Register #define TRXDDR DDRD #define TRXPORT PORTD #define TRXPIN PIND #define SET_TX_PIN( ) ( TRXPORT |= ( 1 << PIN_SERIALTX ) ) #define CLEAR_TX_PIN( ) ( TRXPORT &= ~( 1 << PIN_SERIALTX ) ) #define GET_RX_PIN( ) ( TRXPIN & ( 1 << PIN_SERIALTX ) ) #define SET_TX_PIN_MB( ) ( TRXDDR &= ~( 1 << PIN_SERIALTX ) ) // in fact we put the port in high impedance because the rx has a pull up resistance #define CLEAR_TX_PIN_MB( ) ( TRXDDR |= ( 1 << PIN_SERIALTX ) ) // in fact we put the port in output mode. PORT is already set to 0 during initialisation #define MB_MAX_ADRESS 15 // values used by the state ".active" #define NOT_ACTIVE 0 #define NOT_AVAILABLE 1 #define LOCKED 2 #define AVAILABLE 3 #endif // End of MULTIPLEX #endif // OXS_OUT_MULTIPLEX_h
cc0c992571b00157fa1bb965a0ed8700e411db97
890ce00c83b3b8d3649752244727686acb5cd85a
/my C++ Programs/IO programs/Week 8 Topic 9 part 1/Week 8 Topic 9 part 1/Week 8 Topic 9 part 1.cpp
5c706c67bc09faaca29014b174be1e03067bb42e
[]
no_license
balee323/OldSchoolWork
8d6e3366e0d91d45cb58b252acd2c95f0d184049
cc6a976e3ef34a6dfa3c955feb29aef1a2ebfce6
refs/heads/master
2022-06-13T20:04:37.025016
2020-05-08T17:09:26
2020-05-08T17:09:26
83,093,307
0
0
null
null
null
null
UTF-8
C++
false
false
3,706
cpp
// Brian Lee // C++ Programming, Jim Shain // Homework #8, Topic 9 Part1 #include <cstdlib> #include <iostream> #include <fstream> using namespace std; void sortem(int num_[]); //my declared function for sorting from smallest to largest int main() { ifstream instream; // input file stream (instream is the name of the created stream file). ofstream outstream; // output file stream (outstream is the name of the created outstream file). //variables int largest=0, smallest=0; //variable declared int num[100]; //an array variable with 100 assignments //============================================================ //File stream activity section instream.open("numberlist.dat"); //input file opened outstream.open("output.out"); //output file created if (instream.fail()){ //this section checks for existence of input file. cout << "Input file opening failed\n" << endl; //This is displayed if input file is missing. system ("pause"); exit (1); } //================================================================ //Programmer Identification and program explaination section. cout << endl; cout << "// Brian Lee" << endl; cout << "// C++ Programming, Jim Shain" << endl; cout << "// Homework #8, Topic 9 Part1" << endl; cout << "This program reads in numbers from an input file and \n" //explains what program does << "and results the numbers from smallest to largest \n" << "to an output file." << endl << endl; //================================================================ // data instreamed and assigned, and main funtion section: int i = 0; //array countdown while(instream >> num[i]){ //brings in all values from file //cout << num[i] << " "; //proof that all the numbers were streamed in and assigned. i=i++; //assigs each streamed input a one of the declared variables from one //of the above num[100]. } sortem(num); //functon call //cout << endl; //cout << num[0] << " " << num[1] << " " << num[2] << " " << " " << num[75] << " " << num[99] << endl; //proof that the sort works smallest = num[0]; largest = num[99]; outstream << "Largest #: " << (largest) << " and Smallest #: " << (smallest); //sum and average written to output file cout << "Largest #: " << largest << " and Smallest #: "<< smallest << endl << endl; //I was using this for verification instream.close(); outstream.close(); system("pause"); return(0); } //================================================================ //functions defined: void sortem(int num_[]) //function brings in whole array for num { int i, j, temp; //local array variables declared for(i = 0; i < 100; i++) { //while counting loop starting at 0, and ends at 99 for i. for (j = i+1; j < 100; j++) { //while counting loop sarting at i+1 or (1) and set to j. if (num_[j] < num_[i]) { //the meat of the function, if num_[j] is less than num_[i] then // set temp equal to num_[i] temp = num_[i]; //set temp equal to num_[i]. num_[i] = num_[j]; // swap num_i with num_[j]. There must be a 3rd temp varible for swapping. num_[j] = temp; // finally set num_[j] equal to temp's value. And we are sorting } } } }
14d359d4039d893d1d45eea2158fcaab540957c8
7253663621e4a517c9fafec957ceba7bd428091f
/EmbeddedSystems/Smartain_ProjectFinal/code/qt/main.cpp
133d1205dc539b4ae8335e47c30d027456bd2ecb
[]
no_license
juliannehong/bu-courseworks
1c7861160a39d8bb6abad0f01c483f854eca8dee
74b424cc0612197cf00ab3a8adc28761ad72718b
refs/heads/master
2021-01-24T10:38:31.624863
2016-05-10T13:59:14
2016-05-10T13:59:14
123,058,357
0
0
null
null
null
null
UTF-8
C++
false
false
196
cpp
#include "qt.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication app(argc, argv); MainWindow mainWindow; mainWindow.showMaximized(); return app.exec(); }
88fdb835644ddb1dab5afc27e97aeef010758c62
ff8fc5fcf678a91150954ff7c3d593456a26a4cc
/Source/KeyLime/PlayerMovementComponent.h
564a63f32d7ac1cc21af96613e845de870908065
[]
no_license
alyssalern/keylime
211cc8132e3431ee973840fccd8d8f8c44196c12
59338692575d00e53ac5eb61a6ac6577e6354ac3
refs/heads/master
2020-08-23T19:49:18.174878
2019-10-22T01:20:59
2019-10-22T01:21:11
216,695,889
0
0
null
null
null
null
UTF-8
C++
false
false
1,736
h
#pragma once #include "CoreMinimal.h" #include "Components/ActorComponent.h" #include "PlayerMovementComponent.generated.h" class UProjectileMovementComponent; UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) ) class KEYLIME_API UPlayerMovementComponent : public UActorComponent { GENERATED_BODY() public: UPlayerMovementComponent(); virtual ~UPlayerMovementComponent(); virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override; void setProjectileMovementComponent(UProjectileMovementComponent* projectileMovementComponent); void addInputAccelLeft(); void addInputAccelRight(); void increaseSpeed(); void decreaseSpeed(); void startTeleportMovement(); void endTeleportMovement(); void stop(); protected: struct MotionVals { float maxAbsVelocityX = 650.f; float maxAbsVelocityY = 500.f; float curAccelXWithoutFriction = 0.f; float absFrictionAccel = 400.f; }; virtual void BeginPlay() override; void tickX(); void tickY(); void setVelocityX(float velocityX); float calculateFinalVelocity(float initialVelocity, float accel) const; float getNetAccelX() const; void addAccelX(float changeInAccelX); void adjustSpeedBy(float speedChange); static float addValueButKeepSign(float originalValue, float valueToAdd); static bool haveDifferentSigns(float a, float b); MotionVals m_motionVals; MotionVals m_savedMotionVals; UProjectileMovementComponent* m_projectileMovementComponent = nullptr; FVector m_savedProjectileVelocity; bool m_active{ true }; static const float ACCEL_Y; static const float SPEED_CHANGE; static const float INPUT_ACCEL_X; };
2f8eb3635cbf75037aaac0aa30e5d80979528763
e80a8bc8e3d8e4f29c59b77f52b0e64409c3abf0
/scripts/plotUtilities.h
eaf0f6877f30543c8db1cc3e9622801ebb8cb1b6
[]
no_license
tastest/SingleLepton2012_olivito
1035d29e519e2c060da719d1b5584331246f796c
6aabb85d9321af8675a3ee23b5c7405ee53efb20
refs/heads/master
2016-09-05T15:46:56.234468
2013-08-07T15:35:59
2013-08-07T15:35:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,415
h
#ifndef PLOTUTILITIES #define PLOTUTILITIES #include "TFile.h" #include "TChain.h" #include "TLegend.h" #include "TCut.h" #include "TCanvas.h" #include "TH1.h" #include "TPad.h" #include "TGraphErrors.h" #include "TGraphAsymmErrors.h" #include <vector> #include <string> struct dataMCHists{ TPad* comppad; TH1F* datahist; TH1F* mctothist; TH1F* ratio; }; //TH1F* compareDataMC( std::vector<TFile*> mcfiles , vector<char*> labels , TFile* datafile , const char* histname , const char* flavor , const char* dir , TGraphErrors* compareDataMC( std::vector<TFile*> mcfiles , vector<char*> labels , TFile* datafile , const char* histname , const char* flavor , const char* dir , int nbins , float xmin , float xmax , const char* xtitle , bool overlayData = true , bool residual = false, bool drawLegend = true , bool log = false , bool normalize = false , bool fit = false, float mcnorm = -1., const char* scalesample = "" ); void initSymbols(int latex); void printLine(int latex); void printHeader(bool dilep = false); void print( TH1F* h , string label , bool dilep = false, bool correlatedError = false ); void printYields( vector<TFile*> mcfiles , vector<char*> labels , TFile* datafile , const char* dir , bool doData, int latex = 0, bool doWeighted = true ); void fillYieldHist( TH1F* hin, TH1F* hyield, int bin, bool doWeighted = true ); void printCutflow( vector<TFile*> mcfiles , vector<char*> labels , TFile* datafile , vector<char*> dirs , bool doData, bool splitMC = false, int latex = 0, bool doWeighted = true ); void printSigRegions( vector<TFile*> mcfiles , vector<char*> labels , TFile* datafile , vector<char*> dirs , bool doData, int latex = 0, bool doWeighted = true ); float getSystError( const TString sample ); std::string getTableName( const TString sample, int latex = 0 ); //void deleteHistos(); int getColor(const TString sample); TLegend *getLegend( vector<char*> labels , bool overlayData, float x1 = 0.7, float y1 = 0.45 , float x2 = 0.87 , float y2 = 0.94 ); TGraphAsymmErrors* makeBand(TH1F* centhist, TH1F* uphist, TH1F* dnhist); TCanvas* compareNormalized(std::string histname, TFile* file1, std::string label1, TFile* file2, std::string label2, int rebin = 1, bool norm = true, TFile* file3 = 0, std::string label3 = "", TFile* file4 = 0, std::string label4 = ""); TCanvas* compareNormalized(TH1F* h1, std::string label1, TH1F* h2, std::string label2, int rebin = 1, bool norm = true, TH1F* h3 = 0, std::string label3 = "", TH1F* h4 = 0, std::string label4 = ""); TH1F* cumulate (TH1F* in, bool increasing); TGraphErrors* eff_rej (TH1F* signal, TH1F* background, bool normalize, bool increasing, bool print = false); TGraph* s_over_rootb (TH1F* signal, TH1F* background, bool increasing, bool do_s_over_b = false, bool print = false); TLegend* init_legend(float x1=0.5, float y1=0.5, float x2=0.88, float y2=0.8); TLegend* legendize(TCanvas* c, const TString& opt = 'l', const TString& label1 = "", const TString& label2 = "", const TString& label3 = ""); float err_mult(float A, float B, float errA, float errB, float C); TGraphErrors* makeMETGraph(TH1F* hdata, TH1F* hmc, float xoffset = 0.0); char* pm; char* delim; char* delimstart; char* delimend; char* ee; char* mm; char* em; char* e; char* m; int startwidth; int width1; int width2; int linelength; #endif
[ "olivito" ]
olivito
ac9c026a566a4c005396acbb8b35c422b1f6a8bd
fa78188170925215d2c31790b01f0225e9e99193
/src/interface/TBBHandler.h
b20ea5f284819012d98c5b7131adddc77af5271d
[]
no_license
chaoslawful/bht
4e2661b396bb9b6d1b2f2e89a4065ffe39240e11
f3309a8efb1887e6752ba923c227c0cbc04d1a1b
refs/heads/master
2021-01-22T05:27:54.530797
2009-12-12T16:48:05
2009-12-12T16:48:05
426,686
5
1
null
null
null
null
UTF-8
C++
false
false
1,129
h
#ifndef BHT_TBBHANDLER_H__ #define BHT_TBBHANDLER_H__ #include "Common.h" #include "InternalKey.h" #include "Node.h" #include "gen-cpp/BHT.h" BHT_CODE_BEGIN class TBBHandler:virtual public BHTIf { public: TBBHandler(); ~TBBHandler(); // 单键操作 void Del(const ::std::string &domain, const Key &k, const bool overwrite, const bool relay); void Get(Val &v, const ::std::string &domain, const Key &k); void Set(const ::std::string &domain, const Key &k, const Val &v, const bool overwrite, const bool relay); // 多键操作 void MDel(const ::std::string &domain, const ::std::vector<Key> &ks, const bool overwrite, const bool relay); void MGet(::std::map<Key, Val> &kvs, const ::std::string &domain, const ::std::vector<Key> &ks); void MSet(const ::std::string &domain, const ::std::map<Key, Val> &kvs, const bool overwrite, const bool relay); void UpdateConfig(); private: void cleanupRing(const PartitionKey &pkey, const ::std::string &s_id); ::boost::shared_ptr<Node> locateNode(const PartitionKey &pkey); ::boost::shared_ptr<Node> locateNodeOrInit(const PartitionKey &pkey); }; BHT_CODE_END #endif
f1a6aa5378550ef679ca8ffb632f0238b295f2e0
95a6640659fdfd02709d3fc4a9e9f6ef516c79c4
/AndroidApps/NomadsCCx/Classes/AppDelegate.cpp
8700b42fd756d2ca933101587d3f4070f22ac47e
[]
no_license
nomadsystem/NOMADS
1c2fffc0f55cd5a8f1b65cc5e393515453b93789
2ab738a023915f7e66f443bfaa3112266bc39cfe
refs/heads/master
2021-05-01T00:12:48.664523
2013-11-16T19:47:26
2013-11-16T19:47:26
4,654,612
1
1
null
null
null
null
UTF-8
C++
false
false
1,433
cpp
#include "AppDelegate.h" #include "Swarm.h" USING_NS_CC; AppDelegate::AppDelegate() { } AppDelegate::~AppDelegate() { } bool AppDelegate::applicationDidFinishLaunching() { // initialize director CCDirector *pDirector = CCDirector::sharedDirector(); pDirector->setOpenGLView(&CCEGLView::sharedOpenGLView()); // enable High Resource Mode(2x, such as iphone4) and maintains low resource on other devices. // pDirector->enableRetinaDisplay(true); // turn on display FPS pDirector->setDisplayStats(true); // set FPS. the default value is 1.0/60 if you don't call this pDirector->setAnimationInterval(1.0 / 60); // create a scene. it's an autorelease object CCScene *pScene = Swarm::scene(); // run pDirector->runWithScene(pScene); return true; } // This function will be called when the app is inactive. When comes a phone call,it's be invoked too void AppDelegate::applicationDidEnterBackground() { CCDirector::sharedDirector()->stopAnimation(); // if you use SimpleAudioEngine, it must be pause // SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic(); } // this function will be called when the app is active again void AppDelegate::applicationWillEnterForeground() { CCDirector::sharedDirector()->startAnimation(); // if you use SimpleAudioEngine, it must resume here // SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic(); }
b35e937e4105f8c51efe0534a2e9ff88174bcbef
d3d1d7d99054b8684ed5fc784421024050a95c79
/atcoder/abc174/c.cpp
1004d391c27c2da3f66991b652867dccaf1fb45a
[]
no_license
rishabhSharmaOfficial/CompetitiveProgramming
76e7ac3f8fe8c53599e600fc2df2520451b39710
85678a6dc1ee437d917adde8ec323a55a340375e
refs/heads/master
2023-04-28T05:51:18.606350
2021-05-15T07:04:33
2021-05-15T07:04:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,014
cpp
#include<bits/stdc++.h> #define ll long long int #define ld long double #define pi pair<int,int> #define all(x) x.begin(), x.end() #define allr(x) x.rbegin(), x.rend() #define sz(x) ((int)x.size()) #define ln(x) ((int)x.length()) #define mp make_pair #define pb push_back #define ff first #define ss second #define endl '\n' #define dbg(x) cout<<#x<<": "<<x<<endl #define clr(x,v) memset(x, v, sizeof(x)) #define FASTIO ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); using namespace std; const double eps = 1e-9; const double PI = acos(-1.0); const ll mod = 1e9 + 7; const int MAXN = 1e7 + 5; void cp() { int k; cin >> k; bool ok = false; int sum = 0; int ans = -1; for(int i = 1; i <= k; i++) { sum = sum * 10 + 7; sum %= k; if(sum == 0) { ans = i; break; } } cout << ans; } int main() { FASTIO; int t; t = 1; // cin >> t; while(t--) { cp(); } return 0; }
29850a0c9d0833be7b7fe87f703d15e2e6ccb023
0c414280cce89f5f4a7c1a13def5cda266186f1c
/src/qt/bitcoin.cpp
a8a9650ecef5868dea1e4b83c0ab9970fdf69f6c
[ "MIT" ]
permissive
ZNCoinCommunity/ZNCoin
d4780e2a04f8d86a1916960d3f9c373c503d7e7c
b56a6ed9643e39219d5f99a311d6c57af9a8a9b0
refs/heads/master
2020-03-21T01:25:35.030599
2018-06-20T08:32:33
2018-06-20T08:32:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,064
cpp
/* * W.J. van der Laan 2011-2012 */ #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include "guiconstants.h" #include "init.h" #include "ui_interface.h" #include "qtipcserver.h" #include <QApplication> #include <QMessageBox> #include <QTextCodec> #include <QLocale> #include <QTranslator> #include <QSplashScreen> #include <QLibraryInfo> #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) #define _BITCOIN_QT_PLUGINS_INCLUDED #define __INSURE__ #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif // Need a global reference for the notifications to find the GUI static BitcoinGUI *guiref; static QSplashScreen *splashref; static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style) { // Message from network thread if(guiref) { bool modal = (style & CClientUIInterface::MODAL); // in case of modal message, use blocking connection to wait for user to click OK QMetaObject::invokeMethod(guiref, "error", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(bool, modal)); } else { printf("%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); } } static bool ThreadSafeAskFee(int64_t nFeeRequired, const std::string& strCaption) { if(!guiref) return false; if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } static void ThreadSafeHandleURI(const std::string& strURI) { if(!guiref) return; QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(), Q_ARG(QString, QString::fromStdString(strURI))); } static void InitMessage(const std::string &message) { if(splashref) { splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(232,186,63)); QApplication::instance()->processEvents(); } } static void QueueShutdown() { QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection); } /* Translate string to current locale using Qt. */ static std::string Translate(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } /* Handle runaway exceptions. Shows a message box with the problem and quits the program. */ static void handleRunawayException(std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. ZNCoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); exit(1); } #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { // Do this early as we don't want to bother initializing if we are just calling IPC ipcScanRelay(argc, argv); #if QT_VERSION < 0x050000 // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); #endif Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); // Command-line options take precedence: ParseParameters(argc, argv); // ... then bitcoin.conf: if (!boost::filesystem::is_directory(GetDataDir(false))) { // This message can not be translated, as translation is not initialized yet // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory) QMessageBox::critical(0, "ZNCoin", QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); return 1; } ReadConfigFile(mapArgs, mapMultiArgs); // Application identification (must be set before OptionsModel is initialized, // as it is used to locate QSettings) app.setOrganizationName("ZNCoin"); //XXX app.setOrganizationDomain(""); if(GetBoolArg("-testnet")) // Separate UI settings for testnet app.setApplicationName("ZNCoin-Qt-testnet"); else app.setApplicationName("ZNCoin-Qt"); // ... then GUI settings: OptionsModel optionsModel; // Get desired locale (e.g. "de_DE") from command line or use system locale QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); QString lang = lang_territory; // Convert to "de" only by truncating "_DE" lang.truncate(lang_territory.lastIndexOf('_')); QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) if (translatorBase.load(lang, ":/translations/")) app.installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) if (translator.load(lang_territory, ":/translations/")) app.installTranslator(&translator); // Subscribe to global signals from core uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox); uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI); uiInterface.InitMessage.connect(InitMessage); uiInterface.QueueShutdown.connect(QueueShutdown); uiInterface.Translate.connect(Translate); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (mapArgs.count("-?") || mapArgs.count("--help")) { GUIUtil::HelpMessageBox help; help.showOrPrint(); return 1; } QSplashScreen splash(QPixmap(":/images/splash"), 0); if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) { splash.show(); splashref = &splash; } app.processEvents(); app.setQuitOnLastWindowClosed(false); try { // Regenerate startup link, to fix links to old versions if (GUIUtil::GetStartOnSystemStartup()) GUIUtil::SetStartOnSystemStartup(true); BitcoinGUI window; guiref = &window; if(AppInit2()) { { // Put this in a block, so that the Model objects are cleaned up before // calling Shutdown(). if (splashref) splash.finish(&window); ClientModel clientModel(&optionsModel); WalletModel walletModel(pwalletMain, &optionsModel); window.setClientModel(&clientModel); window.setWalletModel(&walletModel); // If -min option passed, start window minimized. if(GetBoolArg("-min")) { window.showMinimized(); } else { window.show(); } // Place this here as guiref has to be defined if we don't want to lose URIs ipcInit(argc, argv); app.exec(); window.hide(); window.setClientModel(0); window.setWalletModel(0); guiref = 0; } // Shutdown the core and its threads, but don't exit Bitcoin-Qt here Shutdown(NULL); } else { return 1; } } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } return 0; } #endif // BITCOIN_QT_TEST
d24512f84dd006fa1948389e7551b3eb00baa70e
158b631998f70d64a4bdc9017ebeb136e91b6e10
/src/midi/io/endianness.h
52da5305cc42fa02835f27c0c5d5c032fad4ac77
[]
no_license
JonasDeBoeck/MIDI-visualizer
536d7f1ca7b82726e5e43ce09dc3aca5096dcd84
0dd0b4962f66c05fb270bc2d164b07efbe5dddab
refs/heads/master
2022-11-17T23:33:35.388286
2020-07-14T14:02:14
2020-07-14T14:02:14
279,589,933
0
0
null
null
null
null
UTF-8
C++
false
false
199
h
#ifndef ENDIANNESS_H #define ENDIANNESS_H #include "stdint.h" namespace io { void switch_endianness(uint16_t* n); void switch_endianness(uint32_t* n); void switch_endianness(uint64_t* n); } #endif
1723bd3e5936fb58680e5a535235da0135e2e421
38ddaa9d07b2c1e943906f6d8f6466e300f0a6ac
/Schoolwork/LAB04.1.cpp
beb86ba55b1a30c7326bbfd5d17b12a7f08ce3d1
[]
no_license
tiananguyen/Practice
932be678aa664a1694589d2c761788f7427ae58a
2d01c8c0f76bd754241a6ea27b06e04c8530ee67
refs/heads/master
2018-11-25T12:08:17.689564
2018-09-04T21:17:54
2018-09-04T21:17:54
104,943,835
0
0
null
null
null
null
UTF-8
C++
false
false
321
cpp
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int die (int n); int main() { srand(time(0)); int n; cout << "How many sides does your die have?\n"; cin >> n; cout << "You rolled a " << die(n) << "!\n"; return 0; } int die (int n) { return (rand() % n) + 1; }
d7cd78bf1dfc9ebcf630e9604b479d3b284c3a8d
808f2767cbca7bbd73cb85ccbe15fa72d77fd847
/TransportModules/Source/KScatteringCalculatorInelastic.cxx
7b84d0173a79b7a672c316b766b29af7f3481fd1
[]
no_license
dlfurse/KassiopeiaDev
6849fb089c32fc524daf46d0c2cf916ee630f332
fdb73cbdedea2568c17fb558aeb7772844ec5e5f
refs/heads/master
2021-01-20T10:05:44.960431
2011-10-19T13:27:45
2011-10-19T13:27:45
2,048,161
0
0
null
null
null
null
UTF-8
C++
false
false
24,218
cxx
#include "KScatteringCalculatorInelastic.h" #include "KSIOToolbox.h" #include "KSTextFile.h" #include <fstream> using std::fstream; #include "TMath.h" #include "KMath.h" #include "KSRandom.h" #include "KSConst.h" using namespace std; namespace Kassiopeia{ KScatteringCalculatorInelastic::KScatteringCalculatorInelastic() : fDataFile(), fIonizationEnergy(0), fMoleculeType(""), fMinimum(-1) { fDataFile.SetKey("InelasticScatteringData"); KSIOToolbox::GetInstance()->AddDataTextFile(&fDataFile); } KScatteringCalculatorInelastic::~KScatteringCalculatorInelastic() { //not needed } void KScatteringCalculatorInelastic::setmolecule(const std::string& aMolecule) { //E < "KScatterBasicInelasticCalculatorFerenc::setmolecule"; fMoleculeType = aMolecule; fDataFile.AddToBases(fMoleculeType + string(".txt")); //cout << "Molecule " << fMoleculeType << endl; if( ReadData() == kFALSE ) { //cout << "unknown ERROR reading file. quit."; } return; } Double_t KScatteringCalculatorInelastic::GetIonizationEnergy() { return fIonizationEnergy; } Double_t KScatteringCalculatorInelastic::sigmaexc(Double_t anE){ //TODO: move constants somewhere. precision? const Double_t a02 = KSConst::BohrRadiusSquared(); // Double_t a02= 28.e-22; //used several times const Double_t R = 13.6; //hydrogen inoisation? precision? Double_t sigma; if(anE<9.8) sigma = 1.e-40; else if(anE>=9.8 && anE<=250.) sigma = sigmaBC(anE) + sigmadiss10(anE) + sigmadiss15(anE); else sigma = 4.*KSConst::Pi() * a02 * R/anE * (0.80*log(anE/R)+0.28); // sigma=sigmainel(anE)-sigmaion(anE); return sigma; } void KScatteringCalculatorInelastic::randomexc(Double_t anE,Double_t& Eloss,Double_t& Theta) //Todo: move static stuff to constructor. constants and precision? { static Int_t iff=0; static Double_t sum[1001]; static Double_t fmax; Double_t Ecen=12.6/27.21; Double_t T,c,u[3],K,xmin,ymin,ymax,x,y,fy,dy,pmax; Double_t D,Dmax; Int_t i,j,n,N,v; // Energy values of the excited electronic states: // (from Mol. Phys. 41 (1980) 1501, in Hartree atomic units) Double_t En[7]={12.73/27.2,13.2/27.2,14.77/27.2,15.3/27.2, 14.93/27.2,15.4/27.2,13.06/27.2}; // Probability numbers of the electronic states: // (from testelectron7.c calculation ) Double_t p[7]={35.86, 40.05, 6.58, 2.26, 9.61, 4.08, 1.54}; // Energy values of the B vibrational states: // (from: Phys. Rev. A51 (1995) 3745 , in Hartree atomic units) Double_t EB[28]={0.411, 0.417, 0.423, 0.428, 0.434, 0.439, 0.444,0.449, 0.454, 0.459, 0.464, 0.468, 0.473, 0.477, 0.481,0.485, 0.489, 0.493, 0.496, 0.500, 0.503, 0.507, 0.510,0.513, 0.516, 0.519, 0.521, 0.524}; // Energy values of the C vibrational states: // (from: Phys. Rev. A51 (1995) 3745 , in Hartree atomic units) Double_t EC[14]={0.452,0.462,0.472,0.481,0.490,0.498,0.506,0.513, 0.519,0.525,0.530,0.534,0.537,0.539}; // Franck-Condon factors of the B vibrational states: // (from: Phys. Rev. A51 (1995) 3745 ) Double_t pB[28]={4.2e-3,1.5e-2,3.0e-2,4.7e-2,6.3e-2,7.3e-2,7.9e-2, 8.0e-2,7.8e-2,7.3e-2,6.6e-2,5.8e-2,5.1e-2,4.4e-2, 3.7e-2,3.1e-2,2.6e-2,2.2e-2,1.8e-2,1.5e-2,1.3e-2, 1.1e-2,8.9e-3,7.4e-3,6.2e-3,5.2e-3,4.3e-3,3.6e-3}; // Franck-Condon factors of the C vibrational states: // (from: Phys. Rev. A51 (1995) 3745 ) Double_t pC[14]={1.2e-1,1.9e-1,1.9e-1,1.5e-1,1.1e-1,7.5e-2,5.0e-2, 3.3e-2,2.2e-2,1.4e-2,9.3e-3,6.0e-3,3.7e-3,1.8e-3}; T=20000./27.2; // xmin=Ecen*Ecen/(2.*T); ymin=log(xmin); ymax=log(8.*T+xmin); dy=(ymax-ymin)/1000.; // Initialization of the sum[] vector, and fmax calculation://TODO move to constructor if(iff==0) { fmax=0; for(i=0;i<=1000;i++) { y=ymin+dy*i; K=exp(y/2.); sum[i]=sumexc(K); if(sum[i]>fmax) fmax=sum[i]; } fmax=1.05*fmax; iff=1; } // // Scattering angle Theta generation: // T=anE/27.2; if(anE>=100.) { xmin=Ecen*Ecen/(2.*T); ymin=log(xmin); ymax=log(8.*T+xmin); dy=(ymax-ymin)/1000.; // Generation of y values with the Neumann acceptance-rejection method: for(j=1;j<5000;j++) { //subrn(u,2); KSRandom::GetInstance()->RndmArray(3, u ); y=ymin+(ymax-ymin)*u[1]; K=exp(y/2.); fy=sumexc(K); if(fmax*u[2]<fy) break; } // Calculation of c=cos(Theta) and Theta: x=exp(y); c=1.-(x-xmin)/(4.*T); Theta=acos(c)*180./KSConst::Pi(); } else { if(anE<=25.) Dmax=60.; else if(anE>25. && anE<=35.) Dmax=95.; else if(anE>35. && anE<=50.) Dmax=150.; else Dmax=400.; for(j=1;j<5000;j++) { //subrn(u,2); KSRandom::GetInstance()->RndmArray(3, u ); c=-1.+2.*u[1]; D = DiffXSecExc(anE,c) * 1.e22; if(Dmax*u[2]<D) break; } Theta=acos(c)*180./KSConst::Pi(); } // Energy loss Eloss generation: // First we generate the electronic state, using the Neumann // acceptance-rejection method for discrete distribution: N=7; // the number of electronic states in our calculation pmax=p[1]; // the maximum of the p[] values for(j=1;j<5000;j++) { KSRandom::GetInstance()->RndmArray(3, u ); //subrn(u,2); n = (Int_t)(N*u[1]); //WOLF: conversion Int_t-> Double_t -> Int_t if(u[2]*pmax<p[n]) break; } if(n<0) n=0; else if(n>6) n=6; if(n>1) // Bp, Bpp, D, Dp, EF states { Eloss=En[n]*27.2; return; } if(n==0) // B state; we generate now a vibrational state, // using the Frank-Condon factors { N=28; // the number of B vibrational states in our calculation pmax=pB[7]; // maximum of the pB[] values for(j=1;j<5000;j++) { KSRandom::GetInstance()->RndmArray(3, u ); //subrn(u,2); //WOLF: conversion Int_t->Double_t v=(Int_t)(N*u[1]); if(u[2]*pmax<pB[v]) break; } if(v<0) v=0; if(v>27) v=27; Eloss=EB[v]*27.2; } if(n==1) // C state; we generate now a vibrational state, // using the Franck-Condon factors { N=14; // the number of C vibrational states in our calculation pmax=pC[1]; // maximum of the pC[] values for(j=1; j<5000; j++){ KSRandom::GetInstance()->RndmArray(3, u ); //subrn(u,2); v=(Int_t)(N*u[1]); //WOLF> conversion Int_t->Double_t if(u[2]*pmax<pC[v]) break; } if(v<0) v=0; else if(v>13) v=13; Eloss=EC[v]*27.2; } return; }//end randomexc //old version (HYDROGEN ONLY!) /* Double_t KScatterBasicInelasticCalculatorFerenc::sigmaion(Double_t anE){ //TODO: move atomic units somewhere Double_t B=15.43,U=15.98,R=13.6; //const Double_t a02=0.28e-20; const Double_t a02 = KaConst::BohrRadiusSquared(); Double_t sigma,t,u,S,r,lnt; if(anE<16.) sigma=1.e-40; else if(anE>=16. && anE<=250.) { t=anE/B; u=U/B; r=R/B; S=4.*KaConst::Pi()*a02*2.*r*r; lnt=log(t); sigma=S/(t+u+1.)*(lnt/2.*(1.-1./(t*t))+1.-1./t-lnt/(t+1.)); } else sigma=4.*KaConst::Pi()*a02*R/anE*(0.82*log(anE/R)+1.3); return sigma; } */ Double_t KScatteringCalculatorInelastic::sigmaion(Double_t anE) { //KSException Except; //Except < "KScatterBasicInelasticCalculatorFerenc::sigmaion"; Double_t sigma = 0.0; std::vector <Double_t> CrossSections; Double_t TotalCrossSection = 0.0; if (fBindingEnergy.size() == 0 ) { // Except = KSException::eFatalError; // Except<<"using unitialized calculator. quitting"; // CatchException(Except); } const Double_t a02 = KSConst::BohrRadiusSquared(); const Double_t ERyd = KSConst::ERyd_eV(); //this does exist! //in old code: //const Double_t ERyd =13.6;//Rydberg constant from EH2SCAT //or nancys value: //const Double_t R=13.6057;//Rydberg constant if (anE > fOrbitalEnergy[fMinimum]){ //if (anE > 16.){//EH2scat sucks //for (std::vector<Double_t>::iterator orbitalIt = fOrbitalEnergy.begin(); // orbitalIt != fOrbitalEnergy.end(); orbitalIt++){ for (UInt_t io=0; io<fOrbitalEnergy.size(); io++){ Int_t i = 0; //numbers the possible shells if ( anE > fOrbitalEnergy[io]){ //???special case for hydrogen and anE>250 EV ???? //is this an approximation, or is this acually more correct? if (fMoleculeType == "Hydrogen" && anE > 250.) { sigma = 4.*KSConst::Pi()*a02 * ERyd / anE* (0.82 * log(anE/ERyd)+1.3); CrossSections.push_back(4.*KSConst::Pi()*a02 * ERyd / anE* (0.82 * log(anE/ERyd)+1.3)); TotalCrossSection = CrossSections.at(i); } else { Double_t t = anE / fBindingEnergy.at(io); Double_t u = fOrbitalEnergy.at(io) / fBindingEnergy.at(io); Double_t r = ERyd / fBindingEnergy.at(io); Double_t S = 4.*KSConst::Pi()*a02 * fNOccupation.at(io) * r * r; Double_t lnt = TMath::Log(t); CrossSections.push_back(S/ (t + u + 1.) * (lnt /2.* ( 1. - 1. / (t * t))+1. - 1. / t - lnt / (t+1.))); TotalCrossSection += CrossSections.at(i); sigma += S/ (t + u + 1.) * (lnt /2.* ( 1. - 1. / (t * t))+1. - 1. / t - lnt / (t+1.)); } i++; } else sigma=1E-40; //for eh2scat comparison! } //Determination of ionization energy //Random number Double_t IonizationDice = KSRandom::GetInstance()->Rndm(); //Decide from which shell the secondary electron is kicked out for( UInt_t i=0; i<CrossSections.size(); i++) { IonizationDice -= CrossSections.at(i)/TotalCrossSection; if( IonizationDice < 0 ) { fIonizationEnergy = fBindingEnergy.at(i); /* #ifdef DEBUG_VERBOSE E = KSException::eKTrackDebug; E < "KSScatterBasicInelastic::sigmaion"; E << "ionization energy: " << CrossSections.at(i); CatchException(E); #endif */ break; } } } else sigma = 1E-40; //why not 0? return sigma; } Bool_t KScatteringCalculatorInelastic::ReadData(){ //TODO replace path with the one specified in the core manager //E < "KScatterBasicInelasticCalculatorFerenc::ReadData"; //KSDataFile* aDataFile = KSIOToolbox::GetInstance()->DemandConfigFile(""); //todo: implemend the line above to avoid multiple instances of one datafile if( fDataFile.Open( KSFile::eRead ) == kTRUE ) { fstream& inputfile = *(fDataFile.File()); Double_t aTemp, anotherTemp; Int_t aTempInt; fBindingEnergy.clear(); fOrbitalEnergy.clear(); fNOccupation.clear(); while ( ! inputfile.eof() ){ //does this remove comments? should work. Char_t c = inputfile.peek(); if ( c >= '0' && c < '9') { inputfile >> aTemp >> anotherTemp >> aTempInt; #ifdef DEBUG_VERBOSE //E = KSException::eScatteringDebug //std::cout << aTemp << " "<<anotherTemp <<" "<< aTempInt<<std::endl; //CatchException(E); #endif fBindingEnergy.push_back(aTemp); fOrbitalEnergy.push_back(anotherTemp); fNOccupation.push_back(aTempInt); } else { Char_t dump[200]; inputfile.getline(dump, 200); #ifdef DEBUG_VERBOSE //E = KSException::eScatteringDebug //E <<"dumping "<< dump<< " because " << c <<" is not a number"; //CatchException(E); #endif continue; } } } else { // E = KSException::eFatalError; // E<< "FATAL ERROR reading scattering data: inputfile " << filename<<" not found or molecule type not supported. "; // CatchException(E); } return FindMinimum(); } Bool_t KScatteringCalculatorInelastic::FindMinimum() { Double_t aMinimum = 999999.99; for (UInt_t io = 0; io < fOrbitalEnergy.size(); io++){ if (aMinimum > fOrbitalEnergy[io]) fMinimum = (Int_t) io; } if (fMinimum >= 0) return true; else return false; } void KScatteringCalculatorInelastic::randomion(Double_t anE,Double_t& Eloss,Double_t& Theta){ // << "Eloss Computation" << endl; //Double_t Ei=15.45/27.21; Double_t IonizationEnergy_eV = GetIonizationEnergy(); //ionization energy in eV Double_t IonizationEnergy_au = IonizationEnergy_eV/27.21; //ionization energy in atomic units Double_t c,b,u[3],K,xmin,ymin,ymax,x,y,T,G,W,Gmax; Double_t q,h,F,Fmin,Fmax,Gp,Elmin,Elmax,qmin,qmax,El,wmax; Double_t WcE,Jstarq,WcstarE,w,D2ion; //Int_t j; Double_t K2,KK,fE,kej,ki,kf,Rex,arg,arctg; //Int_t i; Double_t st1,st2; // // I. Generation of Theta // ----------------------- Gmax=1.e-20; if(anE<200.) Gmax=2.e-20; T=anE/27.21; xmin=IonizationEnergy_au*IonizationEnergy_au/(2.*T); b=xmin/(4.*T); ymin=log(xmin); ymax=log(8.*T+xmin); // Generation of y values with the Neumann acceptance-rejection method: for(Int_t j=1;j<5000;j++) { //subrn(u,2); KSRandom::GetInstance()->RndmArray(3, u ); y=ymin+(ymax-ymin) * u[1]; K=exp(y/2.); c=1.+b-K*K/(4.*T); G=K*K*( DiffXSecInel(anE,c)- DiffXSecExc(anE,c)); if(Gmax*u[2]<G) break; } // y --> x --> c --> Theta x=exp(y); c=1.-(x-xmin)/(4.*T); Theta=acos(c)*180./KSConst::Pi(); // // II. Generation of Eloss, for fixed Theta // ---------------------------------------- // // For anE<=200 eV we use subr. gensecelen // (in this case no correlation between Theta and Eloss) if(anE<=200.) { gensecelen(anE, W); Eloss=IonizationEnergy_eV+W; return; } // For Theta>=20 the free electron model is used // (with full correlation between Theta and Eloss) if(Theta>=20.) { Eloss=anE*(1.-c*c); if(Eloss<IonizationEnergy_eV+0.05) Eloss=IonizationEnergy_eV+0.05; return; } // For anE>200 eV and Theta<20: analytical first Born approximation // formula of Bethe for H atom (with modification for H2) // // Calc. of wmax: if(Theta>=0.7) wmax=1.1; else if(Theta<=0.7 && Theta>0.2) wmax=2.; else if(Theta<=0.2 && Theta>0.05) wmax=4.; else wmax=8.; // We generate the q value according to the Jstarq pdf. We have to // define the qmin and qmax limits for this generation: K=sqrt(4.*T*(1.-IonizationEnergy_au/(2.*T)-sqrt(1.-IonizationEnergy_au/T)*c)); Elmin=IonizationEnergy_au; Elmax=(anE+IonizationEnergy_eV)/2./27.2; qmin=Elmin/K-K/2.; qmax=Elmax/K-K/2.; // q=qmax; Fmax=1./2.+1./KSConst::Pi()*(q/(1.+q*q)+atan(q)); q=qmin; Fmin=1./2.+1./KSConst::Pi()*(q/(1.+q*q)+atan(q)); h=Fmax-Fmin; // Generation of Eloss with the Neumann acceptance-rejection method: for(Int_t j=1;j<5000;j++) { // Generation of q with inverse transform method // (we use the Newton-Raphson method in order to solve the nonlinear eq. // for the inversion) : KSRandom::GetInstance()->RndmArray(3, u ); //subrn(u,2); F=Fmin+h*u[1]; y=0.; for(Int_t i=1;i<=30;i++) { G=1./2.+(y+sin(2.*y)/2.)/KSConst::Pi(); Gp=(1.+cos(2.*y))/KSConst::Pi(); y=y-(G-F)/Gp; if(fabs(G-F)<1.e-8) break; } q=tan(y); // We have the q value, so we can define El, and calculate the weight: El=q*K+K*K/2.; // First Born approximation formula of Bethe for e-H ionization: KK=K; ki=sqrt(2.*T); kf=sqrt(2.*(T-El)); K2=4.*T*(1.-El/(2.*T)-sqrt(1.-El/T)*c); if(K2<1.e-9) K2=1.e-9; K=sqrt(K2); // momentum transfer Rex=1.-K*K/(kf*kf)+K2*K2/(kf*kf*kf*kf); kej=sqrt(2.*fabs(El-IonizationEnergy_au)+1.e-8); st1=K2-2.*El+2.; if(fabs(st1)<1.e-9) st1=1.e-9; arg=2.*kej/st1; if(arg>=0.) arctg=atan(arg); else arctg=atan(arg)+KSConst::Pi(); st1=(K+kej)*(K+kej)+1.; st2=(K-kej)*(K-kej)+1.; fE=1024.*El*(K2+2./3.*El)/(st1*st1*st1*st2*st2*st2)* exp(-2./kej*arctg)/(1.-exp(-2.*KSConst::Pi()/kej)); D2ion=2.*kf/ki*Rex/(El*K2)*fE; K=KK; // WcE=D2ion; Jstarq=16./(3.*KSConst::Pi()*(1.+q*q)*(1.+q*q)); WcstarE=4./(K*K*K*K*K)*Jstarq; w=WcE/WcstarE; if(wmax*u[2]<w) break; } // Eloss=El*27.21; if(Eloss<IonizationEnergy_eV+0.05) Eloss=IonizationEnergy_eV+0.05; // // << "Eloss " << Eloss << endl; return; }//end randomion Double_t KScatteringCalculatorInelastic::DiffXSecExc(Double_t anE,Double_t cosTheta){ Double_t K2,K,T,theta; Double_t sigma = 0.; //Double_t a02=28.e-22; // Bohr radius squared Double_t a02 = KSConst::BohrRadiusSquared(); Double_t EE=12.6/27.21; Double_t e[5]={0.,25.,35.,50.,100.}; Double_t t[9]={0.,10.,20.,30.,40.,60.,80.,100.,180.}; Double_t D[4][9]={ {60.,43.,27.,18.,13.,8.,6.,6.,6.}, {95.,70.,21.,9.,6.,3.,2.,2.,2.,}, {150.,120.,32.,8.,3.7,1.9,1.2,0.8,0.8}, {400.,200.,12.,2.,1.4,0.7,0.3,0.2,0.2}}; Int_t i,j; // T=anE/27.21; if(anE>=100.) { K2=4.*T*(1.-EE/(2.*T)-sqrt(1.-EE/T)*cosTheta); if(K2<1.e-9) K2=1.e-9; K=sqrt(K2); // momentum transfer sigma=2./K2 * sumexc(K)*a02; } else if(anE<=10.) sigma=0.; else { theta=acos(cosTheta)*180./KSConst::Pi(); for(i=0;i<=3;i++) if(anE>=e[i] && anE<e[i+1]) for(j=0;j<=7;j++) if(theta>=t[j] && theta<t[j+1]) sigma=1.e-22*(D[i][j]+(D[i][j+1]-D[i][j])* (theta-t[j])/(t[j+1]-t[j])); } return sigma; }//end DiffXSecExc Double_t KScatteringCalculatorInelastic::DiffXSecInel(Double_t anE,Double_t cosTheta){ //Double_t a02=28.e-22; // Bohr radius squared Double_t a02 = KSConst::BohrRadiusSquared(); Double_t Cinel[50]={ -0.246, -0.244, -0.239, -0.234, -0.227, -0.219, -0.211, -0.201, -0.190, -0.179, -0.167, -0.155, -0.142, -0.130, -0.118, -0.107, -0.096, -0.085, -0.076, -0.067, -0.059, -0.051, -0.045, -0.039, -0.034, -0.029, -0.025, -0.022, -0.019, -0.016, -0.014, -0.010, -0.008, -0.006, -0.004, -0.003, -0.003, -0.002, -0.002, -0.001, -0.001, -0.001, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000}; //Double_t Ei=0.568; Double_t IonizationEnergy_eV = GetIonizationEnergy(); //ionization energy in eV Double_t IonizationEnergy_au = IonizationEnergy_eV/27.21; //ionization energy in atomic units Double_t T,K2,K,st1,F,DH,Dinelreturn,CinelK,Ki; Int_t i; if(anE<IonizationEnergy_eV)//Achtung! 16. return DiffXSecExc(anE, cosTheta); T=anE/27.21; K2=4.*T*(1.-IonizationEnergy_au/(2.*T)-sqrt(1.-IonizationEnergy_au/T)*cosTheta); if(K2<1.e-9) K2=1.e-9;//Achtung!! K=sqrt(K2); // momentum transfer st1=1.+K2/4.; F=1./(st1*st1); // scatt. formfactor of hydrogen atom // DH is the diff. cross section for inelastic electron scatt. // on atomic hydrogen within the first Born approximation : DH=4./(K2*K2)*(1.-F*F)*a02; // CinelK calculation with linear interpolation. // CinelK is the correction of the inelastic electron // scatt. on molecular hydrogen compared to the independent atom // model. if(K<3.) { i=(Int_t)(K/0.1); //WOLF: Double_t->Int_t Ki=i*0.1; //WOLF: Double_t->Int_t CinelK=Cinel[i]+(K-Ki)/0.1*(Cinel[i+1]-Cinel[i]);} else if(K>=3. && K < 5.) { i=(Int_t)(30+(K-3.)/ 0.2); //WOLF: Double->Int_t Ki=3.+(i-30)* 0.2;//WOLF Double_t->Int_t CinelK=Cinel[i]+(K-Ki)/0.2*(Cinel[i+1]-Cinel[i]);} else if(K>=5. && K < 9.49) { i=(Int_t)(40+(K-5.)/0.5); //WOLF: Double_t ->Int_t Ki=5.+(i-40)*0.5; //WOLF: Double_t->Int CinelK=Cinel[i]+(K-Ki)/0.5*(Cinel[i+1]-Cinel[i]);} else CinelK=0.; Dinelreturn=2.*DH*(1.+CinelK); return Dinelreturn; } void KScatteringCalculatorInelastic::gensecelen(Double_t anE,Double_t& W){ //TODO Double_t IonizationEnergy_eV = GetIonizationEnergy(); //ionization energy in eV Double_t /*Ei=15.45,*/eps2=14.3,b=6.25; Double_t B; Double_t C,A,eps,a,u,epsmax; B=atan((IonizationEnergy_eV-eps2)/b); epsmax=(anE+IonizationEnergy_eV)/2.; A=atan((epsmax-eps2)/b); C=b/(A-B); u=KSRandom::GetInstance()->Rndm(); a=b/C*(u+C/b*B); eps=eps2+b*tan(a); W=eps-IonizationEnergy_eV; return; } Double_t KScatteringCalculatorInelastic::sigmainel(Double_t anE){ if ( anE < 250.){ // E < "KScatterBasicInelasticCalculatorFerenc::sigmainel"; // E = KSException::eError; // E <<"cross section not valid. return 0."; // CatchException(E); return 0.0; } Double_t IonizationEnergy_eV = GetIonizationEnergy(); Double_t IonizationEnergy_au = IonizationEnergy_eV/27.21; //ionization energy in atomic units //Double_t Ei=0.568; // ionization energy of molecular // hydrogen in Hartree atomic units // (15.45 eV) Double_t a02 = KSConst::BohrRadiusSquared(); Double_t sigma,gamtot,T; T=anE/27.21; gamtot=2.*(-7./4.+log(IonizationEnergy_au/(2.*T))); sigma=2.*KSConst::Pi()/T*(1.5487*log(2.*T)+2.4036+gamtot/(2.*T)); sigma=sigma*a02; return sigma; } ///////////////////////////////////////////////////////////// //private helper methods Double_t KScatteringCalculatorInelastic::sumexc(Double_t K) { Double_t Kvec[15]={0.,0.1,0.2,0.4,0.6,0.8,1.,1.2,1.5,1.8,2.,2.5,3.,4.,5.}; Double_t fvec[7][15]= {{2.907e-1,2.845e-1,2.665e-1,2.072e-1,1.389e-1, // B 8.238e-2,4.454e-2,2.269e-2,7.789e-3,2.619e-3, 1.273e-3,2.218e-4,4.372e-5,2.889e-6,4.247e-7}, {3.492e-1,3.367e-1,3.124e-1,2.351e-1,1.507e-1, // C 8.406e-2,4.214e-2,1.966e-2,5.799e-3,1.632e-3, 6.929e-4,8.082e-5,9.574e-6,1.526e-7,7.058e-9}, {6.112e-2,5.945e-2,5.830e-2,5.072e-2,3.821e-2, // Bp 2.579e-2,1.567e-2,8.737e-3,3.305e-3,1.191e-3, 6.011e-4,1.132e-4,2.362e-5,1.603e-6,2.215e-7}, {2.066e-2,2.127e-2,2.137e-2,1.928e-2,1.552e-2, // Bpp 1.108e-2,7.058e-3,4.069e-3,1.590e-3,5.900e-4, 3.046e-4,6.142e-5,1.369e-5,9.650e-7,1.244e-7}, {9.405e-2,9.049e-2,8.613e-2,7.301e-2,5.144e-2, // D 3.201e-2,1.775e-2,8.952e-3,2.855e-3,8.429e-4, 3.655e-4,4.389e-5,5.252e-6,9.010e-8,7.130e-9}, {4.273e-2,3.862e-2,3.985e-2,3.362e-2,2.486e-2, // Dp 1.612e-2,9.309e-3,4.856e-3,1.602e-3,4.811e-4, 2.096e-4,2.498e-5,2.905e-6,5.077e-8,6.583e-9}, {0.000e-3,2.042e-3,7.439e-3,2.200e-2,3.164e-2, // EF 3.161e-2,2.486e-2,1.664e-2,7.562e-3,3.044e-3, 1.608e-3,3.225e-4,7.120e-5,6.290e-6,1.066e-6}}; Double_t EeV[7]={12.73,13.20,14.77,15.3,14.93,15.4,13.06}; Int_t jmin = 0; Int_t nnmax = 6; Double_t En,f[7],x4[4],f4[4],sum; // sum=0.; for( Int_t n=0;n<=nnmax;n++) { En=EeV[n]/27.21; // En is the excitation energy in Hartree atomic units if(K>=5.) f[n]=0.; else if(K>=3. && K<=4.) f[n]=fvec[n][12]+(K-3.)*(fvec[n][13]-fvec[n][12]); else if(K>=4. && K<=5.) f[n]=fvec[n][13]+(K-4.)*(fvec[n][14]-fvec[n][13]); else { for(Int_t j=0;j<14;j++) { if(K>=Kvec[j] && K<=Kvec[j+1]) jmin=j-1 ;} if(jmin<0) jmin=0; if(jmin>11) jmin=11; for( Int_t j=0;j<=3;j++) { x4[j]=Kvec[jmin+j]; f4[j]=fvec[n][jmin+j];} f[n]=KMath::Lagrange(4,x4,f4,K); } sum+=f[n]/En; } return sum; }//end sumexc Double_t KScatteringCalculatorInelastic::sigmadiss10(Double_t anE) { Double_t a[9]={-2.297914361e5,5.303988579e5,-5.316636672e5, 3.022690779e5,-1.066224144e5,2.389841369e4, -3.324526406e3,2.624761592e2,-9.006246604}; Double_t lnsigma,lnE,lnEn,Emin,sigma; Int_t n; // anE is in eV sigma=0.; Emin=9.8; lnE=log(anE); lnEn=1.; lnsigma=0.; if(anE<Emin) sigma=0.; else { for(n=0;n<=8;n++) { lnsigma+=a[n]*lnEn; lnEn=lnEn*lnE; } sigma=exp(lnsigma); } return sigma*1.e-4; } Double_t KScatteringCalculatorInelastic::sigmadiss15(Double_t anE) { Double_t a[9]={ -1.157041752e3,1.501936271e3,-8.6119387e2, 2.754926257e2,-5.380465012e1,6.573972423, -4.912318139e-1,2.054926773e-2,-3.689035889e-4}; Double_t lnsigma,lnE,lnEn,Emin,sigma; Int_t n; // anE is in eV sigma=0.; Emin=16.5; lnE=log(anE); lnEn=1.; lnsigma=0.; if(anE<Emin) sigma=0.; else { for(n=0;n<=8;n++) { lnsigma+=a[n]*lnEn; lnEn=lnEn*lnE; } sigma=exp(lnsigma); } return sigma*1.e-4; } Double_t KScatteringCalculatorInelastic::sigmaBC(Double_t anE) { Double_t aB[9]={-4.2935194e2, 5.1122109e2, -2.8481279e2, 8.8310338e1, -1.6659591e1, 1.9579609, -1.4012824e-1, 5.5911348e-3, -9.5370103e-5}; Double_t aC[9]={-8.1942684e2, 9.8705099e2, -5.3095543e2, 1.5917023e2, -2.9121036e1,3.3321027, -2.3305961e-1, 9.1191781e-3,-1.5298950e-4}; Double_t lnsigma,lnE,lnEn,sigmaB,Emin,sigma,sigmaC; Int_t n; sigma=0.; Emin=12.5; lnE=log(anE); lnEn=1.; lnsigma=0.; if(anE<Emin) sigmaB=0.; else { for(n=0;n<=8;n++) { lnsigma+=aB[n]*lnEn; lnEn=lnEn*lnE; } sigmaB=exp(lnsigma); } sigma+=sigmaB; // sigma=0.; // C state: Emin=15.8; lnE=log(anE); lnEn=1.; lnsigma=0.; if(anE<Emin) sigmaC=0.; else { for(n=0;n<=8;n++) { lnsigma+=aC[n]*lnEn; lnEn=lnEn*lnE; } sigmaC=exp(lnsigma); } sigma+=sigmaC; return sigma*1.e-4; } }
e0dc6f5f797421f5c867bfadf8d85c6e9cd767a9
475850f09ea39d11814f3c9f6e301df2fd62c76e
/leetcode/227_Basic Calculator II.cpp
4cae61532f90606b1f398c187fc76ff525b2b809
[]
no_license
njuHan/OJcodes
fed59759b4b954a123cdc423d8c36addd7252d41
1adc57f0850f3f0031ba8d62e974ab3842da5c2d
refs/heads/master
2021-01-25T14:22:21.728203
2019-06-16T05:11:55
2019-06-16T05:11:55
123,686,571
16
1
null
null
null
null
GB18030
C++
false
false
936
cpp
#include<iostream> #include<cstdio> #include<vector> #include<string> #include<map> #include<set> #include<unordered_map> #include<stack> #include<algorithm> #include<queue> #include<sstream> using namespace std; class Solution { public: //利用sstream 自动划分char int //遇到+或-,将当前计算值cur加入总值total,更新cur // int calculate(string s) { int total = 0; int cur = 0; istringstream in(s); in >> cur; char op; while (in >> op) { if (op == '+' || op == '-') { total += cur; in >> cur; if (op == '-') cur = -cur; } else { int temp; in >> temp; if (op == '*') cur *= temp; else cur /= temp; } } return total + cur; } }; int main() { Solution solu; int ans = solu.calculate(" 10 + 2 * 10"); string str = "10*3010"; istringstream is(str); string s; char ch; int n1, n2; is >> n1; is >> ch; is >> n2; system("pause"); return 0; }
c6aab0e7a36c7007e014e78e15c984630cbf4117
a4d2330e1ccdd74f7b6d4bafcea2699bd1a5b354
/Li-fi Programming/Receiver.ino
b1c198835f1b055f82f115a2dca320ce00007254
[]
no_license
adharshmurali/Vehicle-to-vehicle-communication-using-Li-Fi
4db70fdf5dcb0ac03956d607e9491fdbe305d107
d49032155b3cab7cdb6c315a3d8d764a4bbdd5a7
refs/heads/master
2020-06-01T21:22:33.721560
2019-06-08T20:31:41
2019-06-08T20:31:41
190,931,816
2
1
null
null
null
null
UTF-8
C++
false
false
1,960
ino
#include <LiquidCrystal.h> String inputString = ""; boolean stringComplete = false; int sensorValue = 0; const int LED = 13; LiquidCrystal lcd(12, 11, 10, 9, 8, 7); void setup() { pinMode(LED,OUTPUT); digitalWrite(LED,LOW); lcd.begin(16, 2); lcd.print("VtoV communication"); Serial.begin(1200); inputString.reserve(200); for (int thisPin = 2; thisPin < 6; thisPin++) { pinMode(thisPin, OUTPUT); } } int Flag=0,sequence=0,robot_start=0; void loop() { if(sequence == 1) { sequence = 0; digitalWrite(LED,HIGH); lcd.setCursor(0, 1); lcd.print("Gas LeakageDetected"); delay(1000); digitalWrite(LED,LOW); } if(sequence == 2) { sequence = 0; digitalWrite(LED,HIGH); lcd.setCursor(0, 1); lcd.print("DrowsinessDetected"); delay(1000); digitalWrite(LED,LOW); } if(sequence == 3) { sequence = 0; digitalWrite(LED,HIGH); lcd.setCursor(0, 1); lcd.print("Obstacle Detected"); delay(1000); digitalWrite(LED,LOW); } if(sequence == 4) { sequence = 0; digitalWrite(LED,HIGH); lcd.setCursor(0, 1); lcd.print(" "); delay(1000); digitalWrite(LED,LOW); } } void serialEvent() { while (Serial.available()) { char inChar = (char)Serial.read(); inputString += inChar; if (inChar == 'A') { sequence = 1; } if (inChar == 'B') { //stringComplete = true; sequence = 2; } if (inChar == 'C') { //stringComplete = true; sequence = 3; } if (inChar == 'D') { //stringComplete = true; sequence = 4; } } }
089a8607588172cdb5672cec40c63161871ea573
b183dcf75351bc18196482b01e513e2f28cb27d3
/devel/include/gazebo_msgs/ModelState.h
b65724fc9884633f08e3b598f4768d75edda7b0b
[]
no_license
pranaysen/ECE470Project
16f9d739dcd8b1fea9524cf32331752dfd6df0dc
5e6d9ebbf9eab74924d9ec0d5f14380c4e17c66a
refs/heads/master
2023-08-28T17:29:17.809377
2021-10-17T04:52:59
2021-10-17T04:52:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,318
h
// Generated by gencpp from file gazebo_msgs/ModelState.msg // DO NOT EDIT! #ifndef GAZEBO_MSGS_MESSAGE_MODELSTATE_H #define GAZEBO_MSGS_MESSAGE_MODELSTATE_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <geometry_msgs/Pose.h> #include <geometry_msgs/Twist.h> namespace gazebo_msgs { template <class ContainerAllocator> struct ModelState_ { typedef ModelState_<ContainerAllocator> Type; ModelState_() : model_name() , pose() , twist() , reference_frame() { } ModelState_(const ContainerAllocator& _alloc) : model_name(_alloc) , pose(_alloc) , twist(_alloc) , reference_frame(_alloc) { (void)_alloc; } typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _model_name_type; _model_name_type model_name; typedef ::geometry_msgs::Pose_<ContainerAllocator> _pose_type; _pose_type pose; typedef ::geometry_msgs::Twist_<ContainerAllocator> _twist_type; _twist_type twist; typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _reference_frame_type; _reference_frame_type reference_frame; typedef boost::shared_ptr< ::gazebo_msgs::ModelState_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::gazebo_msgs::ModelState_<ContainerAllocator> const> ConstPtr; }; // struct ModelState_ typedef ::gazebo_msgs::ModelState_<std::allocator<void> > ModelState; typedef boost::shared_ptr< ::gazebo_msgs::ModelState > ModelStatePtr; typedef boost::shared_ptr< ::gazebo_msgs::ModelState const> ModelStateConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::gazebo_msgs::ModelState_<ContainerAllocator> & v) { ros::message_operations::Printer< ::gazebo_msgs::ModelState_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace gazebo_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False} // {'sensor_msgs': ['/opt/ros/kinetic/share/sensor_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'trajectory_msgs': ['/opt/ros/kinetic/share/trajectory_msgs/cmake/../msg'], 'gazebo_msgs': ['/home/ur3/catkin_jaym2/src/drivers/gazebo_ros_pkgs/gazebo_msgs/msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::gazebo_msgs::ModelState_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::gazebo_msgs::ModelState_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::gazebo_msgs::ModelState_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::gazebo_msgs::ModelState_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::gazebo_msgs::ModelState_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::gazebo_msgs::ModelState_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::gazebo_msgs::ModelState_<ContainerAllocator> > { static const char* value() { return "9330fd35f2fcd82d457e54bd54e10593"; } static const char* value(const ::gazebo_msgs::ModelState_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x9330fd35f2fcd82dULL; static const uint64_t static_value2 = 0x457e54bd54e10593ULL; }; template<class ContainerAllocator> struct DataType< ::gazebo_msgs::ModelState_<ContainerAllocator> > { static const char* value() { return "gazebo_msgs/ModelState"; } static const char* value(const ::gazebo_msgs::ModelState_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::gazebo_msgs::ModelState_<ContainerAllocator> > { static const char* value() { return "# Set Gazebo Model pose and twist\n\ string model_name # model to set state (pose and twist)\n\ geometry_msgs/Pose pose # desired pose in reference frame\n\ geometry_msgs/Twist twist # desired twist in reference frame\n\ string reference_frame # set pose/twist relative to the frame of this entity (Body/Model)\n\ # leave empty or \"world\" or \"map\" defaults to world-frame\n\ \n\ \n\ ================================================================================\n\ MSG: geometry_msgs/Pose\n\ # A representation of pose in free space, composed of position and orientation. \n\ Point position\n\ Quaternion orientation\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/Point\n\ # This contains the position of a point in free space\n\ float64 x\n\ float64 y\n\ float64 z\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/Quaternion\n\ # This represents an orientation in free space in quaternion form.\n\ \n\ float64 x\n\ float64 y\n\ float64 z\n\ float64 w\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/Twist\n\ # This expresses velocity in free space broken into its linear and angular parts.\n\ Vector3 linear\n\ Vector3 angular\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/Vector3\n\ # This represents a vector in free space. \n\ # It is only meant to represent a direction. Therefore, it does not\n\ # make sense to apply a translation to it (e.g., when applying a \n\ # generic rigid transformation to a Vector3, tf2 will only apply the\n\ # rotation). If you want your data to be translatable too, use the\n\ # geometry_msgs/Point message instead.\n\ \n\ float64 x\n\ float64 y\n\ float64 z\n\ "; } static const char* value(const ::gazebo_msgs::ModelState_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::gazebo_msgs::ModelState_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.model_name); stream.next(m.pose); stream.next(m.twist); stream.next(m.reference_frame); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct ModelState_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::gazebo_msgs::ModelState_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::gazebo_msgs::ModelState_<ContainerAllocator>& v) { s << indent << "model_name: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.model_name); s << indent << "pose: "; s << std::endl; Printer< ::geometry_msgs::Pose_<ContainerAllocator> >::stream(s, indent + " ", v.pose); s << indent << "twist: "; s << std::endl; Printer< ::geometry_msgs::Twist_<ContainerAllocator> >::stream(s, indent + " ", v.twist); s << indent << "reference_frame: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.reference_frame); } }; } // namespace message_operations } // namespace ros #endif // GAZEBO_MSGS_MESSAGE_MODELSTATE_H
124642381cae7bd71ca5404b235dee8d457ba43b
280b3a71a76defbc2a4df66db7f38b48eff9ba32
/apps/texture.cpp
1e3fdc37908fcb3ae98dc12cc1399fc079ab8d25
[ "MIT" ]
permissive
yangfengzzz/DigitalRender
46cc8956767bcc8db28eb3b3513e05af2c1b235a
c8220fe2e59b40d24fe3b33589b4b1c5de5cd3f2
refs/heads/main
2023-02-01T18:01:16.587795
2020-12-17T13:36:05
2020-12-17T13:36:05
309,258,567
1
0
null
null
null
null
UTF-8
C++
false
false
94
cpp
// // texture.cpp // apps // // Created by 杨丰 on 2020/12/1. // #include "texture.hpp"
5ed406cf024b962dbe0900d8f477d511453b60c0
a57c55bbdd2ec560cdaa6d40a608b18676041411
/Cpp And Inspiration/19.Cpp And QSketchBasedInterface/12.Cpp And QSketchModel/Project/QOpenGL/QOpenGLPolygon.cpp
c8e3f037f10c890a405818a79a8849102f13178e
[]
no_license
cristian357r4/Code-And-Inspiration
77b8a058b39ec59d0e062378c8db2039141d6141
e8df8e82ff04bb1d7bccd8ca3542868ab45adc88
refs/heads/master
2022-06-04T14:34:20.740679
2018-05-29T15:01:23
2018-05-29T15:01:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,720
cpp
#include "QOpenGLPolygon.h" #define dot QVector3D::dotProduct #define cross QVector3D::crossProduct QOpenGLPolygon::QOpenGLPolygon(QVector<QVector3D*> quads, QVector<QVector<qreal>> coords) { for(int i=0; i<quads.size(); i++) { QVector3D normal=getNormal(quads[i]); this->translateQuad(quads[i], normal); this->loadPolygon(quads[i], coords[i]); this->translateQuad(quads[i], -2*normal); this->loadPolygon(quads[i], coords[i]); this->addPolygonSide(quads[i], coords[i], normal); } this->initializeVertices(positions.size(), normals.size()*6); for(int i=0; i<normals.size(); i++) { this->addVertex(i*4+0, i, i*4+0); this->addVertex(i*4+1, i, i*4+1); this->addVertex(i*4+2, i, i*4+2); this->addVertex(i*4+3, i, i*4+3); this->addIndex(i*4+0); this->addIndex(i*4+1); this->addIndex(i*4+2); this->addIndex(i*4+2); this->addIndex(i*4+3); this->addIndex(i*4+0); } this->createBuffers(); } void QOpenGLPolygon::addPolygonSide(QVector3D* quad, QVector<qreal> coords, QVector3D normal) { for(int i=0, size=coords.size()/2; i<size; i++) { int i0=i+0, i1=(i+1)%size; QVector3D translate=normal*thickness; qreal u0=coords[i0*2+0], v0=coords[i0*2+1]; qreal u1=coords[i1*2+0], v1=coords[i1*2+1]; QVector3D p00=getPosition(u0, v0), p01=getPosition(u1, v1); QVector3D p10=p00+2*translate, p11=p01+2*translate; QVector3D normal=cross(p01-p00, p10-p00).normalized(); this->texcoords<<QVector2D(u0, v0)<<QVector2D(u0, v0); this->texcoords<<QVector2D(u1, v1)<<QVector2D(u1, v1); this->positions<<p00<<p10<<p11<<p01; this->normals<<normal; } } void QOpenGLPolygon::translateQuad(QVector3D* quad, QVector3D normal) { for(int i=0; i<4; i++)quad[i]+=normal*thickness; } QVector3D QOpenGLPolygon::getNormal(QVector3D* quad) { QVector3D p00=quad[0], p01=quad[1], p10=quad[3]; return cross(p01-p00, p10-p00).normalized(); } void QOpenGLPolygon::addVertex(int p, int n, int t) { GLfloat px=positions[p].x(); GLfloat py=positions[p].y(); GLfloat pz=positions[p].z(); GLfloat nx=normals[n].x(); GLfloat ny=normals[n].y(); GLfloat nz=normals[n].z(); GLfloat tx=texcoords[t].x(); GLfloat ty=texcoords[t].y(); this->addPosition(px, py, pz); this->addNormal(nx, ny, nz); this->addTexcoord(tx, ty); } void QOpenGLPolygon::createEdgeListTable(const QVector<qreal>& coordinates) { this->edgeListTable.clear(); int length=coordinates.size(), l=length/2, L=l; for(int i=0; i<L; i++) { int i0=(i-1+l)%l, i1=(i+1)%l; qreal u0=coordinates[i0*2+0]; qreal v0=coordinates[i0*2+1]; qreal u=coordinates[i*2+0]; qreal v=coordinates[i*2+1]; qreal u1=coordinates[i1*2+0]; qreal v1=coordinates[i1*2+1]; while(u0==u) { i=(i-1+l)%l; L--; i0=(i-1+l)%l; i1=(i+1)%l; u0=coordinates[i0*2+0]; v0=coordinates[i0*2+1]; u=coordinates[i*2+0]; v=coordinates[i*2+1]; u1=coordinates[i1*2+0]; v1=coordinates[i1*2+1]; } if(u1==u) { this->addEdgeNode(u0, v0, u, v, -1, -1); while(u1==u) { i=(i+1)%l; i1=(i+1)%l; u=coordinates[i*2+0]; v=coordinates[i*2+1]; u1=coordinates[i1*2+0]; v1=coordinates[i1*2+1]; } this->addEdgeNode(-1, -1, u, v, u1, v1); } else this->addEdgeNode(u0, v0, u, v, u1, v1); } } void QOpenGLPolygon::addEdgeNode(qreal u0, qreal v0, qreal u, qreal v, qreal u1, qreal v1) { qreal dv0=(v0-v)/(u0-u), dv1=(v1-v)/(u1-u); if(u0>u&&u1>u) { this->edgeListTable.insert(u, new QEdgeNode(v, dv0, u0)); this->edgeListTable.insert(u, new QEdgeNode(v, dv1, u1)); } else if(u0<u&&u1<u); else { if(u1<u0)this->edgeListTable.insert(u, new QEdgeNode(v, dv0, u0)); else this->edgeListTable.insert(u, new QEdgeNode(v, dv1, u1)); } } void QOpenGLPolygon::loadPolygon(QVector3D* quad, const QVector<qreal>& coords) { this->createEdgeListTable(coords); this->p00=quad[0]; this->p01=quad[1]; this->p11=quad[2]; this->p10=quad[3]; QVector3D normal=getNormal(quad); QEdgeList* activeEdgeList=new QEdgeList(0.0); while(edgeListTable.isNotEmpty()) { QEdgeList* tempEdgeList=edgeListTable.getFirst(); QEdgeList* midEdgeList=NULL; qreal u0=tempEdgeList->u; activeEdgeList->u=u0; while(tempEdgeList->isNotEmpty()) { activeEdgeList->insert(tempEdgeList->getFirst()); } if(activeEdgeList->isNotEmpty()) { QEdgeList* newEdgeListTable=new QEdgeList(0.0); while(activeEdgeList->isNotEmpty()) { QEdgeNode* n0=activeEdgeList->getFirst(); QEdgeNode* n1=activeEdgeList->getFirst(); qreal v00=n0->v, v01=n1->v, v10=v00, v11=v01; qreal u1=edgeListTable.u(); qreal maxU0=n0->maxU, maxU1=n1->maxU; if(u1<=maxU0&&u1<=maxU1) { v10=v00+(u1-u0)*n0->dv; v11=v01+(u1-u0)*n1->dv; n0->v=v10;n1->v=v11; if(u1<maxU0)newEdgeListTable->insert(n0); if(u1<maxU1)newEdgeListTable->insert(n1); } else if(u1>maxU0&&maxU0==maxU1) { u1=maxU0; v10=v00+(u1-u0)*n0->dv; v11=v01+(u1-u0)*n1->dv; n0->v=v10; n1->v=v11; } else if(u1>maxU1) { u1=maxU1; v10=v00+(u1-u0)*n0->dv; v11=v01+(u1-u0)*n1->dv; n0->v=v10; if(midEdgeList==NULL)midEdgeList=new QEdgeList(u1); midEdgeList->insert(n0); } else if(u1>maxU0) { u1=maxU0; v10=v00+(u1-u0)*n0->dv; v11=v01+(u1-u0)*n1->dv; n1->v=v11; if(midEdgeList==NULL)midEdgeList=new QEdgeList(u1); midEdgeList->insert(n1); } this->texcoords<<QVector2D(u0, v00); this->texcoords<<QVector2D(u1, v10); this->texcoords<<QVector2D(u1, v11); this->texcoords<<QVector2D(u0, v01); this->positions<<getPosition(u0, v00); this->positions<<getPosition(u1, v10); this->positions<<getPosition(u1, v11); this->positions<<getPosition(u0, v01); this->normals<<normal; } activeEdgeList=newEdgeListTable; } if(midEdgeList!=NULL)this->edgeListTable.insert(midEdgeList); } } QVector3D QOpenGLPolygon::getPosition(qreal u, qreal v) { QVector3D du=p10-p00, dv=p01-p00; QVector3D y=cross(du, dv).normalized(); QVector3D x=dv.normalized(), z=cross(x, y); return p00+u*dot(du, z)*z+v*dot(dv, x)*x; } void QEdgeList::insert(QEdgeNode* node) { if(first==NULL) { this->first=node; this->last=node; } else if(node->v<first->v||(node->v==first->v&&node->dv<first->dv)) { node->next=first; this->first=node; } else if(node->v>last->v||(node->v==last->v&&node->dv>last->dv)) { this->last->next=node; this->last=node; } else { QEdgeNode* m, *n; for(n=first, m=n; n&&(node->v>n->v||(node->v==n->v&&node->dv>n->dv)); m=n, n=n->next); node->next=n; m->next=node; } this->length++; } QEdgeNode* QEdgeList::getFirst() { if(first==NULL)return NULL; QEdgeNode* node=first; this->first=first->next; node->next=NULL; this->length--; return node; } bool QEdgeList::isNotEmpty() { return (first!=NULL); } void QEdgeListTable::insert(QEdgeList* list) { if(first==NULL) { this->first=list; this->last=list; } else if(list->u>=last->u) { this->last->next=list; this->last=list; } else if(list->u<=first->u) { list->next=first; this->first=list; } else { QEdgeList *m, *n; for(n=first, m=n; list->u>n->u; m=n, n=n->next); list->next=n; m->next=list; } } void QEdgeListTable::insert(double u, QEdgeNode* node) { QEdgeList* l; for(l=first; l&&l->u<u; l=l->next); if(!l||l->u!=u) { QEdgeList* l1=new QEdgeList(u); l1->insert(node); this->insert(l1); } else l->insert(node); } qreal QEdgeListTable::u() { return first==NULL?1.0:first->u; } QEdgeList* QEdgeListTable::getFirst() { if(first==NULL)return NULL; QEdgeList *list=first; this->first=first->next; list->next=NULL; return list; } bool QEdgeListTable::isNotEmpty() { return (first!=NULL); } void QEdgeListTable::clear() { this->first=NULL; this->last=NULL; }