hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
77k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
653k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
1
2799cac237d65f737878d98c615edc69f4bcb292
3,997
cpp
C++
benchmarks/allocator_benchmarks.cpp
nanzifan/Umpire-edit
990895b527bef0716aaa0fbb0c0f2017e8e15882
[ "MIT" ]
null
null
null
benchmarks/allocator_benchmarks.cpp
nanzifan/Umpire-edit
990895b527bef0716aaa0fbb0c0f2017e8e15882
[ "MIT" ]
null
null
null
benchmarks/allocator_benchmarks.cpp
nanzifan/Umpire-edit
990895b527bef0716aaa0fbb0c0f2017e8e15882
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2018, Lawrence Livermore National Security, LLC. // Produced at the Lawrence Livermore National Laboratory // // Created by David Beckingsale, david@llnl.gov // LLNL-CODE-747640 // // All rights reserved. // // This file is part of Umpire. // // For details, see https://github.com/LLNL/Umpire // Please also see the LICENSE file for MIT license. ////////////////////////////////////////////////////////////////////////////// #include <iostream> #include "benchmark/benchmark_api.h" #include "umpire/config.hpp" #include "umpire/ResourceManager.hpp" #include "umpire/Allocator.hpp" static const size_t max_allocations = 100000; static void benchmark_allocate(benchmark::State& state, std::string name) { auto allocator = umpire::ResourceManager::getInstance().getAllocator(name); void** allocations = new void*[max_allocations]; auto size = state.range(0); size_t i = 0; while (state.KeepRunning()) { if ( i == max_allocations ) { state.PauseTiming(); for (size_t j = 0; j < max_allocations; j++) allocator.deallocate(allocations[j]); i = 0; state.ResumeTiming(); } allocations[i++] = allocator.allocate(size); } for (size_t j = 0; j < i; j++) allocator.deallocate(allocations[j]); delete[] allocations; } static void benchmark_deallocate(benchmark::State& state, std::string name) { auto allocator = umpire::ResourceManager::getInstance().getAllocator(name); void** allocations = new void*[max_allocations]; auto size = state.range(0); size_t i = 0; while (state.KeepRunning()) { if ( i == 0 || i == max_allocations ) { state.PauseTiming(); for (size_t j = 0; j < max_allocations; j++) allocations[j] = allocator.allocate(size); i = 0; state.ResumeTiming(); } allocator.deallocate(allocations[i++]); } for (size_t j = i; j < max_allocations; j++) allocator.deallocate(allocations[j]); delete[] allocations; } static void benchmark_malloc(benchmark::State& state, std::string name) { auto allocator = umpire::ResourceManager::getInstance().getAllocator(name); void** allocations = new void*[max_allocations]; auto size = state.range(0); size_t i = 0; while (state.KeepRunning()) { if ( i == max_allocations ) { state.PauseTiming(); for (size_t j = 0; j < max_allocations; j++) free(allocations[j]); i = 0; state.ResumeTiming(); } allocations[i++] = malloc(size); } for (size_t j = 0; j < i; j++) free(allocations[j]); delete[] allocations; } static void benchmark_free(benchmark::State& state, std::string name) { auto allocator = umpire::ResourceManager::getInstance().getAllocator(name); void** allocations = new void*[max_allocations]; auto size = state.range(0); size_t i = 0; while (state.KeepRunning()) { if ( i == 0 || i == max_allocations ) { state.PauseTiming(); for (size_t j = 0; j < max_allocations; j++) allocations[j] = malloc(size); i = 0; state.ResumeTiming(); } free(allocations[i++]); } for (size_t j = i; j < max_allocations; j++) free(allocations[j]); delete[] allocations; } BENCHMARK_CAPTURE(benchmark_allocate, host, std::string("HOST"))->Range(4, 1024); BENCHMARK_CAPTURE(benchmark_malloc, host, std::string("HOST"))->Range(4, 1024); BENCHMARK_CAPTURE(benchmark_deallocate, host, std::string("HOST"))->Range(4, 1024); BENCHMARK_CAPTURE(benchmark_free, host, std::string("HOST"))->Range(4, 1024); #if defined(UMPIRE_ENABLE_CUDA) BENCHMARK_CAPTURE(benchmark_allocate, um, std::string("UM"))->Range(4, 1024); BENCHMARK_CAPTURE(benchmark_deallocate, um, std::string("UM"))->Range(4, 1024); BENCHMARK_CAPTURE(benchmark_allocate, device, std::string("DEVICE"))->Range(4, 1024); BENCHMARK_CAPTURE(benchmark_deallocate, device, std::string("DEVICE"))->Range(4, 1024); #endif BENCHMARK_MAIN();
29.607407
87
0.641981
279b22e9f90e6a8cb81f16bf7bfb8a29ee781a25
763
cpp
C++
src/random-set/main.cpp
schien/practices
b248813e51314095c21cf9dc6193d0e1e48550d3
[ "MIT" ]
null
null
null
src/random-set/main.cpp
schien/practices
b248813e51314095c21cf9dc6193d0e1e48550d3
[ "MIT" ]
null
null
null
src/random-set/main.cpp
schien/practices
b248813e51314095c21cf9dc6193d0e1e48550d3
[ "MIT" ]
null
null
null
#include <iostream> #include "input_helper.h" #include "solution.cpp" int main() { RandomizedSet rset; while (std::cin.good()) { char op; std::cin >> op; if (std::cin.eof()) { break; } switch (op) { case 'i': { std::cout << std::boolalpha << rset.insert(next<int>()) << '\n'; break; } case 'd': { std::cout << std::boolalpha << rset.remove(next<int>()) << '\n'; break; } case 'r': { try { std::cout << rset.getRandom() << '\n'; } catch (runtime_error& ex) { std::cerr << ex.what() << std::endl; } break; } default: break; } } return 0; }
18.609756
74
0.415465
279c9c7e74e622d478ea12804163ac171fa04981
207
hpp
C++
parser/spirit/BoostPrecompile.hpp
Vitaliy-Grigoriev/PDL
da528e34e91add4e11415e31e01535db04e7043f
[ "MIT" ]
1
2019-09-23T08:27:31.000Z
2019-09-23T08:27:31.000Z
parser/spirit/BoostPrecompile.hpp
Vitaliy-Grigoriev/PDL
da528e34e91add4e11415e31e01535db04e7043f
[ "MIT" ]
null
null
null
parser/spirit/BoostPrecompile.hpp
Vitaliy-Grigoriev/PDL
da528e34e91add4e11415e31e01535db04e7043f
[ "MIT" ]
null
null
null
//#define BOOST_SPIRIT_X3_DEBUG #define BOOST_SPIRIT_NO_STANDARD_WIDE // Disable wide characters for compilation speed. #include <boost/spirit/home/x3.hpp> #include <boost/fusion/include/adapt_struct.hpp>
34.5
88
0.816425
279e201b5087433e51391b8b41c1d569115758b8
22,572
cxx
C++
main/sw/source/core/text/txtio.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sw/source/core/text/txtio.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sw/source/core/text/txtio.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifdef DBG_UTIL #include "viewsh.hxx" // IsDbg() #include "viewopt.hxx" // IsDbg() #include "txtatr.hxx" #include "errhdl.hxx" #include "txtcfg.hxx" #include "txtfrm.hxx" // IsDbg() #include "rootfrm.hxx" #include "flyfrms.hxx" #include "inftxt.hxx" #include "porexp.hxx" #include "porfld.hxx" #include "porfly.hxx" #include "porftn.hxx" #include "porglue.hxx" #include "porhyph.hxx" #include "porlay.hxx" #include "porlin.hxx" #include "porref.hxx" #include "porrst.hxx" #include "portab.hxx" #include "portox.hxx" #include "portxt.hxx" #include "pordrop.hxx" #include "pormulti.hxx" #include "ndhints.hxx" // So kann man die Layoutstruktur ausgeben lassen // #define AMA_LAYOUT #ifdef AMA_LAYOUT #include <stdio.h> #include <stdlib.h> // getenv() #include <flowfrm.hxx> #include <pagefrm.hxx> #include <svx/svdobj.hxx> #include <dflyobj.hxx> void lcl_OutFollow( XubString &rTmp, const SwFrm* pFrm ) { if( pFrm->IsFlowFrm() ) { const SwFlowFrm *pFlow = SwFlowFrm::CastFlowFrm( pFrm ); if( pFlow->IsFollow() || pFlow->GetFollow() ) { rTmp += "("; if( pFlow->IsFollow() ) rTmp += "."; if( pFlow->GetFollow() ) { MSHORT nFrmId = pFlow->GetFollow()->GetFrm()->GetFrmId(); rTmp += nFrmId; } rTmp += ")"; } } } void lcl_OutFrame( SvFileStream& rStr, const SwFrm* pFrm, ByteString& rSp, sal_Bool bNxt ) { if( !pFrm ) return; KSHORT nSpc = 0; MSHORT nFrmId = pFrm->GetFrmId(); ByteString aTmp; if( pFrm->IsLayoutFrm() ) { if( pFrm->IsRootFrm() ) aTmp = "R"; else if( pFrm->IsPageFrm() ) aTmp = "P"; else if( pFrm->IsBodyFrm() ) aTmp = "B"; else if( pFrm->IsColumnFrm() ) aTmp = "C"; else if( pFrm->IsTabFrm() ) aTmp = "Tb"; else if( pFrm->IsRowFrm() ) aTmp = "Rw"; else if( pFrm->IsCellFrm() ) aTmp = "Ce"; else if( pFrm->IsSctFrm() ) aTmp = "S"; else if( pFrm->IsFlyFrm() ) { aTmp = "F"; const SwFlyFrm *pFly = (SwFlyFrm*)pFrm; if( pFly->IsFlyInCntFrm() ) aTmp += "in"; else if( pFly->IsFlyAtCntFrm() ) { aTmp += "a"; if( pFly->IsAutoPos() ) aTmp += "u"; else aTmp += "t"; } else aTmp += "l"; } else if( pFrm->IsHeaderFrm() ) aTmp = "H"; else if( pFrm->IsFooterFrm() ) aTmp = "Fz"; else if( pFrm->IsFtnContFrm() ) aTmp = "Fc"; else if( pFrm->IsFtnFrm() ) aTmp = "Fn"; else aTmp = "?L?"; aTmp += nFrmId; lcl_OutFollow( aTmp, pFrm ); aTmp += " "; rStr << aTmp; nSpc = aTmp.Len(); rSp.Expand( nSpc + rSp.Len() ); lcl_OutFrame( rStr, ((SwLayoutFrm*)pFrm)->Lower(), rSp, sal_True ); } else { if( pFrm->IsTxtFrm() ) aTmp = "T"; else if( pFrm->IsNoTxtFrm() ) aTmp = "N"; else aTmp = "?C?"; aTmp += nFrmId; lcl_OutFollow( aTmp, pFrm ); aTmp += " "; rStr << aTmp; nSpc = aTmp.Len(); rSp.Expand( nSpc + rSp.Len() ); } if( pFrm->IsPageFrm() ) { const SwPageFrm* pPg = (SwPageFrm*)pFrm; const SwSortedObjs *pSorted = pPg->GetSortedObjs(); const MSHORT nCnt = pSorted ? pSorted->Count() : 0; if( nCnt ) { for( MSHORT i=0; i < nCnt; ++i ) { // --> OD 2004-07-07 #i28701# - consider changed type of // <SwSortedObjs> entries SwAnchoredObject* pAnchoredObj = (*pSorted)[ i ]; if( pAnchoredObj->ISA(SwFlyFrm) ) { SwFlyFrm* pFly = static_cast<SwFlyFrm*>(pAnchoredObj); lcl_OutFrame( rStr, pFly, rSp, sal_False ); } else { aTmp = pAnchoredObj->GetDrawObj()->IsUnoObj() ? "UNO" : "Drw"; rStr << aTmp; } // <-- if( i < nCnt - 1 ) rStr << endl << rSp; } } } else if( pFrm->GetDrawObjs() ) { MSHORT nCnt = pFrm->GetDrawObjs()->Count(); if( nCnt ) { for( MSHORT i=0; i < nCnt; ++i ) { // --> OD 2004-07-07 #i28701# - consider changed type of // <SwSortedObjs> entries SwAnchoredObject* pAnchoredObj = (*pFrm->GetDrawObjs())[ i ]; if( pAnchoredObj->ISA(SwFlyFrm) ) { SwFlyFrm* pFly = static_cast<SwFlyFrm*>(pAnchoredObj); lcl_OutFrame( rStr, pFly, rSp, sal_False ); } else { aTmp = pAnchoredObj->GetDrawObj()->IsUnoObj() ? "UNO" : "Drw"; rStr << aTmp; } if( i < nCnt - 1 ) rStr << endl << rSp; } } } if( nSpc ) rSp.Erase( rSp.Len() - nSpc ); if( bNxt && pFrm->GetNext() ) { do { pFrm = pFrm->GetNext(); rStr << endl << rSp; lcl_OutFrame( rStr, pFrm, rSp, sal_False ); } while ( pFrm->GetNext() ); } } void LayOutPut( const SwFrm* pFrm ) { static char* pOutName = 0; const sal_Bool bFirstOpen = pOutName ? sal_False : sal_True; if( bFirstOpen ) { char *pPath = getenv( "TEMP" ); char *pName = "layout.txt"; if( !pPath ) pOutName = pName; else { const int nLen = strlen(pPath); // fuer dieses new wird es kein delete geben. pOutName = new char[nLen + strlen(pName) + 3]; if(nLen && (pPath[nLen-1] == '\\') || (pPath[nLen-1] == '/')) snprintf( pOutName, sizeof(pOutName), "%s%s", pPath, pName ); else snprintf( pOutName, sizeof(pOutName), "%s/%s", pPath, pName ); } } SvFileStream aStream( pOutName, (bFirstOpen ? STREAM_WRITE | STREAM_TRUNC : STREAM_WRITE )); if( !aStream.GetError() ) { if ( bFirstOpen ) aStream << "Layout-Struktur"; else aStream.Seek( STREAM_SEEK_TO_END ); aStream << endl; aStream << "---------------------------------------------" << endl; XubString aSpace; lcl_OutFrame( aStream, pFrm, aSpace, sal_False ); } } #endif SvStream &operator<<( SvStream &rOs, const SwpHints & ) //$ ostream { rOs << " {HINTS:"; // REMOVED rOs << '}'; return rOs; } /************************************************************************* * IsDbg() *************************************************************************/ sal_Bool IsDbg( const SwTxtFrm *pFrm ) { if( pFrm && pFrm->getRootFrm()->GetCurrShell() ) return pFrm->getRootFrm()->GetCurrShell()->GetViewOptions()->IsTest4(); else return sal_False; } #if OSL_DEBUG_LEVEL < 2 static void Error() { // wegen PM und BCC sal_Bool bFalse = sal_False; ASSERT( bFalse, "txtio: No debug version" ); } #define IMPL_OUTOP(class) \ SvStream &class::operator<<( SvStream &rOs ) const /*$ostream*/\ { \ Error(); \ return rOs; \ } IMPL_OUTOP( SwTxtPortion ) IMPL_OUTOP( SwLinePortion ) IMPL_OUTOP( SwBreakPortion ) IMPL_OUTOP( SwGluePortion ) IMPL_OUTOP( SwFldPortion ) IMPL_OUTOP( SwHiddenPortion ) IMPL_OUTOP( SwHyphPortion ) IMPL_OUTOP( SwFixPortion ) IMPL_OUTOP( SwFlyPortion ) IMPL_OUTOP( SwFlyCntPortion ) IMPL_OUTOP( SwMarginPortion ) IMPL_OUTOP( SwNumberPortion ) IMPL_OUTOP( SwBulletPortion ) IMPL_OUTOP( SwGrfNumPortion ) IMPL_OUTOP( SwLineLayout ) IMPL_OUTOP( SwParaPortion ) IMPL_OUTOP( SwFtnPortion ) IMPL_OUTOP( SwFtnNumPortion ) IMPL_OUTOP( SwTmpEndPortion ) IMPL_OUTOP( SwHyphStrPortion ) IMPL_OUTOP( SwExpandPortion ) IMPL_OUTOP( SwBlankPortion ) IMPL_OUTOP( SwToxPortion ) IMPL_OUTOP( SwRefPortion ) IMPL_OUTOP( SwIsoToxPortion ) IMPL_OUTOP( SwIsoRefPortion ) IMPL_OUTOP( SwSoftHyphPortion ) IMPL_OUTOP( SwSoftHyphStrPortion ) IMPL_OUTOP( SwTabPortion ) IMPL_OUTOP( SwTabLeftPortion ) IMPL_OUTOP( SwTabRightPortion ) IMPL_OUTOP( SwTabCenterPortion ) IMPL_OUTOP( SwTabDecimalPortion ) IMPL_OUTOP( SwPostItsPortion ) IMPL_OUTOP( SwQuoVadisPortion ) IMPL_OUTOP( SwErgoSumPortion ) IMPL_OUTOP( SwHolePortion ) IMPL_OUTOP( SwDropPortion ) IMPL_OUTOP( SwKernPortion ) IMPL_OUTOP( SwArrowPortion ) IMPL_OUTOP( SwMultiPortion ) IMPL_OUTOP( SwCombinedPortion ) const char *GetPortionName( const MSHORT ) { return 0; } const char *GetPrepName( const PrepareHint ) { return 0; } void SwLineLayout::DebugPortions( SvStream &, const XubString &, //$ ostream const xub_StrLen ) { } const char *GetLangName( const MSHORT ) { return 0; } #else # include <limits.h> # include <stdlib.h> # include "swtypes.hxx" // ZTCCONST # include "swfont.hxx" // SwDropPortion CONSTCHAR( pClose, "} " ); /************************************************************************* * GetPortionName() *************************************************************************/ CONSTCHAR( pPOR_LIN, "LIN" ); CONSTCHAR( pPOR_TXT, "TXT" ); CONSTCHAR( pPOR_SHADOW, "SHADOW" ); CONSTCHAR( pPOR_TAB, "TAB" ); CONSTCHAR( pPOR_TABLEFT, "TABLEFT" ); CONSTCHAR( pPOR_TABRIGHT, "TABRIGHT" ); CONSTCHAR( pPOR_TABCENTER, "TABCENTER" ); CONSTCHAR( pPOR_TABDECIMAL, "TABDECIMAL" ); CONSTCHAR( pPOR_EXP, "EXP" ); CONSTCHAR( pPOR_HYPH, "HYPH" ); CONSTCHAR( pPOR_HYPHSTR, "HYPHSTR" ); CONSTCHAR( pPOR_FLD, "FLD" ); CONSTCHAR( pPOR_FIX, "FIX" ); CONSTCHAR( pPOR_FLY, "FLY" ); CONSTCHAR( pPOR_FLYCNT, "FLYCNT" ); CONSTCHAR( pPOR_MARGIN, "MARGIN" ); CONSTCHAR( pPOR_GLUE, "GLUE" ); CONSTCHAR( pPOR_HOLE, "HOLE" ); CONSTCHAR( pPOR_END, "END" ); CONSTCHAR( pPOR_BRK, "BRK" ); CONSTCHAR( pPOR_LAY, "LAY" ); CONSTCHAR( pPOR_BLANK, "BLANK" ); CONSTCHAR( pPOR_FTN, "FTN" ); CONSTCHAR( pPOR_FTNNUM, "FTNNUM" ); CONSTCHAR( pPOR_POSTITS, "POSTITS" ); CONSTCHAR( pPOR_SOFTHYPH, "SOFTHYPH" ); CONSTCHAR( pPOR_SOFTHYPHSTR, "SOFTHYPHSTR" ); CONSTCHAR( pPOR_TOX, "TOX" ); CONSTCHAR( pPOR_REF, "REF" ); CONSTCHAR( pPOR_ISOTOX, "ISOTOX" ); CONSTCHAR( pPOR_ISOREF, "ISOREF" ); CONSTCHAR( pPOR_HIDDEN, "Hidden" ); CONSTCHAR( pPOR_QUOVADIS, "QuoVadis" ); CONSTCHAR( pPOR_ERGOSUM, "ErgoSum" ); CONSTCHAR( pPOR_NUMBER, "NUMBER" ); CONSTCHAR( pPOR_BULLET, "BULLET" ); CONSTCHAR( pPOR_UNKW, "UNKW" ); CONSTCHAR( pPOR_PAR, "PAR" ); const char *GetPortionName( const MSHORT /*nType*/ ) { return 0; } CONSTCHAR( pPREP_CLEAR, "CLEAR" ); CONSTCHAR( pPREP_WIDOWS_ORPHANS, "WIDOWS_ORPHANS" ); CONSTCHAR( pPREP_FIXSIZE_CHG, "FIXSIZE_CHG" ); CONSTCHAR( pPREP_FOLLOW_FOLLOWS, "FOLLOW_FOLLOWS" ); CONSTCHAR( pPREP_ADJUST_FRM, "ADJUST_FRM" ); CONSTCHAR( pPREP_FREE_SPACE, "FREE_SPACE" ); CONSTCHAR( pPREP_FLY_CHGD, "FLY_CHGD" ); CONSTCHAR( pPREP_FLY_ATTR_CHG, "FLY_ATTR_CHG" ); CONSTCHAR( pPREP_FLY_ARRIVE, "FLY_ARRIVE" ); CONSTCHAR( pPREP_FLY_LEAVE, "FLY_LEAVE" ); CONSTCHAR( pPREP_VIEWOPT, "VIEWOPT" ); CONSTCHAR( pPREP_FTN, "FTN" ); CONSTCHAR( pPREP_POS_CHGD, "POS" ); CONSTCHAR( pPREP_UL_SPACE, "UL_SPACE" ); CONSTCHAR( pPREP_MUST_FIT, "MUST_FIT" ); CONSTCHAR( pPREP_WIDOWS, "ORPHANS" ); CONSTCHAR( pPREP_QUOVADIS, "QUOVADIS" ); CONSTCHAR( pPREP_PAGE, "PAGE" ); const char *GetPrepName( const PrepareHint ePrep ) { // Kurz und schmerzlos: const char *ppNameArr[PREP_END] = { pPREP_CLEAR, pPREP_WIDOWS_ORPHANS, pPREP_FIXSIZE_CHG, pPREP_FOLLOW_FOLLOWS, pPREP_ADJUST_FRM, pPREP_FREE_SPACE, pPREP_FLY_CHGD, pPREP_FLY_ATTR_CHG, pPREP_FLY_ARRIVE, pPREP_FLY_LEAVE, pPREP_VIEWOPT, pPREP_FTN, pPREP_POS_CHGD, pPREP_UL_SPACE, pPREP_MUST_FIT, pPREP_WIDOWS, pPREP_QUOVADIS, pPREP_PAGE }; ASSERT( ePrep < PREP_END, "GetPrepName: unknown PrepareHint" ); return( ppNameArr[ePrep] ); } /************************************************************************* * SwLineLayout::DebugPortions() * * DebugPortion() iteriert ueber alle Portions einer Zeile und deckt die * internen Strukturen auf. * Im Gegensatz zum Ausgabe-Operator werden auch die Textteile ausgegeben. *************************************************************************/ void SwLineLayout::DebugPortions( SvStream &rOs, const XubString &/*rTxt*/, //$ ostream const xub_StrLen /*nStart*/ ) { SwLinePortion *pPortion2 = GetPortion(); xub_StrLen nPos = 0; MSHORT nNr = 0; KSHORT nPrtWidth, nLastPrt; nPrtWidth = nLastPrt = 0; SwLinePortion::operator<<( rOs ); rOs << '\"' << endl; while( pPortion2 ) { DBG_LOOP; SwTxtPortion *pTxtPor = pPortion2->InTxtGrp() ? (SwTxtPortion *)pPortion2 : NULL ; (void)pTxtPor; ++nNr; nLastPrt = nPrtWidth; nPrtWidth = nPrtWidth + pPortion2->PrtWidth(); rOs << "\tNr:" << nNr << " Pos:" << nPos << " Org:" << nLastPrt << endl; rOs << "\t"; pPortion2->operator<<( rOs ); rOs << endl; nPos = nPos + pPortion2->GetLen(); pPortion2 = pPortion2->GetPortion(); } } const char *GetLangName( const MSHORT /*nLang*/ ) { return "???"; } SvStream &SwLinePortion::operator<<( SvStream &rOs ) const //$ ostream { rOs << " {"; rOs << "L:" << nLineLength; rOs << " H:" << Height(); rOs << " W:" << PrtWidth(); rOs << " A:" << nAscent; rOs << pClose; return rOs; } SvStream &SwTxtPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {TXT:" ); rOs << pTxt; SwLinePortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwTmpEndPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {END:" ); rOs << pTxt; SwLinePortion::operator<<( rOs ); if( PrtWidth() ) rOs << "(view)"; rOs << pClose; return rOs; } SvStream &SwBreakPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {BREAK:" ); rOs << pTxt; SwLinePortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwKernPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {KERN:" ); rOs << pTxt; SwLinePortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwArrowPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {ARROW:" ); rOs << pTxt; SwLinePortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwMultiPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {MULTI:" ); rOs << pTxt; SwLinePortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwCombinedPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {COMBINED:" ); rOs << pTxt; SwLinePortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwLineLayout::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {LINE:" ); rOs << pTxt; SwLinePortion::operator<<( rOs ); SwLinePortion *pPos = GetPortion(); while( pPos ) { DBG_LOOP; rOs << "\t"; pPos->operator<<( rOs ); pPos = pPos->GetPortion(); } rOs << pClose; return rOs; } SvStream &SwGluePortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {GLUE:" ); rOs << pTxt; SwLinePortion::operator<<( rOs ); rOs << " F:" << GetFixWidth(); rOs << " G:" << GetPrtGlue(); rOs << pClose; return rOs; } SvStream &SwFixPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {FIX:" ); rOs << pTxt; SwGluePortion::operator<<( rOs ); rOs << " Fix:" << nFix; rOs << pClose; return rOs; } SvStream &SwFlyPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {FLY:" ); rOs << pTxt; SwFixPortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwMarginPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {MAR:" ); rOs << pTxt; SwGluePortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwFlyCntPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {FLYCNT:" ); rOs << pTxt; SwLinePortion::operator<<( rOs ); if( bDraw ) { CONSTCHAR( pTxt2, " {DRAWINCNT" ); rOs << pTxt2; rOs << pClose; } else { CONSTCHAR( pTxt2, " {FRM:" ); rOs << pTxt2; rOs << " {FRM:" << GetFlyFrm()->Frm() << pClose; rOs << " {PRT:" << GetFlyFrm()->Prt() << pClose; rOs << pClose; } rOs << pClose; return rOs; } SvStream &SwExpandPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {EXP:" ); rOs << pTxt; SwLinePortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwFtnPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {FTN:" ); rOs << pTxt; SwExpandPortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwFtnNumPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {FTNNUM:" ); rOs << pTxt; SwNumberPortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwNumberPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {NUMBER:" ); rOs << pTxt; SwExpandPortion::operator<<( rOs ); rOs << " Exp:\"" << '\"'; rOs << pClose; return rOs; } SvStream &SwBulletPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {BULLET:" ); rOs << pTxt; SwNumberPortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwGrfNumPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {GRFNUM:" ); rOs << pTxt; SwNumberPortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwHiddenPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {Hidden:" ); rOs << pTxt; SwFldPortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwToxPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {TOX:" ); rOs << pTxt; SwTxtPortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwRefPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {Ref:" ); rOs << pTxt; SwTxtPortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwIsoToxPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {ISOTOX:" ); rOs << pTxt; SwToxPortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwIsoRefPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {ISOREF:" ); rOs << pTxt; SwRefPortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwHyphPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {HYPH:" ); rOs << pTxt; SwExpandPortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwHyphStrPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {HYPHSTR:" ); rOs << pTxt; SwExpandPortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwSoftHyphPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {SOFTHYPH:" ); rOs << pTxt; SwHyphPortion::operator<<( rOs ); rOs << (IsExpand() ? " on" : " off"); rOs << pClose; return rOs; } SvStream &SwSoftHyphStrPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {SOFTHYPHSTR:" ); rOs << pTxt; SwHyphStrPortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwBlankPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {BLANK:" ); rOs << pTxt; SwExpandPortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwFldPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {FLD:" ); rOs << pTxt; SwLinePortion::operator<<( rOs ); if( IsFollow() ) rOs << " F!"; rOs << pClose; return rOs; } SvStream &SwPostItsPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {POSTITS" ); rOs << pTxt; SwLinePortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwTabPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {TAB" ); rOs << pTxt; SwFixPortion::operator<<( rOs ); rOs << " T:" << nTabPos; if( IsFilled() ) rOs << " \"" << cFill << '\"'; rOs << pClose; return rOs; } SvStream &SwTabLeftPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {TABLEFT" ); rOs << pTxt; SwTabPortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwTabRightPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {TABRIGHT" ); rOs << pTxt; SwTabPortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwTabCenterPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {TABCENTER" ); rOs << pTxt; SwTabPortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwTabDecimalPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {TABDECIMAL" ); rOs << pTxt; SwTabPortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwParaPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {PAR" ); rOs << pTxt; SwLineLayout::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwHolePortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {HOLE" ); rOs << pTxt; SwLinePortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwQuoVadisPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {QUOVADIS" ); rOs << pTxt; SwFldPortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &SwErgoSumPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {ERGOSUM" ); rOs << pTxt; SwFldPortion::operator<<( rOs ); rOs << pClose; return rOs; } SvStream &operator<<( SvStream &rOs, const SwTxtSizeInfo &rInf ) //$ ostream { CONSTCHAR( pTxt, " {SIZEINFO:" ); rOs << pTxt; rOs << ' ' << (rInf.OnWin() ? "WIN:" : "PRT:" ); rOs << " Idx:" << rInf.GetIdx(); rOs << " Len:" << rInf.GetLen(); rOs << pClose; return rOs; } SvStream &SwDropPortion::operator<<( SvStream &rOs ) const //$ ostream { CONSTCHAR( pTxt, " {DROP:" ); rOs << pTxt; SwTxtPortion::operator<<( rOs ); if( pPart && nDropHeight ) { rOs << " H:" << nDropHeight; rOs << " L:" << nLines; rOs <<" Fnt:" << pPart->GetFont().GetHeight(); if( nX || nY ) rOs << " [" << nX << '/' << nY << ']'; } rOs << pClose; return rOs; } #endif /* OSL_DEBUG_LEVEL */ #endif // DBG_UTIL
23.885714
90
0.616073
279ebb6034b6a93be79868b35fc5586368c57798
825
cpp
C++
src/error_handling_tk205.cpp
open205/libtk205
48b9c13623bd737e80cc9323d82a217afd927d04
[ "BSD-3-Clause" ]
1
2021-12-09T00:04:43.000Z
2021-12-09T00:04:43.000Z
src/error_handling_tk205.cpp
open205/libtk205
48b9c13623bd737e80cc9323d82a217afd927d04
[ "BSD-3-Clause" ]
null
null
null
src/error_handling_tk205.cpp
open205/libtk205
48b9c13623bd737e80cc9323d82a217afd927d04
[ "BSD-3-Clause" ]
null
null
null
#include "error_handling_tk205.h" #include <map> #include <iostream> #include <string_view> namespace tk205 { msg_handler _error_handler; void Set_error_handler(msg_handler handler) { _error_handler = std::move(handler); } void Show_message(msg_severity severity, const std::string &message) { static std::map<msg_severity, std::string_view> severity_str { {msg_severity::DEBUG_205, "DEBUG"}, {msg_severity::INFO_205, "INFO"}, {msg_severity::WARN_205, "WARN"}, {msg_severity::ERR_205, "ERR"} }; if (!_error_handler) { //std::cout << severity_str[severity] << ": " << message << std::endl; } else { _error_handler(severity, message, nullptr); } } }
24.264706
82
0.578182
279fca8026a43de5182a515cb704965a388aa3a8
6,403
cpp
C++
src/lllarith.cpp
gligneul/Lua-LLVM
1579b46e28d9ca16b70b9e9f3c11b389734eca00
[ "MIT" ]
12
2016-02-26T02:50:59.000Z
2021-05-27T00:56:16.000Z
src/lllarith.cpp
gligneul/Lua-LLVM
1579b46e28d9ca16b70b9e9f3c11b389734eca00
[ "MIT" ]
null
null
null
src/lllarith.cpp
gligneul/Lua-LLVM
1579b46e28d9ca16b70b9e9f3c11b389734eca00
[ "MIT" ]
1
2021-03-25T18:56:50.000Z
2021-03-25T18:56:50.000Z
/* ** LLL - Lua Low Level ** September, 2015 ** Author: Gabriel de Quadros Ligneul ** Copyright Notice for LLL: see lllcore.h ** ** lllarith.cpp ** Compiles the arithmetics opcodes */ #include "lllarith.h" #include "lllcompilerstate.h" #include "lllvalue.h" extern "C" { #include "lprefix.h" #include "lobject.h" #include "lopcodes.h" #include "lvm.h" } namespace lll { Arith::Arith(CompilerState& cs, Stack& stack) : Opcode(cs, stack), ra_(stack.GetR(GETARG_A(cs.instr_))), rkb_(stack.GetRK(GETARG_B(cs.instr_))), rkc_(stack.GetRK(GETARG_C(cs.instr_))), x_(rkb_), y_(rkc_), check_y_(cs.CreateSubBlock("check_y")), intop_(cs.CreateSubBlock("intop", check_y_)), floatop_(cs.CreateSubBlock("floatop", intop_)), tmop_(cs.CreateSubBlock("tmop", floatop_)), x_int_(nullptr), x_float_(nullptr) { } void Arith::Compile() { CheckXTag(); CheckYTag(); ComputeInt(); ComputeFloat(); ComputeTaggedMethod(); } void Arith::CheckXTag() { auto check_y_int = cs_.CreateSubBlock("is_y_int"); auto check_x_float = cs_.CreateSubBlock("is_x_float", check_y_int); auto tonumber_x = cs_.CreateSubBlock("tonumber_x", check_x_float); cs_.B_.SetInsertPoint(entry_); auto xtag = x_.GetTag(); auto is_x_int = cs_.B_.CreateICmpEQ(xtag, cs_.MakeInt(LUA_TNUMINT)); cs_.B_.CreateCondBr(is_x_int, check_y_int, check_x_float); cs_.B_.SetInsertPoint(check_y_int); x_int_ = x_.GetInteger(); auto floatt = cs_.rt_.GetType("lua_Number"); auto x_itof = cs_.B_.CreateSIToFP(x_int_, floatt, x_int_->getName() + "_flt"); x_float_inc_.push_back({x_itof, check_y_int}); auto is_y_int = y_.HasTag(LUA_TNUMINT); cs_.B_.CreateCondBr(is_y_int, intop_, check_y_); cs_.B_.SetInsertPoint(check_x_float); x_float_inc_.push_back({x_.GetFloat(), check_x_float}); auto is_x_float = cs_.B_.CreateICmpEQ(xtag, cs_.MakeInt(LUA_TNUMFLT)); cs_.B_.CreateCondBr(is_x_float, check_y_, tonumber_x); cs_.B_.SetInsertPoint(tonumber_x); auto args = {x_.GetTValue(), cs_.values_.xnumber}; auto tonumberret = cs_.CreateCall("luaV_tonumber_", args); auto x_converted = cs_.B_.CreateLoad(cs_.values_.xnumber); x_float_inc_.push_back({x_converted, tonumber_x}); auto converted = cs_.ToBool(tonumberret); cs_.B_.CreateCondBr(converted, check_y_, tmop_); } void Arith::CheckYTag() { auto tonumber_y = cs_.CreateSubBlock("tonumber_y", check_y_); cs_.B_.SetInsertPoint(check_y_); auto floatt = cs_.rt_.GetType("lua_Number"); x_float_ = CreatePHI(floatt, x_float_inc_, "xfloat"); y_float_inc_.push_back({y_.GetFloat(), check_y_}); auto is_y_float = y_.HasTag(LUA_TNUMFLT); cs_.B_.CreateCondBr(is_y_float, floatop_, tonumber_y); cs_.B_.SetInsertPoint(tonumber_y); auto args = {y_.GetTValue(), cs_.values_.ynumber}; auto tonumberret = cs_.CreateCall("luaV_tonumber_", args); auto y_converted = cs_.B_.CreateLoad(cs_.values_.ynumber); y_float_inc_.push_back({y_converted, tonumber_y}); auto converted = cs_.ToBool(tonumberret); cs_.B_.CreateCondBr(converted, floatop_, tmop_); } void Arith::ComputeInt() { cs_.B_.SetInsertPoint(intop_); auto y_int = y_.GetInteger(); if (HasIntegerOp()) { ra_.SetInteger(PerformIntOp(x_int_, y_int)); cs_.B_.CreateBr(exit_); } else { auto floatt = cs_.rt_.GetType("lua_Number"); auto x_float = cs_.B_.CreateSIToFP(x_int_, floatt); auto y_float = cs_.B_.CreateSIToFP(y_int, floatt); ra_.SetFloat(PerformFloatOp(x_float, y_float)); cs_.B_.CreateBr(exit_); } } void Arith::ComputeFloat() { cs_.B_.SetInsertPoint(floatop_); auto floatt = cs_.rt_.GetType("lua_Number"); auto y_float = CreatePHI(floatt, y_float_inc_, "yfloat"); ra_.SetFloat(PerformFloatOp(x_float_, y_float)); cs_.B_.CreateBr(exit_); } void Arith::ComputeTaggedMethod() { cs_.B_.SetInsertPoint(tmop_); auto args = { cs_.values_.state, x_.GetTValue(), y_.GetTValue(), ra_.GetTValue(), cs_.MakeInt(GetMethodTag()) }; cs_.CreateCall("luaT_trybinTM", args); stack_.Update(); cs_.B_.CreateBr(exit_); } bool Arith::HasIntegerOp() { switch (GET_OPCODE(cs_.instr_)) { case OP_ADD: case OP_SUB: case OP_MUL: case OP_MOD: case OP_IDIV: return true; default: break; } return false; } llvm::Value* Arith::PerformIntOp(llvm::Value* lhs, llvm::Value* rhs) { auto name = "result"; switch (GET_OPCODE(cs_.instr_)) { case OP_ADD: return cs_.B_.CreateAdd(lhs, rhs, name); case OP_SUB: return cs_.B_.CreateSub(lhs, rhs, name); case OP_MUL: return cs_.B_.CreateMul(lhs, rhs, name); case OP_MOD: return cs_.CreateCall("luaV_mod", {cs_.values_.state, lhs, rhs}, name); case OP_IDIV: return cs_.CreateCall("luaV_div", {cs_.values_.state, lhs, rhs}, name); default: break; } assert(false); return nullptr; } llvm::Value* Arith::PerformFloatOp(llvm::Value* lhs, llvm::Value* rhs) { auto name = "result"; switch (GET_OPCODE(cs_.instr_)) { case OP_ADD: return cs_.B_.CreateFAdd(lhs, rhs, name); case OP_SUB: return cs_.B_.CreateFSub(lhs, rhs, name); case OP_MUL: return cs_.B_.CreateFMul(lhs, rhs, name); case OP_MOD: return cs_.CreateCall("LLLNumMod", {lhs, rhs}, name); case OP_POW: return cs_.CreateCall(STRINGFY2(l_mathop(pow)), {lhs, rhs}, name); case OP_DIV: return cs_.B_.CreateFDiv(lhs, rhs, name); case OP_IDIV: return cs_.CreateCall(STRINGFY2(l_mathop(floor)), {cs_.B_.CreateFDiv(lhs, rhs, name)}, "floor"); default: break; } assert(false); return nullptr; } int Arith::GetMethodTag() { switch (GET_OPCODE(cs_.instr_)) { case OP_ADD: return TM_ADD; case OP_SUB: return TM_SUB; case OP_MUL: return TM_MUL; case OP_MOD: return TM_MOD; case OP_POW: return TM_POW; case OP_DIV: return TM_DIV; case OP_IDIV: return TM_IDIV; default: break; } assert(false); return -1; } }
30.636364
82
0.640325
27a1ee71243b7276ca7d333f8a7d3dde4bc3800b
785
cpp
C++
Codeforces/1108A-Two_distinct_points.cpp
Pankajcoder1/Competitive_programming
72ee0d41f3f72f43a5c2a232255eb84a04b14df9
[ "MIT" ]
null
null
null
Codeforces/1108A-Two_distinct_points.cpp
Pankajcoder1/Competitive_programming
72ee0d41f3f72f43a5c2a232255eb84a04b14df9
[ "MIT" ]
null
null
null
Codeforces/1108A-Two_distinct_points.cpp
Pankajcoder1/Competitive_programming
72ee0d41f3f72f43a5c2a232255eb84a04b14df9
[ "MIT" ]
1
2020-10-02T04:51:22.000Z
2020-10-02T04:51:22.000Z
/* written by Pankaj Kumar. country:-INDIA Institute: National Institute of Technology, Uttarakhand */ #include<iostream> #include<vector> #include<cmath> #include<algorithm> #include<string.h> #define pan cin.tie(0);cout.tie(0);ios_base::sync_with_stdio(0); #define mod 1000000007; using namespace std; typedef long long ll ; #define line cout<<endl; int main() { pan; ll t; cin>>t; while(t--) { ll l1,r1,l2,r2; cin>>l1>>r1>>l2>>r2; if(l2!=l1) cout<<l1<<" "<<l2<<endl; else cout<<l1<<" "<<l2+1<<endl; } } // * -----------------END OF PROGRAM --------------------*/ /* * stuff you should look before submission * constraint and time limit * int overflow * special test case (n=0||n=1||n=2) * don't get stuck on one approach if you get wrong answer */
19.625
64
0.628025
27a1f8f0e9171053961ab73f49b30d853cdbf9d1
25,258
cpp
C++
test/code/myauth/myauth_test.cpp
Bhaskers-Blu-Org2/MySQL-Provider
211f79e98e7f34a13c4fb7c01f3aaaefc0dada63
[ "MIT" ]
5
2016-06-18T14:41:36.000Z
2019-01-10T09:46:20.000Z
test/code/myauth/myauth_test.cpp
microsoft/MySQL-Provider
211f79e98e7f34a13c4fb7c01f3aaaefc0dada63
[ "MIT" ]
5
2016-04-12T23:00:45.000Z
2019-03-28T23:04:57.000Z
test/code/myauth/myauth_test.cpp
microsoft/MySQL-Provider
211f79e98e7f34a13c4fb7c01f3aaaefc0dada63
[ "MIT" ]
6
2019-09-18T00:11:36.000Z
2021-11-10T10:07:03.000Z
/* * --------------------------------- START OF LICENSE ---------------------------- * * MySQL cimprov ver. 1.0 * * Copyright (c) Microsoft Corporation * * All rights reserved. * * MIT License * * 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. * * ---------------------------------- END OF LICENSE ----------------------------- */ /*-------------------------------------------------------------------------------- Created date 2015-01-23 08:45:00 MySQL Authentication Tool unit tests. */ /*----------------------------------------------------------------------------*/ #include <scxcorelib/scxcmn.h> #include <scxcorelib/scxfile.h> #include <scxcorelib/scxprocess.h> #include <scxcorelib/stringaid.h> #include <testutils/scxunit.h> #include <testutils/providertestutils.h> #include <iostream> // for cout #include "sqlauth.h" #include "sqlcredentials.h" static const std::wstring s_authProgram = L"./mycimprovauth"; static const wchar_t* s_authFilePath = L"./mysql-auth"; static const int s_timeout = 0; using namespace SCXCoreLib; class MyCimprovAuth_Test : public CPPUNIT_NS::TestFixture { CPPUNIT_TEST_SUITE( MyCimprovAuth_Test ); CPPUNIT_TEST( test_NoCommandOptions ); CPPUNIT_TEST( test_BasicHelp ); CPPUNIT_TEST( test_CommandHelp ); CPPUNIT_TEST( test_OptionTest_Valid ); CPPUNIT_TEST( test_CommandPrint_Empty ); CPPUNIT_TEST( test_CommandQuit_DoesntUpdate ); CPPUNIT_TEST( test_AutoUpdate_Interactive ); CPPUNIT_TEST( test_AutoUpdate_CommandLine ); CPPUNIT_TEST( test_Default_Interactive ); CPPUNIT_TEST( test_Default_CommandLine ); CPPUNIT_TEST( test_Update_Interactive ); CPPUNIT_TEST( test_Update_CommandLine ); CPPUNIT_TEST( test_Delete_Interactive ); CPPUNIT_TEST( test_Delete_CommandLine ); CPPUNIT_TEST_SUITE_END(); private: public: void setUp(void) { } void tearDown(void) { // Delete the authentication file SCXCoreLib::SCXFile::Delete( s_authFilePath ); } void test_NoCommandOptions() { std::istringstream processInput; std::ostringstream processOutput; std::ostringstream processErr; int status = SCXProcess::Run(s_authProgram, processInput, processOutput, processErr, s_timeout); CPPUNIT_ASSERT_EQUAL( "", processOutput.str() ); CPPUNIT_ASSERT_EQUAL( "./mycimprovauth: Try './mycimprovauth -h' for more information.\n", processErr.str() ); CPPUNIT_ASSERT_EQUAL( 1, status ); } void test_BasicHelp() { std::istringstream processInput; std::ostringstream processOutput; std::ostringstream processErr; int status = SCXProcess::Run(s_authProgram + L" -h", processInput, processOutput, processErr, s_timeout); std::stringstream expectedOutput; expectedOutput << "Usage: ./mycimprovauth[options] [operations]" << std::endl << std::endl << "Options:" << std::endl << " -h:\tDisplay detailed help information" << std::endl << " -i:\tInteractive use" << std::endl << " -v:\tDisplay version information" << std::endl << std::endl << "Operations:" << std::endl << " autoupdate true|false" << std::endl << " default [bind-address] [username] [password]" << std::endl << " delete default|<port#>" << std::endl << " help" << std::endl << " print" << std::endl << " update <port#> [bind-address] [username] [password]" << std::endl; CPPUNIT_ASSERT_EQUAL( expectedOutput.str(), processOutput.str() ); CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() ); CPPUNIT_ASSERT_EQUAL( 0, status ); } void test_CommandHelp() { std::istringstream processInput; std::ostringstream processOutput; std::ostringstream processErr; int status = SCXProcess::Run(s_authProgram + L" help", processInput, processOutput, processErr, s_timeout); std::stringstream expectedOutput; expectedOutput << "Help for commands to maintain MySQL Provider Authentication File:" << std::endl << std::endl << " autoupdate [true|false]" << std::endl << " Allow/disallow automatic updates to authentication file." << std::endl << std::endl << " default [bind-address] [username] [password] [in-base64]:" << std::endl << " Add or update default record to provide default information for" << std::endl << " port records (set via update command)." << std::endl << " [bind-address] is default bind address for MySQL Server" << std::endl << " [username] is default username for login to MySQL Server" << std::endl << " [password] is default password for login to MySQL Server" << std::endl << " [in-base64] is \"true\" or \"false\" if record pw in Base64 format" << std::endl << " Default record is entirely optional, and need not exist. Specify" << std::endl << " an empty field as \"\"." << std::endl << std::endl << " delete [default|port#]:" << std::endl << " Delete default record or a port record in authentication file." << std::endl << std::endl << " exit:" << std::endl << " Saves changes and exits (only useful for interactive mode)." << std::endl << std::endl << " help:" << std::endl << " Display this help text." << std::endl << std::endl << " print:" << std::endl << " Print the contents of the MySQL provider authenticaiton file." << std::endl << std::endl << " quit:" << std::endl << " Quits interactive mode without saving changes." << std::endl << std::endl << " save:" << std::endl << " Save changes to disk. This is automatic for non-interactive mode." << std::endl << std::endl << " update [port#] [bind-address] [username] [password] [in-base64]:" << std::endl << " Add or update a port record to identify a MySQL Server instance in the" << std::endl << " authentication file." << std::endl << " [port#] is the port number for the MySQL Server instance" << std::endl << " [bind-address] is default bind address for MySQL Server" << std::endl << " [username] is default username for login to MySQL Server" << std::endl << " [password] is default password for login to MySQL Server" << std::endl << " [in-base64] is \"true\" or \"false\" if record pw in Base64 format" << std::endl << " Note that all information is validated by connecting to MySQL Server." << std::endl << " Specify an empty field as \"\"." << std::endl; CPPUNIT_ASSERT_EQUAL( expectedOutput.str(), processOutput.str() ); CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() ); CPPUNIT_ASSERT_EQUAL( 0, status ); } void test_OptionTest_Valid() { std::istringstream processInput; std::ostringstream processOutput; std::ostringstream processErr; int status = SCXProcess::Run(s_authProgram + L" -t", processInput, processOutput, processErr, s_timeout); CPPUNIT_ASSERT_EQUAL( std::string(""), processOutput.str() ); CPPUNIT_ASSERT_EQUAL( std::string("Error - No command specified or command keyword empty\n"), processErr.str() ); CPPUNIT_ASSERT_EQUAL( 3, status ); } void test_CommandPrint_Empty() { std::istringstream processInput; std::ostringstream processOutput; std::ostringstream processErr; int status = SCXProcess::Run(s_authProgram + L" -t print", processInput, processOutput, processErr, s_timeout); std::stringstream expectedOutput; expectedOutput << "[Automatic Updates: Enabled]" << std::endl << "[No default entry defined]" << std::endl; CPPUNIT_ASSERT_EQUAL( expectedOutput.str(), processOutput.str() ); CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() ); CPPUNIT_ASSERT_EQUAL( 0, status ); } void test_CommandQuit_DoesntUpdate() { std::istringstream processInput( std::string("autoupdate false\nprint\nquit\n") ); std::ostringstream processOutput; std::ostringstream processErr; int status = SCXProcess::Run(s_authProgram + L" -t -i", processInput, processOutput, processErr, s_timeout); std::stringstream expectedOutput; expectedOutput << "auth> autoupdate false" << std::endl << "auth> print" << std::endl << "[Automatic Updates: DISABLED]" << std::endl << "[No default entry defined]" << std::endl << "auth> quit" << std::endl; CPPUNIT_ASSERT_EQUAL( expectedOutput.str(), processOutput.str() ); CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() ); CPPUNIT_ASSERT_EQUAL( 0, status ); // Validate that the authentication file was written properly CPPUNIT_ASSERT( SCXFile::Exists( s_authFilePath ) ); std::vector<std::wstring> lines; SCXStream::NLFs nlfs; SCXFile::ReadAllLines( s_authFilePath, lines, nlfs ); CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), lines.size() ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"AutoUpdate=true"), lines[0] ); } void test_AutoUpdate_Interactive() { std::istringstream processInput( std::string("autoupdate false\nprint\nexit\n") ); std::ostringstream processOutput; std::ostringstream processErr; int status = SCXProcess::Run(s_authProgram + L" -t -i", processInput, processOutput, processErr, s_timeout); std::stringstream expectedOutput; expectedOutput << "auth> autoupdate false" << std::endl << "auth> print" << std::endl << "[Automatic Updates: DISABLED]" << std::endl << "[No default entry defined]" << std::endl << "auth> exit" << std::endl; CPPUNIT_ASSERT_EQUAL( expectedOutput.str(), processOutput.str() ); CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() ); CPPUNIT_ASSERT_EQUAL( 0, status ); // Validate that the authentication file was written properly CPPUNIT_ASSERT( SCXFile::Exists( s_authFilePath ) ); std::vector<std::wstring> lines; SCXStream::NLFs nlfs; SCXFile::ReadAllLines( s_authFilePath, lines, nlfs ); CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), lines.size() ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"AutoUpdate=false"), lines[0] ); } void test_AutoUpdate_CommandLine() { std::istringstream processInput; std::ostringstream processOutput; std::ostringstream processErr; int status = SCXProcess::Run(s_authProgram + L" -t autoupdate false", processInput, processOutput, processErr, s_timeout); CPPUNIT_ASSERT_EQUAL( std::string(""), processOutput.str() ); CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() ); CPPUNIT_ASSERT_EQUAL( 0, status ); // Validate that the authentication file was written properly CPPUNIT_ASSERT( SCXFile::Exists( s_authFilePath ) ); std::vector<std::wstring> lines; SCXStream::NLFs nlfs; SCXFile::ReadAllLines( s_authFilePath, lines, nlfs ); CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), lines.size() ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"AutoUpdate=false"), lines[0] ); } void test_Default_Interactive() { std::istringstream processInput( std::string("default " + sqlHostname + " " + sqlUsername + " " + sqlPassword + "\nprint\nexit\n") ); std::ostringstream processOutput; std::ostringstream processErr; int status = SCXProcess::Run(s_authProgram + L" -t -i", processInput, processOutput, processErr, s_timeout); std::stringstream expectedOutput; expectedOutput << "auth> default "<< sqlHostname << " " << sqlUsername << " " << sqlPassword << std::endl << "auth> print" << std::endl << "[Automatic Updates: Enabled]" << std::endl << std::endl << "Default Entry: " << std::endl << " Binding: " << sqlHostname << std::endl << " Username: root" << std::endl << " Password: root" << std::endl << "auth> exit" << std::endl; CPPUNIT_ASSERT_EQUAL( expectedOutput.str(), processOutput.str() ); CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() ); CPPUNIT_ASSERT_EQUAL( 0, status ); // Validate that the authentication file was written properly CPPUNIT_ASSERT( SCXFile::Exists( s_authFilePath ) ); std::vector<std::wstring> lines; SCXStream::NLFs nlfs; SCXFile::ReadAllLines( s_authFilePath, lines, nlfs ); CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(2), lines.size() ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"0=127.0.0.1, root, cm9vdA=="), lines[0] ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"AutoUpdate=true"), lines[1] ); } void test_Default_CommandLine() { std::istringstream processInput; std::ostringstream processOutput; std::ostringstream processErr; std::wstring commandLine(s_authProgram); commandLine += L" -t default " + StrFromUTF8(sqlHostname) + L" " + StrFromUTF8(sqlUsername) + L" " + StrFromUTF8(sqlPassword); int status = SCXProcess::Run(commandLine, processInput, processOutput, processErr, s_timeout); CPPUNIT_ASSERT_EQUAL( std::string(""), processOutput.str() ); CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() ); CPPUNIT_ASSERT_EQUAL( 0, status ); // Validate that the authentication file was written properly CPPUNIT_ASSERT( SCXFile::Exists( s_authFilePath ) ); std::vector<std::wstring> lines; SCXStream::NLFs nlfs; SCXFile::ReadAllLines( s_authFilePath, lines, nlfs ); CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(2), lines.size() ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"0=127.0.0.1, root, cm9vdA=="), lines[0] ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"AutoUpdate=true"), lines[1] ); } void test_Update_Interactive() { std::istringstream processInput( std::string( "default " + sqlHostname + " " + sqlUsername + " " + sqlPassword + "\n" "update 3306 \"\"\n" "print\n" "exit\n") ); std::ostringstream processOutput; std::ostringstream processErr; int status = SCXProcess::Run(s_authProgram + L" -t -i", processInput, processOutput, processErr, s_timeout); std::stringstream expectedOutput; expectedOutput << "auth> default " << sqlHostname << " " << sqlUsername << " " << sqlPassword << std::endl << "auth> update 3306 \"\"" << std::endl << "auth> print" << std::endl << "[Automatic Updates: Enabled]" << std::endl << std::endl << "Default Entry: " << std::endl << " Binding: " << sqlHostname << std::endl << " Username: " << sqlUsername << std::endl << " Password: " << sqlPassword << std::endl << std::endl << "Port 3306:" << std::endl << " Binding: <From Default>" << std::endl << " Username: <From Default>" << std::endl << " Password: <From Default>" << std::endl << "auth> exit" << std::endl; CPPUNIT_ASSERT_EQUAL( expectedOutput.str(), processOutput.str() ); CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() ); CPPUNIT_ASSERT_EQUAL( 0, status ); // Validate that the authentication file was written properly CPPUNIT_ASSERT( SCXFile::Exists( s_authFilePath ) ); std::vector<std::wstring> lines; SCXStream::NLFs nlfs; SCXFile::ReadAllLines( s_authFilePath, lines, nlfs ); CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(3), lines.size() ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"0=127.0.0.1, root, cm9vdA=="), lines[0] ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"3306=, ,"), lines[1] ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"AutoUpdate=true"), lines[2] ); } void test_Update_CommandLine() { std::istringstream processInput; std::ostringstream processOutput; std::ostringstream processErr; std::wstring commandLine(s_authProgram); commandLine += L" -t default " + StrFromUTF8(sqlHostname) + L" " + StrFromUTF8(sqlUsername) + L" " + StrFromUTF8(sqlPassword); int status = SCXProcess::Run(commandLine, processInput, processOutput, processErr, s_timeout); CPPUNIT_ASSERT_EQUAL( std::string(""), processOutput.str() ); CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() ); CPPUNIT_ASSERT_EQUAL( 0, status ); commandLine = s_authProgram + L" -t update 3306 " + StrFromUTF8(sqlHostname); status = SCXProcess::Run(commandLine, processInput, processOutput, processErr, s_timeout); CPPUNIT_ASSERT_EQUAL( std::string(""), processOutput.str() ); CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() ); CPPUNIT_ASSERT_EQUAL( 0, status ); // Validate that the authentication file was written properly CPPUNIT_ASSERT( SCXFile::Exists( s_authFilePath ) ); std::vector<std::wstring> lines; SCXStream::NLFs nlfs; SCXFile::ReadAllLines( s_authFilePath, lines, nlfs ); CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(3), lines.size() ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"0=127.0.0.1, root, cm9vdA=="), lines[0] ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"3306=127.0.0.1, ,"), lines[1] ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"AutoUpdate=true"), lines[2] ); } void test_Delete_Interactive() { std::istringstream processInput( std::string( "default " + sqlHostname + " " + sqlUsername + " " + sqlPassword + "\n" "update 3306 \"\"\n" "delete 3306\n" "delete default\n" "print\n" "exit\n") ); std::ostringstream processOutput; std::ostringstream processErr; int status = SCXProcess::Run(s_authProgram + L" -t -i", processInput, processOutput, processErr, s_timeout); std::stringstream expectedOutput; expectedOutput << "auth> default " << sqlHostname << " " << sqlUsername << " " << sqlPassword << std::endl << "auth> update 3306 \"\"" << std::endl << "auth> delete 3306" << std::endl << "auth> delete default" << std::endl << "auth> print" << std::endl << "[Automatic Updates: Enabled]" << std::endl << "[No default entry defined]" << std::endl << "auth> exit" << std::endl; CPPUNIT_ASSERT_EQUAL( expectedOutput.str(), processOutput.str() ); CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() ); CPPUNIT_ASSERT_EQUAL( 0, status ); // Validate that the authentication file was written properly CPPUNIT_ASSERT( SCXFile::Exists( s_authFilePath ) ); std::vector<std::wstring> lines; SCXStream::NLFs nlfs; SCXFile::ReadAllLines( s_authFilePath, lines, nlfs ); CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), lines.size() ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"AutoUpdate=true"), lines[0] ); } void test_Delete_CommandLine() { std::istringstream processInput; std::ostringstream processOutput; std::ostringstream processErr; // Create default record std::wstring commandLine(s_authProgram); commandLine += L" -t default " + StrFromUTF8(sqlHostname) + L" " + StrFromUTF8(sqlUsername) + L" " + StrFromUTF8(sqlPassword); int status = SCXProcess::Run(commandLine, processInput, processOutput, processErr, s_timeout); CPPUNIT_ASSERT_EQUAL( std::string(""), processOutput.str() ); CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() ); CPPUNIT_ASSERT_EQUAL( 0, status ); // Validate that the authentication file was written properly CPPUNIT_ASSERT( SCXFile::Exists( s_authFilePath ) ); std::vector<std::wstring> lines; SCXStream::NLFs nlfs; SCXFile::ReadAllLines( s_authFilePath, lines, nlfs ); CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(2), lines.size() ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"0=127.0.0.1, root, cm9vdA=="), lines[0] ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"AutoUpdate=true"), lines[1] ); // Create port 3306 record commandLine = s_authProgram + L" -t update 3306 " + StrFromUTF8(sqlHostname); status = SCXProcess::Run(commandLine, processInput, processOutput, processErr, s_timeout); CPPUNIT_ASSERT_EQUAL( std::string(""), processOutput.str() ); CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() ); CPPUNIT_ASSERT_EQUAL( 0, status ); // Validate that the authentication file was written properly CPPUNIT_ASSERT( SCXFile::Exists( s_authFilePath ) ); SCXFile::ReadAllLines( s_authFilePath, lines, nlfs ); CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(3), lines.size() ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"0=127.0.0.1, root, cm9vdA=="), lines[0] ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"3306=127.0.0.1, ,"), lines[1] ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"AutoUpdate=true"), lines[2] ); // Delete port 3306 record commandLine = s_authProgram + L" -t delete 3306"; status = SCXProcess::Run(commandLine, processInput, processOutput, processErr, s_timeout); CPPUNIT_ASSERT_EQUAL( std::string(""), processOutput.str() ); CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() ); CPPUNIT_ASSERT_EQUAL( 0, status ); // Validate that the authentication file was written properly CPPUNIT_ASSERT( SCXFile::Exists( s_authFilePath ) ); SCXFile::ReadAllLines( s_authFilePath, lines, nlfs ); CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(2), lines.size() ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"0=127.0.0.1, root, cm9vdA=="), lines[0] ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"AutoUpdate=true"), lines[1] ); // Delete default record commandLine = s_authProgram + L" -t delete default"; status = SCXProcess::Run(commandLine, processInput, processOutput, processErr, s_timeout); CPPUNIT_ASSERT_EQUAL( std::string(""), processOutput.str() ); CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() ); CPPUNIT_ASSERT_EQUAL( 0, status ); // Validate that the authentication file was written properly CPPUNIT_ASSERT( SCXFile::Exists( s_authFilePath ) ); SCXFile::ReadAllLines( s_authFilePath, lines, nlfs ); CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), lines.size() ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"AutoUpdate=true"), lines[0] ); } }; CPPUNIT_TEST_SUITE_REGISTRATION( MyCimprovAuth_Test );
45.428058
141
0.598305
27a228655f5fe4c49b886949898cbc561d65c722
2,891
hpp
C++
include/Graphy/Graphables/Styles/LabelStyle.hpp
dominicprice/Graphy
4553adf06e9c63365ed2ef994fa76c460f8673f4
[ "MIT" ]
null
null
null
include/Graphy/Graphables/Styles/LabelStyle.hpp
dominicprice/Graphy
4553adf06e9c63365ed2ef994fa76c460f8673f4
[ "MIT" ]
null
null
null
include/Graphy/Graphables/Styles/LabelStyle.hpp
dominicprice/Graphy
4553adf06e9c63365ed2ef994fa76c460f8673f4
[ "MIT" ]
null
null
null
///////////////////////////////////////////////////////////////////////////////// //MIT License // //Copyright(c) 2017 Dominic Price // //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. ///////////////////////////////////////////////////////////////////////////////// #ifndef GRAPHY_LABELSTYLE_H #define GRAPHY_LABELSTYLE_H //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <string> #include <SFML/Graphics/Color.hpp> namespace graphy { struct LabelStyle { //////////////////////////////////////////////////////////// /// \brief Enumeration defining where the label should float relative to its position /// //////////////////////////////////////////////////////////// enum Float : signed char { above_right = 0, ///< Above and to the right of a point below_right = 1, ///< Below and to the right of a point above_left = 2, ///< Above and to the left of a point below_left = 3, ///< Below and to the left of a point _unset = -1 ///< Ambiguous, may be drawn anywhere }; //////////////////////////////////////////////////////////// /// \brief Default constructor /// /// Constructs a default style. /// //////////////////////////////////////////////////////////// LabelStyle() : enabled(true), text(), color(sf::Color::Black), size(15), pos(Float::below_left), x(0), offset(0) {} bool enabled; ///< Labels will only display if this is set to true std::string text; ///< Label text sf::Color color; ///< Colour of label unsigned int size; ///< Height of label in pixels Float pos; ///< Placement of label relative to position double x; ///< x-coordinate of label for objects with extended length float offset; ///< offset of label from its position }; } // namespace graphy #endif //GRAPHY_LABELSTYLE_H
36.1375
87
0.583189
27a6b11730fa13345cf43b0a3ed5ce356008fcee
1,848
hpp
C++
ParticleSystem/src/ParticleUpdater.hpp
Azatsu/ParticleSystem
8d8a5f41200c1865089b3b2dff8c41cc63dc3b13
[ "MIT" ]
1
2021-05-05T06:42:19.000Z
2021-05-05T06:42:19.000Z
ParticleSystem/src/ParticleUpdater.hpp
Azatsu/ParticleSystem
8d8a5f41200c1865089b3b2dff8c41cc63dc3b13
[ "MIT" ]
5
2021-05-04T10:05:11.000Z
2021-05-05T08:28:02.000Z
ParticleSystem/src/ParticleUpdater.hpp
Azatsu/ParticleSystem
8d8a5f41200c1865089b3b2dff8c41cc63dc3b13
[ "MIT" ]
null
null
null
#ifndef __PRTCL_UPDT_HPP__ #define __PRTCL_UPDT_HPP__ #include <vector> #include <algorithm> #include "particleGenerator.hpp" class ParticleUpdater { public: ParticleUpdater() { } virtual ~ParticleUpdater() { } virtual void Update(float dt, ParticleData* p) = 0; }; class EulerUpdater : public ParticleUpdater { public: float4 globalAcceleration; public: EulerUpdater() : globalAcceleration(0.f, 0.f, 0.f, 0.f) { } virtual void Update(float dt, ParticleData* p) override; }; // collision with the floor :) todo: implement a collision model class FloorUpdater : public ParticleUpdater { public: float floorY; float bounceFactor; public: FloorUpdater() :floorY(0.0), bounceFactor(0.5f) { } virtual void Update(float dt, ParticleData* p) override; }; class AttractorUpdater : public ParticleUpdater { protected: std::vector<float4> attractors; // .w is force public: virtual void Update(float dt, ParticleData* p) override; size_t CollectionSize() const { return attractors.size(); } void Add(const float4& attr) { attractors.push_back(attr); } float4& Get(size_t id) { return attractors[id]; } }; class BasicColorUpdater : public ParticleUpdater { public: virtual void Update(float dt, ParticleData* p) override; }; class PosColorUpdater : public ParticleUpdater { public: float4 minPos; float4 maxPos; public: PosColorUpdater() : minPos(0.f, 0.f, 0.f, 0.f), maxPos(1.f, 1.f, 1.f, 1.f) { } virtual void Update(float dt, ParticleData* p) override; }; class VelColorUpdater : public ParticleUpdater { public: float4 minVel; float4 maxVel; public: VelColorUpdater() : minVel(0.f, 0.f, 0.f, 0.f), maxVel(1.f, 1.f, 1.f, 1.f) { } virtual void Update(float dt, ParticleData* p) override; }; class BasicTimeUpdater : public ParticleUpdater { public: virtual void Update(float dt, ParticleData* p) override; }; #endif
21.488372
79
0.731061
27a79a997fe218c175ba9a076c86934794aa53d3
96
hh
C++
vm/vm/main/cached/Unit-implem-decl.hh
Ahzed11/mozart2
4806504b103e11be723e7813be8f69e4d85875cf
[ "BSD-2-Clause" ]
379
2015-01-02T20:27:33.000Z
2022-03-26T23:18:17.000Z
vm/vm/main/cached/Unit-implem-decl.hh
Ahzed11/mozart2
4806504b103e11be723e7813be8f69e4d85875cf
[ "BSD-2-Clause" ]
81
2015-01-08T13:18:52.000Z
2021-12-21T14:02:21.000Z
vm/vm/main/cached/Unit-implem-decl.hh
Ahzed11/mozart2
4806504b103e11be723e7813be8f69e4d85875cf
[ "BSD-2-Clause" ]
75
2015-01-06T09:08:20.000Z
2021-12-17T09:40:18.000Z
class Unit; template <> class Storage<Unit> { public: typedef struct mozart::unit_t Type; };
12
37
0.708333
27a7c014c2902b7a8d7ab0d4b44e8fa5b6538169
1,632
cpp
C++
Gym/0719/c.cpp
tusikalanse/acm-icpc
20150f42752b85e286d812e716bb32ae1fa3db70
[ "MIT" ]
2
2021-06-09T12:27:07.000Z
2021-06-11T12:02:03.000Z
Gym/0719/c.cpp
tusikalanse/acm-icpc
20150f42752b85e286d812e716bb32ae1fa3db70
[ "MIT" ]
1
2021-09-08T12:00:05.000Z
2021-09-08T14:52:30.000Z
Gym/0719/c.cpp
tusikalanse/acm-icpc
20150f42752b85e286d812e716bb32ae1fa3db70
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; const int MAXN = 405; int val[MAXN][MAXN], dis[MAXN], vis[MAXN]; int T, n, m, k, W, w, s, t, op; struct node { int id, d; bool operator<(const node &rhs) const { return id > rhs.id; } }; vector<pair<int,int>> toerase; bool hd; void dfs(int id, int des) { if(hd) return; if(id == des) { hd = 1; return; } for(int i = des; hd == 0 && i > id; --i) { if(dis[i] - dis[id] == val[id][i]) { toerase.push_back(make_pair(id, i)); dfs(i, des); if(!hd) toerase.pop_back(); } } } int dijk() { memset(dis, -1, sizeof(dis)); memset(vis, 0, sizeof(vis)); priority_queue<node> q; q.push({0, 0}); dis[0] = 0; vis[0] = 1; while(!q.empty()) { node u = q.top(); q.pop(); vis[u.id] = 1; if(dis[u.id] > u.d) continue; for(int i = u.id + 1; i <= 2 * n; ++i) if(vis[i] == 0) { if(dis[i] < dis[u.id] + val[u.id][i]) { dis[i] = dis[u.id] + val[u.id][i]; q.push({i, dis[i]}); } } } int mmax = dis[2 * n], id = 2 * n; if(mmax < dis[2 * n - 1]) { mmax = dis[2 * n - 1]; id = 2 * n - 1; } toerase.resize(0); hd = 0; dfs(0, id); for(auto it : toerase) { val[it.first][it.second] = 0; } return mmax; } int main() { scanf("%d", &T); while(T--) { memset(val, 0, sizeof(val)); scanf("%d%d%d%d", &n, &m, &k, &W); while(m--) { scanf("%d%d%d%d", &s, &t, &w, &op); if(op == 0) { val[2 * s][2 * t] = w - W; val[2 * s - 1][2 * t] = w; } else { val[2 * s - 1][2 * t - 1] = w - W; val[2 * s][2 * t - 1] = w; } } int ans = 0; while(k--) { ans += dijk(); } printf("%d\n", ans); } return 0; }
18.133333
58
0.474265
27a836943d08f7a9b12542c16ca7586f2d6c4e34
1,689
cpp
C++
BRAC University Competitive Programming training/Prefix sum/chechinkg range for a particular summation.cpp
Mit382/Mitul-s-Competitive-Programming-March-August
3b0d9b3d018444584020e37b892021f7e9ec984d
[ "MIT" ]
1
2021-04-23T16:53:35.000Z
2021-04-23T16:53:35.000Z
BRAC University Competitive Programming training/Prefix sum/chechinkg range for a particular summation.cpp
Mit382/Mitul-s-Competitive-Programming-March-August
3b0d9b3d018444584020e37b892021f7e9ec984d
[ "MIT" ]
null
null
null
BRAC University Competitive Programming training/Prefix sum/chechinkg range for a particular summation.cpp
Mit382/Mitul-s-Competitive-Programming-March-August
3b0d9b3d018444584020e37b892021f7e9ec984d
[ "MIT" ]
1
2021-03-27T19:56:19.000Z
2021-03-27T19:56:19.000Z
//Question in array 1 , -1, 0,2 there is how many ranges, that can make the summation 2? //Input: //4 2 //1 -1 0 2 //Output: //3 //solve: //index: 0 1 2 3 4 //array 1 -1 0 2 //prefix: 0 1 0 0 2 // check that there is 2 , (0,2 ), (1,-1,0,2) can make summation 2. thus answer is 3 //now check the prefix array and relate: prefix[4]-2=0 . here 0 is there 3 times beacuse in the prefix we assume index 0 has default value =0 and such 0 is there 3 times and that is the answer. Note: prefix[4]=2 #include<bits/stdc++.h> using namespace std; int main(){ ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n,s; cin>>n>>s; //n+1 beacuse in for loop we took i=1 to i<=n and thus vector<long long int > input(n+1);//creating input vecor (dynamic array). Note:1≤xi≤10^9 in problem and thus you may need to add a lot of this and it may exceed the integer range and thus long long integer is suggested vector<long long int>pref(n+1);// creating prefix vecor . Note:1≤xi≤10^9 in problem and thus you may need to add a lot of this and it may exceed the integer range and thus long long integer is suggested for(int i=1; i<=n;i++){ cin>>input[i]; } //Prefix sum building pref[0]=0; //prefix[0]=0 for(int i=1; i<=n;i++){ pref[i]=pref[i-1]+input[i]; } map<long long int, int> mp; long long int ans=0;// defining from the map; mp[0]=1;//defining from the map for( int i=1; i<=n;i++){ long long int key=pref[i]-s; ans+=mp[key]; mp[pref[i]]++;// adding value to map's 2nd parameter } cout<<ans<<endl; return 0; }
31.867925
222
0.606868
27ad1a1f8e279742a161e298429f27e55e93c7b6
1,481
cc
C++
src/Parser/AST/MatchStatementNode.cc
stenbror/PythonCoreNative
9b5b1e55acf7d6adc7d8202e951872b2b9f71167
[ "BSL-1.0" ]
null
null
null
src/Parser/AST/MatchStatementNode.cc
stenbror/PythonCoreNative
9b5b1e55acf7d6adc7d8202e951872b2b9f71167
[ "BSL-1.0" ]
null
null
null
src/Parser/AST/MatchStatementNode.cc
stenbror/PythonCoreNative
9b5b1e55acf7d6adc7d8202e951872b2b9f71167
[ "BSL-1.0" ]
1
2021-05-24T11:18:32.000Z
2021-05-24T11:18:32.000Z
#include <ast/MatchStatementNode.h> using namespace PythonCoreNative::RunTime::Parser::AST; using namespace PythonCoreNative::RunTime::Parser; MatchStatementNode::MatchStatementNode( unsigned int start, unsigned int end, std::shared_ptr<Token> op1, std::shared_ptr<AST::StatementNode> left, std::shared_ptr<Token> op2, std::shared_ptr<Token> op3, std::shared_ptr<Token> op4, std::shared_ptr<std::vector<std::shared_ptr<StatementNode>>> nodes, std::shared_ptr<Token> op5 ) : StatementNode(start, end) { mOp1 = op1; mLeft = left; mOp2 = op2; mOp3 = op3; mOp4 = op4; mNodes = nodes; mOp3 = op5; } std::shared_ptr<Token> MatchStatementNode::GetOperator1() { return mOp1; } std::shared_ptr<Token> MatchStatementNode::GetOperator2() { return mOp2; } std::shared_ptr<Token> MatchStatementNode::GetOperator3() { return mOp3; } std::shared_ptr<Token> MatchStatementNode::GetOperator4() { return mOp4; } std::shared_ptr<Token> MatchStatementNode::GetOperator5() { return mOp5; } std::shared_ptr<AST::StatementNode> MatchStatementNode::GetLeft() { return mLeft; } std::shared_ptr<std::vector<std::shared_ptr<StatementNode>>> MatchStatementNode::GetNodes() { return mNodes; }
24.278689
95
0.602296
27ad2135e457a7db745ea1d84b8fd2e9f8eb59b5
1,239
cpp
C++
arm9/source/menuDemo.cpp
henke37/hblankmegademo
638d6200c930e305acb6aea341211cff99dc5893
[ "BSD-2-Clause" ]
2
2019-09-01T14:31:51.000Z
2019-09-10T11:00:20.000Z
arm9/source/menuDemo.cpp
henke37/hblankmegademo
638d6200c930e305acb6aea341211cff99dc5893
[ "BSD-2-Clause" ]
8
2017-09-24T20:21:15.000Z
2022-03-04T15:29:05.000Z
arm9/source/menuDemo.cpp
henke37/hblankmegademo
638d6200c930e305acb6aea341211cff99dc5893
[ "BSD-2-Clause" ]
2
2019-02-04T02:59:42.000Z
2019-02-05T06:16:07.000Z
#include "menuDemo.h" #include "sinScrollDemo.h" #include "peepHoleWindowDemo.h" #include "spotlightDemo.h" #include "demoRunner.h" #include "scanInDemo.h" #include "rasterbarDemo.h" #include "flutterDemo.h" #include <nds/arm9/console.h> #include <cassert> #include <nds/arm9/input.h> MenuDemo::MenuDemo() : selection(0) {} MenuDemo::~MenuDemo() {} void MenuDemo::Load() { setupDefaultBG(); consoleClear(); } void MenuDemo::Unload() {} void MenuDemo::PrepareFrame(VramBatcher &) {} void MenuDemo::AcceptInput() { auto keys = keysDown(); if(keys & KEY_UP && selection > 0) { selection--; } else if(keys & KEY_DOWN && selection+1 < demoCount) { selection++; } if(keys & KEY_START) { runner.RunDemo(makeDemo()); } } std::shared_ptr<Demo> MenuDemo::makeDemo() { switch(selection) { case 0: return std::make_shared<SinXScrollDemo>(); case 1: return std::make_shared<SinYScrollDemo>(); case 2: return std::make_shared<ScanInDemo>(); case 3: return std::make_shared<PeepHoleWindowDemo>(); case 4: return std::make_shared<SpotLightDemo>(); case 5: return std::make_shared<RasterBarDemo>(); case 6: return std::make_shared<FlutterDemo>(); } sassert(0,"Bad menu selection instatiated"); assert(0); }
21
56
0.696529
27b1c2cd6ce82237c2f7d858ce0e4ac2557e9295
487
hpp
C++
src/util.hpp
Cynnexis/dna-not-ascii
9df62c48f530297a12c9c0328a8d3e115c5c18cf
[ "MIT" ]
null
null
null
src/util.hpp
Cynnexis/dna-not-ascii
9df62c48f530297a12c9c0328a8d3e115c5c18cf
[ "MIT" ]
1
2021-03-03T08:51:30.000Z
2021-03-03T08:51:30.000Z
src/util.hpp
Cynnexis/dna-not-ascii
9df62c48f530297a12c9c0328a8d3e115c5c18cf
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include <functional> #include <cstdlib> #include <string> #include <sstream> #include <cassert> using std::cout, std::cerr, std::cin, std::endl, std::string; /** * @brief Get the current epoch in milliseconds. * @details Source code inspired from https://stackoverflow.com/a/17371925/7347145 * by Dan Moulding and Raedwald. * * @return unsigned long The time in milliseconds starting from January the 1st, * 1970. */ unsigned long epochMs();
23.190476
82
0.722793
27b7166908d70e2f3a7588a7d6f426a25888dffc
1,287
cpp
C++
VeronixApp.cpp
LNAV/Sudoku_Solver_Cpp
431a5d0e370d3d5f7da33674601f3a57efd7032a
[ "Apache-2.0" ]
1
2020-05-17T11:46:46.000Z
2020-05-17T11:46:46.000Z
VeronixApp.cpp
LNAV/VeronixApp-Sudoku_Solver
431a5d0e370d3d5f7da33674601f3a57efd7032a
[ "Apache-2.0" ]
null
null
null
VeronixApp.cpp
LNAV/VeronixApp-Sudoku_Solver
431a5d0e370d3d5f7da33674601f3a57efd7032a
[ "Apache-2.0" ]
null
null
null
/* * VeronixApp.cpp * * Created on: May 18, 2019 * Author: LavishK1 */ #include <SudokuConsoleViewController.h> #include "VeronixApp.h" #include "AppDefines.h" #include "APP/GridSolver.h" #include "APP/Helper/InputHelper.h" namespace Veronix { namespace App { VeronixApp::VeronixApp() { DEF_COUT( "VeronixApp::VeronixApp" ); } VeronixApp::~VeronixApp() { DEF_COUT( "VeronixApp::~VeronixApp" ); } void VeronixApp::start() { DEF_COUT( "This is a Start" ); try { helper::InputHelper inputProcessor; const Array::TabularArray<int> & gridValues = inputProcessor.getSudokuGridData(/*helper::console_read*/); sudosolver::container::GridContainer gridContainer(gridValues); viewcontroller::SudokuViewController sudokuView(gridContainer); DEF_COUT( "Before Solving Sudoku: " ); sudokuView.displaySudoku(); sudosolver::GridSolver gridSolver(gridContainer); gridSolver.solveGrid(); DEF_COUT( "After Solving Sudoku: " ); sudokuView.displaySudoku(); } catch (const std::string e) { DEF_COUT( "Exception Thrown" << e ); } catch (const char * e) { DEF_COUT( "Exception Thrown int *: " << e ); } catch (...) { DEF_COUT("Exception is thrown somewhere"); } DEF_COUT( "Start Ended Here" ); } } /* namespace App */ } /* namespace Veronix */
18.652174
107
0.694639
27ba6a4992b0b98dd27c85182d91b4b2eb479c1f
1,729
cc
C++
components/shared_highlighting/core/common/disabled_sites.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
components/shared_highlighting/core/common/disabled_sites.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
components/shared_highlighting/core/common/disabled_sites.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2020 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. #include "components/shared_highlighting/core/common/disabled_sites.h" #include "base/feature_list.h" #include "components/shared_highlighting/core/common/shared_highlighting_features.h" #include "third_party/re2/src/re2/re2.h" #include <map> #include <utility> namespace shared_highlighting { bool ShouldOfferLinkToText(const GURL& url) { if (base::FeatureList::IsEnabled(kSharedHighlightingUseBlocklist)) { // If a URL's host matches a key in this map, then the path will be tested // against the RE stored in the value. For example, {"foo.com", ".*"} means // any page on the foo.com domain. const static std::map<std::string, std::string> kBlocklist = { {"facebook.com", ".*"}, // TODO(crbug.com/1157981): special case this to cover other Google TLDs {"google.com", "^\\/amp\\/.*"}, {"instagram.com", ".*"}, {"mail.google.com", ".*"}, {"outlook.live.com", ".*"}, {"reddit.com", ".*"}, {"twitter.com", ".*"}, {"web.whatsapp.com", ".*"}, {"youtube.com", ".*"}, }; std::string domain = url.host(); if (domain.compare(0, 4, "www.") == 0) { domain = domain.substr(4); } else if (domain.compare(0, 2, "m.") == 0) { domain = domain.substr(2); } else if (domain.compare(0, 7, "mobile.") == 0) { domain = domain.substr(7); } auto it = kBlocklist.find(domain); if (it != kBlocklist.end()) { return !re2::RE2::FullMatch(url.path(), it->second); } } return true; } } // namespace shared_highlighting
32.622642
84
0.614806
27bf7731c49ad3e4ee83bc3d6c5443f9e1de0774
1,980
hpp
C++
include/Animation.hpp
prfcto2/noName
e179d49282755039f2acb267931ef445aff5000b
[ "MIT" ]
3
2019-08-05T13:33:01.000Z
2022-02-14T12:55:18.000Z
include/Animation.hpp
prfcto2/noName
e179d49282755039f2acb267931ef445aff5000b
[ "MIT" ]
null
null
null
include/Animation.hpp
prfcto2/noName
e179d49282755039f2acb267931ef445aff5000b
[ "MIT" ]
null
null
null
# define ANIMATION_HPP # ifndef HELPERS_HPP # include <Helpers.hpp> # endif # include <vector> //Animation has the animation's frames, it's duration and it's loop conditional. // if the animation is looping, it means that the animation is going to repite itself // in the pass of time but, if it is not looping, it is going to show it last frame after the // total duration has been reached class Animation { public: // constructor takes as parameters the total time to get to the last frame // and if it is going to loop Animation(const sf::Time &, bool = false); Animation(const Animation &); ~Animation(); //sets animation time elapsed to zero void reset(); // methods identifiers are pretty clear I believe void setDuraton(const sf::Time &); void setLooping(bool); sf::Texture & getFrame() const; const sf::Time & getDuration() const; const sf::Time & getElapsed() const; bool getLooping() const; size_t size() const; // it's mean to work as a manual setter of frames getting as parameter // the complete path of it's texture on assets folder void addFrame(const std::string &); // parameter 1 is the path to a folder of animation, // for simplicity, our animations using this method are going to have a name // "frame" and what our function does is to take all frames starting from 1. // it takes all frames placed on the prefix path // parameter 2 is the postfx of the frame,s by default they are ".png" void addFrames(const std::string &, const std::string & = ".png", bool = false); void addFrames(const std::string &, bool); // @note: This method is setted virtual so we can define different types of interactions // from derived classes, with aims of class Enemies having a global Animator. virtual void update(const sf::Time &); private: std::vector<sf::Texture *> m_frames; sf::Time m_duration; bool m_looping; sf::Time m_elapsed; uint m_pos; };
33
93
0.697475
27c63cfb63003f012076586134080800fb72ffc3
46
cpp
C++
libs/vis_utils/summedareatable.cpp
danniesim/cpp_volume_rendering
242c8917aea0a58c9851c2ae3e6c1555db51912e
[ "MIT" ]
10
2020-05-15T23:50:19.000Z
2022-02-17T09:54:44.000Z
libs/vis_utils/summedareatable.cpp
danniesim/cpp_volume_rendering
242c8917aea0a58c9851c2ae3e6c1555db51912e
[ "MIT" ]
1
2022-01-25T02:36:59.000Z
2022-01-26T11:41:38.000Z
libs/vis_utils/summedareatable.cpp
danniesim/cpp_volume_rendering
242c8917aea0a58c9851c2ae3e6c1555db51912e
[ "MIT" ]
3
2021-11-01T10:32:46.000Z
2021-12-28T16:40:10.000Z
#include "summedareatable.h" namespace vis {}
11.5
28
0.76087
27cbf90cb2a6126f4154915a781b815cccc234b3
4,422
cpp
C++
TestApps/bnn/bin_dense_tb.cpp
HansGiesen/hls_tuner
9c8d03737d1115f4e5cfa03cabc2334ea8b3ca19
[ "MIT" ]
1
2021-02-21T12:13:09.000Z
2021-02-21T12:13:09.000Z
TestApps/bnn/bin_dense_tb.cpp
HansGiesen/hls_tuner
9c8d03737d1115f4e5cfa03cabc2334ea8b3ca19
[ "MIT" ]
null
null
null
TestApps/bnn/bin_dense_tb.cpp
HansGiesen/hls_tuner
9c8d03737d1115f4e5cfa03cabc2334ea8b3ca19
[ "MIT" ]
1
2019-09-10T16:45:27.000Z
2019-09-10T16:45:27.000Z
#include <random> #include <ap_int.h> const unsigned WORD_SIZE = 64; const unsigned CONVOLVERS = 2; const unsigned CONV_W_PER_WORD = 7; const unsigned WT_L = 16*4*512*64; // parameter to control wt mem size const unsigned C_WT_WORDS = ((WT_L+CONV_W_PER_WORD-1)/CONV_W_PER_WORD + CONVOLVERS-1) / CONVOLVERS; // wt words per convolver const unsigned KH_WORDS = WT_L/128*16 / WORD_SIZE; const unsigned DMEM_WORDS = 128*32*32 / WORD_SIZE; const unsigned C_DMEM_WORDS = DMEM_WORDS / CONVOLVERS; typedef ap_int<WORD_SIZE> Word; typedef ap_uint<22> Address; enum LayerTypeEnum {LAYER_CONV1, LAYER_CONV, LAYER_DENSE, LAYER_LAST}; void bin_dense_orig( const Word wt_mem[CONVOLVERS][C_WT_WORDS], const Word kh_mem[KH_WORDS], Word dmem[2][CONVOLVERS][C_DMEM_WORDS], ap_uint<2> layer_type, ap_uint<1> d_i_idx, ap_uint<1> d_o_idx, const Address o_index, const unsigned n_inputs, const unsigned n_outputs ); typedef ap_uint<1> Input; typedef ap_uint<1> Output; typedef ap_int<16> Sum; typedef ap_uint<1> Weight; typedef ap_int<16> Norm_coef; typedef ap_uint<4> Pred; typedef ap_fixed<16, 2> Scale; typedef ap_fixed<16, 4> Offset; void bin_dense_0(Input input[8192], Output output[1024], Weight weights[8192 * 1024], Norm_coef norm_coefs[1024]); void bin_dense_1(Input input[1024], Output output[1024], Weight weights[1024 * 1024], Norm_coef norm_coefs[1024]); void bin_dense_2(Input input[1024], Pred & pred, Weight weights[1024 * 10], Scale scales[10], Offset offsets[10]); template <unsigned in_cnt, unsigned out_cnt> int bin_dense_tb_core() { std::random_device rd; std::default_random_engine generator; std::uniform_int_distribution<long long unsigned> distribution(0, 0xFFFFFFFFFFFFFFFF); auto wt_mem = new Word[CONVOLVERS][C_WT_WORDS]; for (int i = 0; i < CONVOLVERS; i++) for (int j = 0; j < C_WT_WORDS; j++) wt_mem[i][j] = distribution(generator); auto kh_mem = new Word[KH_WORDS]; for (int i = 0; i < KH_WORDS; i++) kh_mem[i] = distribution(generator); auto dmem = new Word[2][CONVOLVERS][C_DMEM_WORDS]; for (int i = 0; i < 2; i++) for (int j = 0; j < CONVOLVERS; j++) for (int k = 0; k < C_DMEM_WORDS; k++) dmem[i][j][k] = distribution(generator); bin_dense_orig(wt_mem, kh_mem, dmem, out_cnt == 1024 ? LAYER_DENSE : LAYER_LAST, 0, 1, 0, in_cnt, out_cnt); auto input = new Input[in_cnt]; for (int i = 0; i < in_cnt / WORD_SIZE / CONVOLVERS; i++) for (int j = 0; j < CONVOLVERS; j++) for (int k = 0; k < WORD_SIZE; k++) input[(i * CONVOLVERS + j) * WORD_SIZE + k] = dmem[0][j][i][k]; auto output = new Output[out_cnt]; Pred pred; auto weights = new Weight[in_cnt * out_cnt]; for (int i = 0; i < in_cnt * out_cnt / WORD_SIZE / CONVOLVERS; i++) for (int j = 0; j < CONVOLVERS; j++) for (int k = 0; k < WORD_SIZE; k++) weights[(i * CONVOLVERS + j) * WORD_SIZE + k] = wt_mem[j][i][k]; auto norm_coefs = new Norm_coef[out_cnt]; for (int i = 0; i < out_cnt; i++) norm_coefs[i] = kh_mem[i / 4].range(16 * (i % 4) + 15, 16 * (i % 4)); auto scales = new Scale[out_cnt]; auto offsets = new Offset[out_cnt]; for (int i = 0; i < 2 * out_cnt; i++) { ap_uint<16> value = kh_mem[i / 4].range(16 * (i % 4) + 15, 16 * (i % 4)); if (i % 2 == 0) scales[i / 2](15, 0) = value; else offsets[i / 2](15, 0) = value; } if (in_cnt == 8192) bin_dense_0(input, output, weights, norm_coefs); else if (out_cnt == 1024) bin_dense_1(input, output, weights, norm_coefs); else bin_dense_2(input, pred, weights, scales, offsets); if (out_cnt == 1024) { for (int i = 0; i < out_cnt / WORD_SIZE / CONVOLVERS; i++) for (int j = 0; j < CONVOLVERS; j++) for (int k = 0; k < WORD_SIZE; k++) if (output[(i * CONVOLVERS + j) * WORD_SIZE + k] != dmem[1][j][i][k]) return true; } else if (dmem[1][0][0].range(3, 0) != pred) return true; delete[] wt_mem; delete[] kh_mem; delete[] dmem; delete[] input; delete[] output; delete[] weights; delete[] norm_coefs; delete[] scales; delete[] offsets; return false; } int bin_dense_tb() { if (bin_dense_tb_core<8192, 1024>()) return true; if (bin_dense_tb_core<1024, 1024>()) return true; if (bin_dense_tb_core<1024, 10>()) return true; printf("bin_dense_tb was successful.\n"); return false; }
31.585714
128
0.644731
27cc89b508504ad3d2e1b8f11c79735721451191
1,441
cpp
C++
src/image/todo/bezier.cpp
TurkMvc/lol
c3fb98c6f371e4648891b59b4adc6cb95ae73451
[ "WTFPL" ]
4
2015-02-14T21:14:25.000Z
2021-12-12T15:45:44.000Z
src/image/todo/bezier.cpp
TurkMvc/lol
c3fb98c6f371e4648891b59b4adc6cb95ae73451
[ "WTFPL" ]
3
2015-02-14T20:56:26.000Z
2015-02-16T08:50:54.000Z
src/image/todo/bezier.cpp
TurkMvc/lol
c3fb98c6f371e4648891b59b4adc6cb95ae73451
[ "WTFPL" ]
1
2021-10-06T16:01:03.000Z
2021-10-06T16:01:03.000Z
/* * Lol Engine * * Copyright © 2004—2008 Sam Hocevar <sam@hocevar.net> * © 2008 Jean-Yves Lamoureux <jylam@lnxscene.org> * * This library is free software. It comes without any warranty, to * the extent permitted by applicable law. You can redistribute it * and/or modify it under the terms of the Do What the Fuck You Want * to Public License, Version 2, as published by the WTFPL Task Force. * See http://www.wtfpl.net/ for more details. */ /* * bezier.c: bezier curves rendering functions */ #include "config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "pipi.h" #include "pipi-internals.h" int pipi_draw_bezier4(pipi_image_t *img , int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, uint32_t c, int n, int aa) { if(img->last_modified == PIPI_PIXELS_RGBA_U8) { float t; float x= x1, y= y1; float lx, ly; for(t=0; t<1; t+=(1.0f/n)) { float a = t; float b = 1 - t; lx = x; ly = y; x = (x1*(b*b*b)) + 3*x2*(b*b)*a + 3*x4*b*(a*a) + x3*(a*a*a); y = (y1*(b*b*b)) + 3*y2*(b*b)*a + 3*y4*b*(a*a) + y3*(a*a*a); pipi_draw_line(img , lx, ly, x, y, c, aa); } pipi_draw_line(img , x, y, x3, y3, c, aa); } return 0; }
25.280702
72
0.517696
27d0429e58d7d8f5e96edd66b15c88fb56dc89ac
21,788
cc
C++
wrappers/7.0.0/vtkPointSetToLabelHierarchyWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
6
2016-02-03T12:48:36.000Z
2020-09-16T15:07:51.000Z
wrappers/7.0.0/vtkPointSetToLabelHierarchyWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
4
2016-02-13T01:30:43.000Z
2020-03-30T16:59:32.000Z
wrappers/7.0.0/vtkPointSetToLabelHierarchyWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
null
null
null
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include <nan.h> #include "vtkLabelHierarchyAlgorithmWrap.h" #include "vtkPointSetToLabelHierarchyWrap.h" #include "vtkObjectWrap.h" #include "vtkTextPropertyWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap; Nan::Persistent<v8::FunctionTemplate> VtkPointSetToLabelHierarchyWrap::ptpl; VtkPointSetToLabelHierarchyWrap::VtkPointSetToLabelHierarchyWrap() { } VtkPointSetToLabelHierarchyWrap::VtkPointSetToLabelHierarchyWrap(vtkSmartPointer<vtkPointSetToLabelHierarchy> _native) { native = _native; } VtkPointSetToLabelHierarchyWrap::~VtkPointSetToLabelHierarchyWrap() { } void VtkPointSetToLabelHierarchyWrap::Init(v8::Local<v8::Object> exports) { Nan::SetAccessor(exports, Nan::New("vtkPointSetToLabelHierarchy").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("PointSetToLabelHierarchy").ToLocalChecked(), ConstructorGetter); } void VtkPointSetToLabelHierarchyWrap::ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkPointSetToLabelHierarchyWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); VtkLabelHierarchyAlgorithmWrap::InitPtpl( ); tpl->Inherit(Nan::New<FunctionTemplate>(VtkLabelHierarchyAlgorithmWrap::ptpl)); tpl->SetClassName(Nan::New("VtkPointSetToLabelHierarchyWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "GetBoundedSizeArrayName", GetBoundedSizeArrayName); Nan::SetPrototypeMethod(tpl, "getBoundedSizeArrayName", GetBoundedSizeArrayName); Nan::SetPrototypeMethod(tpl, "GetClassName", GetClassName); Nan::SetPrototypeMethod(tpl, "getClassName", GetClassName); Nan::SetPrototypeMethod(tpl, "GetIconIndexArrayName", GetIconIndexArrayName); Nan::SetPrototypeMethod(tpl, "getIconIndexArrayName", GetIconIndexArrayName); Nan::SetPrototypeMethod(tpl, "GetLabelArrayName", GetLabelArrayName); Nan::SetPrototypeMethod(tpl, "getLabelArrayName", GetLabelArrayName); Nan::SetPrototypeMethod(tpl, "GetMaximumDepth", GetMaximumDepth); Nan::SetPrototypeMethod(tpl, "getMaximumDepth", GetMaximumDepth); Nan::SetPrototypeMethod(tpl, "GetOrientationArrayName", GetOrientationArrayName); Nan::SetPrototypeMethod(tpl, "getOrientationArrayName", GetOrientationArrayName); Nan::SetPrototypeMethod(tpl, "GetPriorityArrayName", GetPriorityArrayName); Nan::SetPrototypeMethod(tpl, "getPriorityArrayName", GetPriorityArrayName); Nan::SetPrototypeMethod(tpl, "GetSizeArrayName", GetSizeArrayName); Nan::SetPrototypeMethod(tpl, "getSizeArrayName", GetSizeArrayName); Nan::SetPrototypeMethod(tpl, "GetTargetLabelCount", GetTargetLabelCount); Nan::SetPrototypeMethod(tpl, "getTargetLabelCount", GetTargetLabelCount); Nan::SetPrototypeMethod(tpl, "GetTextProperty", GetTextProperty); Nan::SetPrototypeMethod(tpl, "getTextProperty", GetTextProperty); Nan::SetPrototypeMethod(tpl, "GetUseUnicodeStrings", GetUseUnicodeStrings); Nan::SetPrototypeMethod(tpl, "getUseUnicodeStrings", GetUseUnicodeStrings); Nan::SetPrototypeMethod(tpl, "IsA", IsA); Nan::SetPrototypeMethod(tpl, "isA", IsA); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "SetBoundedSizeArrayName", SetBoundedSizeArrayName); Nan::SetPrototypeMethod(tpl, "setBoundedSizeArrayName", SetBoundedSizeArrayName); Nan::SetPrototypeMethod(tpl, "SetIconIndexArrayName", SetIconIndexArrayName); Nan::SetPrototypeMethod(tpl, "setIconIndexArrayName", SetIconIndexArrayName); Nan::SetPrototypeMethod(tpl, "SetLabelArrayName", SetLabelArrayName); Nan::SetPrototypeMethod(tpl, "setLabelArrayName", SetLabelArrayName); Nan::SetPrototypeMethod(tpl, "SetMaximumDepth", SetMaximumDepth); Nan::SetPrototypeMethod(tpl, "setMaximumDepth", SetMaximumDepth); Nan::SetPrototypeMethod(tpl, "SetOrientationArrayName", SetOrientationArrayName); Nan::SetPrototypeMethod(tpl, "setOrientationArrayName", SetOrientationArrayName); Nan::SetPrototypeMethod(tpl, "SetPriorityArrayName", SetPriorityArrayName); Nan::SetPrototypeMethod(tpl, "setPriorityArrayName", SetPriorityArrayName); Nan::SetPrototypeMethod(tpl, "SetSizeArrayName", SetSizeArrayName); Nan::SetPrototypeMethod(tpl, "setSizeArrayName", SetSizeArrayName); Nan::SetPrototypeMethod(tpl, "SetTargetLabelCount", SetTargetLabelCount); Nan::SetPrototypeMethod(tpl, "setTargetLabelCount", SetTargetLabelCount); Nan::SetPrototypeMethod(tpl, "SetTextProperty", SetTextProperty); Nan::SetPrototypeMethod(tpl, "setTextProperty", SetTextProperty); Nan::SetPrototypeMethod(tpl, "SetUseUnicodeStrings", SetUseUnicodeStrings); Nan::SetPrototypeMethod(tpl, "setUseUnicodeStrings", SetUseUnicodeStrings); Nan::SetPrototypeMethod(tpl, "UseUnicodeStringsOff", UseUnicodeStringsOff); Nan::SetPrototypeMethod(tpl, "useUnicodeStringsOff", UseUnicodeStringsOff); Nan::SetPrototypeMethod(tpl, "UseUnicodeStringsOn", UseUnicodeStringsOn); Nan::SetPrototypeMethod(tpl, "useUnicodeStringsOn", UseUnicodeStringsOn); #ifdef VTK_NODE_PLUS_VTKPOINTSETTOLABELHIERARCHYWRAP_INITPTPL VTK_NODE_PLUS_VTKPOINTSETTOLABELHIERARCHYWRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkPointSetToLabelHierarchyWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { vtkSmartPointer<vtkPointSetToLabelHierarchy> native = vtkSmartPointer<vtkPointSetToLabelHierarchy>::New(); VtkPointSetToLabelHierarchyWrap* obj = new VtkPointSetToLabelHierarchyWrap(native); obj->Wrap(info.This()); } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkPointSetToLabelHierarchyWrap::GetBoundedSizeArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder()); vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetBoundedSizeArrayName(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkPointSetToLabelHierarchyWrap::GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder()); vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetClassName(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkPointSetToLabelHierarchyWrap::GetIconIndexArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder()); vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetIconIndexArrayName(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkPointSetToLabelHierarchyWrap::GetLabelArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder()); vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetLabelArrayName(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkPointSetToLabelHierarchyWrap::GetMaximumDepth(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder()); vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetMaximumDepth(); info.GetReturnValue().Set(Nan::New(r)); } void VtkPointSetToLabelHierarchyWrap::GetOrientationArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder()); vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetOrientationArrayName(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkPointSetToLabelHierarchyWrap::GetPriorityArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder()); vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetPriorityArrayName(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkPointSetToLabelHierarchyWrap::GetSizeArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder()); vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetSizeArrayName(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkPointSetToLabelHierarchyWrap::GetTargetLabelCount(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder()); vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetTargetLabelCount(); info.GetReturnValue().Set(Nan::New(r)); } void VtkPointSetToLabelHierarchyWrap::GetTextProperty(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder()); vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer(); vtkTextProperty * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetTextProperty(); VtkTextPropertyWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkTextPropertyWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkTextPropertyWrap *w = new VtkTextPropertyWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkPointSetToLabelHierarchyWrap::GetUseUnicodeStrings(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder()); vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer(); bool r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetUseUnicodeStrings(); info.GetReturnValue().Set(Nan::New(r)); } void VtkPointSetToLabelHierarchyWrap::IsA(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder()); vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); int r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->IsA( *a0 ); info.GetReturnValue().Set(Nan::New(r)); return; } Nan::ThrowError("Parameter mismatch"); } void VtkPointSetToLabelHierarchyWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder()); vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer(); vtkPointSetToLabelHierarchy * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkPointSetToLabelHierarchyWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkPointSetToLabelHierarchyWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkPointSetToLabelHierarchyWrap *w = new VtkPointSetToLabelHierarchyWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkPointSetToLabelHierarchyWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder()); vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectWrap::ptpl))->HasInstance(info[0])) { VtkObjectWrap *a0 = ObjectWrap::Unwrap<VtkObjectWrap>(info[0]->ToObject()); vtkPointSetToLabelHierarchy * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObject *) a0->native.GetPointer() ); VtkPointSetToLabelHierarchyWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkPointSetToLabelHierarchyWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkPointSetToLabelHierarchyWrap *w = new VtkPointSetToLabelHierarchyWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } Nan::ThrowError("Parameter mismatch"); } void VtkPointSetToLabelHierarchyWrap::SetBoundedSizeArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder()); vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetBoundedSizeArrayName( *a0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkPointSetToLabelHierarchyWrap::SetIconIndexArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder()); vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetIconIndexArrayName( *a0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkPointSetToLabelHierarchyWrap::SetLabelArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder()); vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetLabelArrayName( *a0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkPointSetToLabelHierarchyWrap::SetMaximumDepth(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder()); vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetMaximumDepth( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkPointSetToLabelHierarchyWrap::SetOrientationArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder()); vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetOrientationArrayName( *a0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkPointSetToLabelHierarchyWrap::SetPriorityArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder()); vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetPriorityArrayName( *a0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkPointSetToLabelHierarchyWrap::SetSizeArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder()); vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetSizeArrayName( *a0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkPointSetToLabelHierarchyWrap::SetTargetLabelCount(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder()); vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetTargetLabelCount( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkPointSetToLabelHierarchyWrap::SetTextProperty(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder()); vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkTextPropertyWrap::ptpl))->HasInstance(info[0])) { VtkTextPropertyWrap *a0 = ObjectWrap::Unwrap<VtkTextPropertyWrap>(info[0]->ToObject()); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetTextProperty( (vtkTextProperty *) a0->native.GetPointer() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkPointSetToLabelHierarchyWrap::SetUseUnicodeStrings(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder()); vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsBoolean()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetUseUnicodeStrings( info[0]->BooleanValue() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkPointSetToLabelHierarchyWrap::UseUnicodeStringsOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder()); vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->UseUnicodeStringsOff(); } void VtkPointSetToLabelHierarchyWrap::UseUnicodeStringsOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder()); vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->UseUnicodeStringsOn(); }
35.085346
118
0.760694
27d217eea9aaf0535e7c9085b31acbb18bae6d1e
499
cpp
C++
test/stream_buf.cpp
mass/m
acb5f266acf902ec60d194cbbaf7375da8927d4f
[ "MIT" ]
null
null
null
test/stream_buf.cpp
mass/m
acb5f266acf902ec60d194cbbaf7375da8927d4f
[ "MIT" ]
null
null
null
test/stream_buf.cpp
mass/m
acb5f266acf902ec60d194cbbaf7375da8927d4f
[ "MIT" ]
null
null
null
#include "m/stream_buf.hpp" //TODO: Probably use a real testing framework //TODO: Add actual tests int main(int argc, char** argv) { UNUSED(argc); UNUSED(argv); m::stream_buf<char> buf; buf.write("Hello, world"); if (buf.get_read_left() != 12) return EXIT_FAILURE; buf.erase_read(buf.get_read() + 2, 3); if (buf.get_read_view() != "He, world") return EXIT_FAILURE; buf.advance_read(9); if (buf.get_read_left() != 0) return EXIT_FAILURE; return EXIT_SUCCESS; }
18.481481
45
0.663327
27d2471f54f504a268038549362c62d3e2f861f2
1,954
cpp
C++
cpp/sololearn/s31_operator_overloading.cpp
bayramcicek/py-repo
e99d8881dd3eb5296ec5dcfba4de2c3418044897
[ "Unlicense" ]
null
null
null
cpp/sololearn/s31_operator_overloading.cpp
bayramcicek/py-repo
e99d8881dd3eb5296ec5dcfba4de2c3418044897
[ "Unlicense" ]
null
null
null
cpp/sololearn/s31_operator_overloading.cpp
bayramcicek/py-repo
e99d8881dd3eb5296ec5dcfba4de2c3418044897
[ "Unlicense" ]
null
null
null
// C11 standard // created by cicek on Feb 05, 2021 8:29 PM #include <iostream> #include <string> using namespace std; // Our class has two constructors and one member variable. class MyClass { public: int var; MyClass() {} MyClass(int a) : var(a) {} /* * Overloaded operators are functions, defined by the keyword operator followed by the * symbol for the operator being defined. An overloaded operator is similar to other functions in that it has a return type and a parameter list. In our example we will be overloading the + operator. It will return an object of our class and take an object of our class as its parameter. */ MyClass operator+(MyClass &obj) { // Now, we need to define what the function does. MyClass res; res.var = this->var + obj.var; return res; } /* * Here, we declared a new res object. We then assigned the sum of the member variables * of the current object (this) and the parameter object (obj) to the res object's var member variable. * The res object is returned as the result. This gives us the ability to create objects in main and use the overloaded + operator to add them together. */ // Which choice is the keyword for overloading an operator in C++?: operator }; int main(int argc, char **argv) { /* * Most of the C++ built-in operators can be redefined or overloaded. Thus, operators can be used with user-defined types as well (for example, allowing you to add two objects together). */ // Operators that can't be overloaded include :: | .* | . | ?: MyClass abc(2); cout << abc.var; // 2 MyClass obj1(12), obj2(54); MyClass res = obj1 + obj2; /* * With overloaded operators, you can use any custom logic needed. * However, it's not possible to alter the operators' precedence, grouping, or number of operands. */ return 0; }
29.164179
116
0.66172
27d526834319a6235abb936f009d3d0696ae33c9
34
cpp
C++
src/MinoGame/ApplicationBuilder.cpp
Nicowcow/Minotaur
74689a1a76b0577138009acc5f8cd37db7bd7630
[ "MIT" ]
5
2017-07-09T08:24:24.000Z
2021-01-11T21:32:39.000Z
src/MinoGame/ApplicationBuilder.cpp
Nicowcow/Minotaur
74689a1a76b0577138009acc5f8cd37db7bd7630
[ "MIT" ]
1
2018-03-06T18:55:13.000Z
2018-12-21T14:20:23.000Z
src/MinoGame/ApplicationBuilder.cpp
Nicowcow/Minotaur
74689a1a76b0577138009acc5f8cd37db7bd7630
[ "MIT" ]
1
2019-01-24T09:32:04.000Z
2019-01-24T09:32:04.000Z
namespace MinoGame { }
2.428571
20
0.5
27d656ebf42a31c2e9669cadc2b6e55b39061a23
645
cpp
C++
src/format.cpp
madhumaheswar/linux-system-monitor
ab5f252bdf32dca22a6a345f5a693ba8fb1a33b6
[ "MIT" ]
1
2020-08-07T04:56:40.000Z
2020-08-07T04:56:40.000Z
src/format.cpp
madhumaheswar/linux-system-monitor
ab5f252bdf32dca22a6a345f5a693ba8fb1a33b6
[ "MIT" ]
null
null
null
src/format.cpp
madhumaheswar/linux-system-monitor
ab5f252bdf32dca22a6a345f5a693ba8fb1a33b6
[ "MIT" ]
null
null
null
#include <iomanip> #include <sstream> #include <string> #include "format.h" // INPUT: Long int measuring seconds // OUTPUT: HHHH:MM:SS std::string Format::ElapsedTime(long seconds) { int HH; int MM; int SS; MM = seconds / 60; SS = seconds % 60; HH = MM / 60; MM = MM % 60; // To format to HHHH:MM:SS std::ostringstream formattedTime; formattedTime << std::setfill('0') << std::setw(4) << std::to_string(HH) << ":" << std::setfill('0') << std::setw(2) << std::to_string(MM) << ":" << std::setfill('0') << std::setw(2) << std::to_string(SS); return formattedTime.str(); }
23.035714
74
0.564341
27d975962cf6301c44ffaf27390159f286a0a5b9
2,891
hpp
C++
libs/Aether/include/Aether/primary/Text.hpp
tkgstrator/SeedHack
227566d993bdea7a2851a8fc664b539186509697
[ "MIT" ]
1
2021-02-04T07:27:46.000Z
2021-02-04T07:27:46.000Z
libs/Aether/include/Aether/primary/Text.hpp
tkgstrator/SeedHack
227566d993bdea7a2851a8fc664b539186509697
[ "MIT" ]
null
null
null
libs/Aether/include/Aether/primary/Text.hpp
tkgstrator/SeedHack
227566d993bdea7a2851a8fc664b539186509697
[ "MIT" ]
null
null
null
#ifndef AETHER_TEXT_HPP #define AETHER_TEXT_HPP #include "Aether/base/BaseText.hpp" namespace Aether { /** * @brief Text extends BaseText by implementing scrolling when the text overflows. * * It's for single-line text. */ class Text : public BaseText { private: /** @brief Indicator on whether the text is scrollable */ bool scroll_; /** @brief Pixels to scroll per second */ int scrollSpeed_; /** @brief Time since scroll finished (in ms) (only used internally) */ int scrollPauseTime; /** @brief Generate a text surface */ void generateSurface(); public: /** * @brief Construct a new Text object * * @param x x-coordinate of start position offset * @param y y-coordinate of start position offset * @param s text string * @param f font size * @param l font style * @param t \ref ::RenderType to use for texture generation */ Text(int x, int y, std::string s, unsigned int f, FontStyle l = FontStyle::Regular, RenderType t = RenderType::OnCreate); /** * @brief Indicator on whether the text is scrollable * * @return true if it is scrollable * @return false otherwise */ bool scroll(); /** * @brief Set whether the text is scrollable * * @param s true if text is scrollable, false otherwise */ void setScroll(bool s); /** * @brief Get the scroll speed for text * * @return scroll speed for text */ int scrollSpeed(); /** * @brief Set the scroll speed for text * * @param s new scroll speed for text */ void setScrollSpeed(int s); /** * @brief Set the font size for the text * * @param f new font size */ void setFontSize(unsigned int f); /** * @brief Set text * * @param s new text to set */ void setString(std::string s); /** * @brief Updates the text. * * Update handles animating the scroll if necessary. * * @param dt change in time */ void update(uint32_t dt); /** * @brief Adjusts the text width. * * Adjusting width may need to adjust amount of text shown. * * @param w new width */ void setW(int w); }; }; #endif
29.20202
133
0.471117
27d9b546990c5c710f165f13626d9aab24f02301
1,020
cpp
C++
CTN_05_Hardware_3D_DirectX/src/PixelShader.cpp
TheUnicum/CTN_05_Hardware_3D_DirectX
39940fb0466ff5b419d7f7c4cf55ee1f90784baa
[ "Apache-2.0" ]
null
null
null
CTN_05_Hardware_3D_DirectX/src/PixelShader.cpp
TheUnicum/CTN_05_Hardware_3D_DirectX
39940fb0466ff5b419d7f7c4cf55ee1f90784baa
[ "Apache-2.0" ]
null
null
null
CTN_05_Hardware_3D_DirectX/src/PixelShader.cpp
TheUnicum/CTN_05_Hardware_3D_DirectX
39940fb0466ff5b419d7f7c4cf55ee1f90784baa
[ "Apache-2.0" ]
null
null
null
#include "PixelShader.h" #include "GraphicsThrowMacros.h" #include "BindableCodex.h" #include "ChiliUtil.h" namespace Bind { PixelShader::PixelShader(Graphics& gfx, const std::string& path) : path(path) { INFOMAN(gfx); Microsoft::WRL::ComPtr<ID3DBlob> pBlob; GFX_THROW_INFO(D3DReadFileToBlob(ToWide(path).c_str(), &pBlob)); GFX_THROW_INFO(GetDevice(gfx)->CreatePixelShader(pBlob->GetBufferPointer(), pBlob->GetBufferSize(), nullptr, &pPixelShader)); } void PixelShader::Bind(Graphics& gfx) noxnd { INFOMAN_NOHR(gfx); GFX_THROW_INFO_ONLY(GetContext(gfx)->PSSetShader(pPixelShader.Get(), nullptr, 0u)); } std::shared_ptr<PixelShader> PixelShader::Resolve(Graphics& gfx, const std::string& path) { return Codex::Resolve<PixelShader>(gfx, path); } std::string PixelShader::GenerateUID(const std::string& path) { using namespace std::string_literals; return typeid(PixelShader).name() + "#"s + path; } std::string PixelShader::GetUID() const noexcept { return GenerateUID(path); } }
26.842105
127
0.731373
27dc65478aacdac1d26b33fa008c55c454198a04
5,526
cpp
C++
src/binaryServer/CachedConverterCallback.cpp
peramic/OPC-UA.Server
ebfafb0f9a1943fc1f2d44f20a0497a59e5bfd97
[ "Apache-2.0" ]
null
null
null
src/binaryServer/CachedConverterCallback.cpp
peramic/OPC-UA.Server
ebfafb0f9a1943fc1f2d44f20a0497a59e5bfd97
[ "Apache-2.0" ]
null
null
null
src/binaryServer/CachedConverterCallback.cpp
peramic/OPC-UA.Server
ebfafb0f9a1943fc1f2d44f20a0497a59e5bfd97
[ "Apache-2.0" ]
null
null
null
#include "CachedConverterCallback.h" #include <common/Exception.h> #include <common/Mutex.h> #include <common/MutexLock.h> #include <common/ScopeGuard.h> #include <common/logging/Logger.h> #include <common/logging/LoggerFactory.h> #include <sasModelProvider/base/ConversionException.h> #include <uadatetime.h> #include <sstream> // std::ostringstream namespace SASModelProviderNamespace { using namespace CommonNamespace; class CachedConverterCallbackPrivate { friend class CachedConverterCallback; private: Logger* log; ConverterUa2IO::ConverterCallback* callback; bool hasValuesAttached; Mutex* mutex; // type -> super types std::map<UaNodeId, std::vector<UaNodeId>*> superTypes; std::map<UaNodeId, UaStructureDefinition> structureDefinitions; }; CachedConverterCallback::CachedConverterCallback(ConverterUa2IO::ConverterCallback& callback, bool attachValue) /* throws MutexException */ { d = new CachedConverterCallbackPrivate(); d->log = LoggerFactory::getLogger("CachedConverterCallback"); d->callback = &callback; d->hasValuesAttached = attachValue; d->mutex = new Mutex(); // MutexException } CachedConverterCallback::~CachedConverterCallback() { clear(); if (d->hasValuesAttached) { delete d->callback; } delete d->mutex; delete d; } void CachedConverterCallback::clear() { MutexLock lock(*d->mutex); for (std::map<UaNodeId, std::vector<UaNodeId>*>::const_iterator it = d->superTypes.begin(); it != d->superTypes.end(); it++) { delete it->second; } d->superTypes.clear(); d->structureDefinitions.clear(); } void CachedConverterCallback::preload(const UaNodeId& typeId) { if (0 == typeId.namespaceIndex()) { return; } // get base type UaNodeId buildInDataTypeId; std::vector<UaNodeId>* superTypes = getSuperTypes(typeId); if (superTypes != NULL) { ScopeGuard<std::vector<UaNodeId> > superTypesSG(superTypes); if (superTypes->size() > 0) { buildInDataTypeId = superTypes->back(); } } if (buildInDataTypeId.isNull()) { std::ostringstream msg; msg << "Cannot get base type of " << typeId.toXmlString().toUtf8(); throw ExceptionDef(ConversionException, msg.str()); } switch (buildInDataTypeId.identifierNumeric()) { case OpcUaId_Structure: // 22 case OpcUaId_Union: // 12756 { UaStructureDefinition sd = getStructureDefinition(typeId); if (!sd.isNull()) { // for each field for (int i = 0; i < sd.childrenCount(); i++) { preload(sd.child(i).typeId()); } } else { std::ostringstream msg; msg << "Cannot get structure definition of " << typeId.toXmlString().toUtf8(); throw ExceptionDef(ConversionException, msg.str()); } break; } default: break; } } UaStructureDefinition CachedConverterCallback::getStructureDefinition(const UaNodeId& typeId) /* throws ConversionException */ { MutexLock lock(*d->mutex); std::map<UaNodeId, UaStructureDefinition>::const_iterator it = d->structureDefinitions.find(typeId); if (it == d->structureDefinitions.end()) { if (d->log->isDebugEnabled()) { d->log->debug("Getting structure definition of %s", typeId.toXmlString().toUtf8()); } UaStructureDefinition sd = d->callback->getStructureDefinition(typeId); if (!sd.isNull()) { d->structureDefinitions[typeId] = sd; if (d->log->isDebugEnabled()) { d->log->debug("Get structure definition"); } return sd; } std::ostringstream msg; msg << "Cannot get structure definition of " << typeId.toXmlString().toUtf8(); throw ExceptionDef(ConversionException, msg.str()); } return it->second; } std::vector<UaNodeId>* CachedConverterCallback::getSuperTypes(const UaNodeId& typeId) /* throws ConversionException */ { MutexLock lock(*d->mutex); std::map<UaNodeId, std::vector<UaNodeId>*>::const_iterator it = d->superTypes.find(typeId); if (it == d->superTypes.end()) { if (d->log->isDebugEnabled()) { d->log->debug("Getting super types of %s", typeId.toXmlString().toUtf8()); } std::vector<UaNodeId>* superTypeIds = d->callback->getSuperTypes(typeId); if (superTypeIds != NULL) { d->superTypes[typeId] = superTypeIds; if (d->log->isDebugEnabled()) { d->log->debug("Get %d super types", superTypeIds->size()); } return new std::vector<UaNodeId>(*superTypeIds); } std::ostringstream msg; msg << "Cannot get super types of " << typeId.toXmlString().toUtf8(); throw ExceptionDef(ConversionException, msg.str()); } return new std::vector<UaNodeId>(*it->second); } }
38.643357
99
0.570575
27e252a5da99b05ecfa26445abd8b1f44f37d85a
722
cpp
C++
code/415.addStrings.cpp
T1mzhou/LeetCode
574540d30f5696e55799831dc3c8d8b7246b74f1
[ "MIT" ]
1
2020-10-04T13:39:34.000Z
2020-10-04T13:39:34.000Z
code/415.addStrings.cpp
T1mzhou/LeetCode
574540d30f5696e55799831dc3c8d8b7246b74f1
[ "MIT" ]
null
null
null
code/415.addStrings.cpp
T1mzhou/LeetCode
574540d30f5696e55799831dc3c8d8b7246b74f1
[ "MIT" ]
null
null
null
class Solution { public: vector<int> add(vector<int>& A, vector<int>& B) { vector<int> C; for (int i = 0, t = 0; i < A.size() || i < B.size() || t; i++) { if (i < A.size()) t += A[i]; if (i < B.size()) t += B[i]; C.push_back(t % 10); t /= 10; } return C; } string addStrings(string num1, string num2) { vector<int> A, B; for (int i = num1.size() - 1; i >= 0; i--) A.push_back(num1[i] - '0'); for (int i = num2.size() - 1; i >= 0; i--) B.push_back(num2[i] - '0'); auto C = add(A, B); string c; for (int i = C.size() - 1; i >= 0; i--) c += to_string(C[i]); return c; } };
31.391304
78
0.414127
27e699cf3d090e1f05b7311a45fa803498de7c0d
15,892
cpp
C++
Base/PLGui/src/Widgets/Controls/Label.cpp
naetherm/PixelLight
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
1
2019-11-09T16:54:04.000Z
2019-11-09T16:54:04.000Z
Base/PLGui/src/Widgets/Controls/Label.cpp
naetherm/pixelligh
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
27
2019-06-18T06:46:07.000Z
2020-02-02T11:11:28.000Z
Base/PLGui/src/Widgets/Controls/Label.cpp
naetherm/PixelLight
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
null
null
null
/*********************************************************\ * File: Label.cpp * * * Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/) * * This file is part of PixelLight. * * 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. \*********************************************************/ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include <PLCore/String/RegEx.h> #include "PLGui/Gui/Resources/Graphics.h" #include "PLGui/Gui/Gui.h" #include "PLGui/Themes/Theme.h" #include "PLGui/Widgets/Controls/Label.h" //[-------------------------------------------------------] //[ Public definitions ] //[-------------------------------------------------------] static const int GAP = 8; // Gap between two words //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] using namespace PLCore; using namespace PLMath; using namespace PLGraphics; namespace PLGui { //[-------------------------------------------------------] //[ Class implementation ] //[-------------------------------------------------------] pl_class_metadata(Label, "PLGui", PLGui::Widget, "Widget that displays a static text") // Constructors pl_constructor_0_metadata(DefaultConstructor, "Default constructor", "") // Attributes pl_attribute_metadata(Color, PLGraphics::Color4, PLGraphics::Color4::Black, ReadWrite, "Text color", "") pl_attribute_metadata(Align, pl_enum_type(EAlign), AlignLeft, ReadWrite, "Text alignment (horizontal)", "") pl_attribute_metadata(VAlign, pl_enum_type(EVAlign), AlignMiddle, ReadWrite, "Text alignment (vertical)", "") pl_attribute_metadata(Wrap, pl_enum_type(ETextWrap), TextWrap, ReadWrite, "Text wrapping", "") pl_attribute_metadata(Style, pl_flag_type(ETextStyle), 0, ReadWrite, "Text style", "") pl_attribute_metadata(Text, PLCore::String, "", ReadWrite, "Text label", "") pl_class_metadata_end(Label) //[-------------------------------------------------------] //[ Public functions ] //[-------------------------------------------------------] /** * @brief * Constructor */ Label::Label(Widget *pParent) : Widget(pParent), Color(this), Align(this), VAlign(this), Wrap(this), Style(this), Text(this), m_cColor(Color4::Black), m_nAlign(AlignLeft), m_nVAlign(AlignMiddle), m_nWrap(TextWrap), m_nStyle(0), m_cFont(*GetGui()) { // Get default font m_cFont = GetGui()->GetTheme()->GetDefaultFont(); // Don't accept keyboard focus SetFocusStyle(NoFocus); } /** * @brief * Destructor */ Label::~Label() { } /** * @brief * Get font */ const Font &Label::GetFont() const { // Return font return m_cFont; } /** * @brief * Set font */ void Label::SetFont(const Font &cFont) { // Set font m_cFont = cFont; // Update widget UpdateContent(); // Redraw Redraw(); } /** * @brief * Get color */ Color4 Label::GetColor() const { // Return color return m_cColor; } /** * @brief * Set color */ void Label::SetColor(const Color4 &cColor) { // Set color m_cColor = cColor; // Update widget UpdateContent(); // Redraw Redraw(); } /** * @brief * Get horizontal alignment */ EAlign Label::GetAlign() const { // Return alignment return m_nAlign; } /** * @brief * Set horizontal alignment */ void Label::SetAlign(EAlign nAlign) { // Set alignment m_nAlign = nAlign; // Update widget UpdateContent(); // Redraw Redraw(); } /** * @brief * Get vertical alignment */ EVAlign Label::GetVAlign() const { // Return alignment return m_nVAlign; } /** * @brief * Set vertical alignment */ void Label::SetVAlign(EVAlign nAlign) { // Set alignment m_nVAlign = nAlign; // Update widget UpdateContent(); // Redraw Redraw(); } /** * @brief * Get text wrapping */ ETextWrap Label::GetWrap() const { // Return wrapping return m_nWrap; } /** * @brief * Set text wrapping */ void Label::SetWrap(ETextWrap nWrap) { // Set wrapping m_nWrap = nWrap; // Update widget UpdateContent(); // Redraw Redraw(); } /** * @brief * Get text style */ uint32 Label::GetStyle() const { // Return style return m_nStyle; } /** * @brief * Set text style */ void Label::SetStyle(uint32 nStyle) { // Set style m_nStyle = nStyle; // Update widget UpdateContent(); // Redraw Redraw(); } /** * @brief * Get text */ String Label::GetText() const { // Return text return m_sText; } /** * @brief * Set text */ void Label::SetText(const String &sText) { // Set text m_sText = sText; // Update widget UpdateContent(); // Redraw Redraw(); } //[-------------------------------------------------------] //[ Protected virtual WidgetFunctions functions ] //[-------------------------------------------------------] PLMath::Vector2i Label::OnPreferredSize(const Vector2i &vRefSize) const { // Call base function Widget::OnPreferredSize(vRefSize); // Try to calculate the size in Y direction. If X is already known, we can use the actual line width // to calculate the height, otherwise we use a virtually endless line and therefore calculate only // hard-coded line feeds. // Create an offscreen graphics object Graphics cGraphics(*GetGui()); // Get font Font cFont = GetFont(); // Get underline mode int nUnderline = 0; if (GetStyle() & UnderlineText) { nUnderline = 2; } // First of all: Is there any text? String sText = GetText(); if (sText.GetLength()) { // Get text width and height uint32 nTextWidth = cGraphics.GetTextWidth (cFont, sText); uint32 nTextHeight = cGraphics.GetTextHeight(cFont, sText); // Get line with int nLineWidth = vRefSize.x; // Check if text has to be wrapped bool bHasNewLines = (sText.IndexOf('\r') > -1) || (sText.IndexOf('\n') > -1); if (GetWrap() == NoTextWrap || (nLineWidth > -1 && static_cast<int>(nTextWidth) < nLineWidth && !bHasNewLines) ) { // No wrapping Vector2i vPreferredSize; vPreferredSize.x = (vRefSize.x > -1 ? vRefSize.x : nTextWidth); vPreferredSize.y = nTextHeight + nUnderline; return vPreferredSize; } else { // With text wrapping int nGap = GAP; // Gap between two words // Get words and mark newlines RegEx cRegEx("([\\r\\n])|([\\s]*([\\S]+))"); Array<String> lstWords; uint32 nParsePos = 0; uint32 nLine = 0; uint32 nNumLines = 0; while (cRegEx.Match(sText, nParsePos)) { // Get next word nParsePos = cRegEx.GetPosition(); String sWord = cRegEx.GetResult(0); if (sWord.GetLength() > 0) sWord = '\n'; else sWord = cRegEx.GetResult(2); int nWidth = cGraphics.GetTextWidth(cFont, sWord); // Add word to line if ((sWord != '\n') && (static_cast<int>(nLine+nWidth) <= nLineWidth || nLineWidth <= -1 || nLine == 0)) { // Add word lstWords.Add(sWord); nLine += nWidth + nGap; } else { // Add line wrap lstWords.Add('\n'); nLine = 0; nNumLines++; // Add first word of next line if (sWord != '\n') { lstWords.Add(sWord); nLine = nWidth + nGap; } } } // Add '\n' after last line String sLastWord = lstWords.Get(lstWords.GetNumOfElements()-1); if (sLastWord.GetLength() && sLastWord != '\n') { lstWords.Add('\n'); nNumLines++; } // Set start position (Y) Vector2i vPos(0, 0); // Calculate lines int nMaxLineWidth = -1; uint32 nFirst = 0; while (nFirst < lstWords.GetNumOfElements()) { // Get end of line ('\n') uint32 nLast; for (nLast=nFirst; nLast<lstWords.GetNumOfElements(); nLast++) { if (lstWords[nLast] == '\n') break; } // Get number of words in this line uint32 nWords = nLast - nFirst; if (nWords > 0) { // Get width of line uint32 nWidth = 0; for (uint32 i=nFirst; i<nLast; i++) { if (nWidth > 0 && GetWrap() != TextWrapBlock) nWidth += nGap; nWidth += cGraphics.GetTextWidth(cFont, lstWords[i]); } // Set start position (X) vPos.x = 0; if (GetWrap() == TextWrapBlock) { // Calculate size of gaps between words for block-text if (nLineWidth > -1) nGap = (nLineWidth - nWidth) / (nWords>1 ? nWords-1 : 1); else nGap = GAP; if (nWords > 1) nWidth += (nWords-1) * nGap; } else { // No block text, use static gaps and align text by alignment options nGap = GAP; if (nLineWidth > -1) { if (GetAlign() == AlignCenter) vPos.x = nLineWidth/2 - nWidth/2; // Center else if (GetAlign() == AlignRight) vPos.x = nLineWidth - nWidth; // Right } } Vector2i vStartPos = vPos; // Calculate line for (uint32 i=nFirst; i<nLast; i++) { // Get word String sWord = lstWords[i]; // Next word vPos.x += cGraphics.GetTextWidth(cFont, sWord) + nGap; } // Save width of widest line if (static_cast<int>(nWidth) > nMaxLineWidth) nMaxLineWidth = nWidth; } // Next line nFirst = nLast + 1; vPos.y += nTextHeight; } // Return vertical size Vector2i vPreferredSize; vPreferredSize.x = (vRefSize.x > -1 ? vRefSize.x : nMaxLineWidth); vPreferredSize.y = vPos.y + nUnderline; return vPreferredSize; } } // Use something like a standard text height uint32 nTextHeight = cGraphics.GetTextHeight(cFont, "Text"); return Vector2i(-1, nTextHeight + nUnderline); } void Label::OnDraw(Graphics &cGraphics) { // Call base implementation Widget::OnDraw(cGraphics); // First of all: Is there any text? String sText = GetText(); if (sText.GetLength()) { // Get font Font cFont = GetFont(); // Get text color Color4 cColor = IsEnabled() ? GetColor() : Color4::Gray; // Get text width and height uint32 nTextWidth = cGraphics.GetTextWidth (cFont, sText); uint32 nTextHeight = cGraphics.GetTextHeight(cFont, sText); // Get line with int nLineWidth = GetSize().x; // Check if text has to be wrapped bool bHasNewLines = (sText.IndexOf('\r') > -1) || (sText.IndexOf('\n') > -1); if (GetWrap() == NoTextWrap || (static_cast<int>(nTextWidth) < nLineWidth && !bHasNewLines) ) { // No wrapping // Align text (horizontally) uint32 nX = 0; if (GetAlign() == AlignCenter) nX = GetSize().x/2 - nTextWidth/2; // Center else if (GetAlign() == AlignRight) nX = GetSize().x - nTextWidth; // Right // Align text (vertically) uint32 nY = 0; if (GetVAlign() == AlignBottom) nY = GetSize().y - nTextHeight; // Bottom else if (GetVAlign() == AlignMiddle) nY = GetSize().y/2 - nTextHeight/2; // Middle // Draw text cGraphics.DrawText(cFont, cColor, Color4::Transparent, Vector2i(nX, nY), sText); // Draw underline if (GetStyle() & UnderlineText) cGraphics.DrawLine(cColor, Vector2i(nX, nY + nTextHeight), Vector2i(nX + nTextWidth, nY + nTextHeight)); // Draw cross-out if (GetStyle() & CrossoutText) cGraphics.DrawLine(cColor, Vector2i(nX, nY + nTextHeight/2), Vector2i(nX + nTextWidth, nY + nTextHeight/2)); } else { // Draw with text wrapping int nGap = GAP; // Gap between two words // Get words and mark newlines RegEx cRegEx("([\\r\\n])|([\\s]*([\\S]+))"); Array<String> lstWords; uint32 nParsePos = 0; uint32 nLine = 0; uint32 nNumLines = 0; while (cRegEx.Match(sText, nParsePos)) { // Get next word nParsePos = cRegEx.GetPosition(); String sWord = cRegEx.GetResult(0); if (sWord.GetLength() > 0) sWord = '\n'; else sWord = cRegEx.GetResult(2); int nWidth = cGraphics.GetTextWidth(cFont, sWord); // Add word to line if ((sWord != '\n') && (static_cast<int>(nLine+nWidth) <= nLineWidth || nLine == 0)) { // Add word lstWords.Add(sWord); nLine += nWidth + nGap; } else { // Add line wrap lstWords.Add('\n'); nLine = 0; nNumLines++; // Add first word of next line if (sWord != '\n') { lstWords.Add(sWord); nLine = nWidth + nGap; } } } // Add '\n' after last line String sLastWord = lstWords.Get(lstWords.GetNumOfElements()-1); if (sLastWord.GetLength() && sLastWord != '\n') { lstWords.Add('\n'); nNumLines++; } // Set start position (Y) Vector2i vPos(0, 0); if (GetVAlign() == AlignBottom) vPos.y = GetSize().y - (nTextHeight*nNumLines); // Bottom else if (GetVAlign() == AlignMiddle) vPos.y = GetSize().y/2 - (nTextHeight*nNumLines)/2; // Middle // Print lines uint32 nFirst = 0; while (nFirst < lstWords.GetNumOfElements()) { // Get end of line ('\n') uint32 nLast; for (nLast=nFirst; nLast<lstWords.GetNumOfElements(); nLast++) { if (lstWords[nLast] == '\n') break; } // Get number of words in this line uint32 nWords = nLast - nFirst; if (nWords > 0) { // Get width of line uint32 nWidth = 0; for (uint32 i=nFirst; i<nLast; i++) { if (nWidth > 0 && GetWrap() != TextWrapBlock) nWidth += nGap; nWidth += cGraphics.GetTextWidth(cFont, lstWords[i]); } // Set start position (X) vPos.x = 0; if (GetWrap() == TextWrapBlock) { // Calculate size of gaps between words for block-text nGap = (GetSize().x - nWidth) / (nWords>1 ? nWords-1 : 1); if (nWords > 1) nWidth += (nWords-1) * nGap; } else { // No block text, use static gaps and align text by alignment options nGap = GAP; if (GetAlign() == AlignCenter) vPos.x = nLineWidth/2 - nWidth/2; // Center else if (GetAlign() == AlignRight) vPos.x = nLineWidth - nWidth; // Right } Vector2i vStartPos = vPos; // Print line for (uint32 i=nFirst; i<nLast; i++) { // Get word String sWord = lstWords[i]; // Draw word cGraphics.DrawText(cFont, cColor, Color4::Transparent, vPos, sWord); // Next word vPos.x += cGraphics.GetTextWidth(cFont, sWord) + nGap; } // Draw underline if (GetStyle() & UnderlineText) cGraphics.DrawLine(cColor, Vector2i(vStartPos.x, vStartPos.y+nTextHeight), Vector2i(vStartPos.x+nWidth, vStartPos.y+nTextHeight)); // Draw cross-out if (GetStyle() & CrossoutText) cGraphics.DrawLine(cColor, Vector2i(vStartPos.x, vStartPos.y+nTextHeight/2), Vector2i(vStartPos.x+nWidth, vStartPos.y+nTextHeight/2)); } // Next line nFirst = nLast + 1; vPos.y += nTextHeight; } } } } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // PLGui
26.267769
140
0.586333
27ef3911b12e41cec13c81fd65eda459051308ba
6,818
cpp
C++
src/autoxtime/db/DbListener.cpp
nmaludy/autoxtime
c4c2603a6990ef3cfddaa1bfab14e48bc81ec2a3
[ "Apache-2.0" ]
null
null
null
src/autoxtime/db/DbListener.cpp
nmaludy/autoxtime
c4c2603a6990ef3cfddaa1bfab14e48bc81ec2a3
[ "Apache-2.0" ]
4
2021-02-23T20:56:42.000Z
2021-04-03T01:56:08.000Z
src/autoxtime/db/DbListener.cpp
nmaludy/autoxtime
c4c2603a6990ef3cfddaa1bfab14e48bc81ec2a3
[ "Apache-2.0" ]
null
null
null
#include <autoxtime/db/DbListener.h> #include <autoxtime/db/DbConnection.h> #include <autoxtime/log/Log.h> #include <google/protobuf/util/json_util.h> #include <QSemaphore> #include <iostream> AUTOXTIME_DB_NAMESPACE_BEG DbEmitter::DbEmitter(const google::protobuf::Message& prototype) : QObject(), mpPrototype(prototype.New()) {} DbEmitter::~DbEmitter() {} void DbEmitter::emitNotification(const QString& name, QSqlDriver::NotificationSource source, const QVariant& payload) { // Note: as a measure of efficiency we convert and parse the JSON data once // then pass the parsed google::protobuf::Message to the emitted signal // so that we dont' have to parse the message over/over in each listener QByteArray payload_ba = payload.toString().toUtf8(); QJsonDocument payload_doc = QJsonDocument::fromJson(payload_ba); QJsonObject payload_json = payload_doc.object(); // payload contains following fields: // "timestamp" - string // "operation" - string (UPDATE, INSERT, DELETE, etc) // "data" - data/row that was changed, encoded as JSON QString timestamp_str = payload_json.value("timestamp").toString(); QString operation = payload_json.value("operation").toString(); QJsonDocument data_doc(payload_json.value("data").toObject()); // parse ISO 8601 timestamp QDateTime timestamp = QDateTime::fromString(timestamp_str, Qt::ISODate); // convert Qt string to string we can use for parsing QString data_json(data_doc.toJson()); std::string data_str(data_json.toStdString()); google::protobuf::StringPiece piece(data_str.data()); // create a new message that will be filled in with the data from the JSON string std::shared_ptr<google::protobuf::Message> msg(mpPrototype->New()); // parse JSON into the message google::protobuf::util::Status status = google::protobuf::util::JsonStringToMessage(piece, msg.get()); if (status.ok()) { AXT_DEBUG << "DbEmitter - Notification name=" << name << " thread=" << QString("autoxtime::thread_") + QString::number((intptr_t)QThread::currentThreadId()) << " timestamp=" << timestamp << " operation=" << operation << " payload=" << payload_ba << "\n" << " msg=" << msg->DebugString(); emit notification(msg, timestamp, operation); } else { AXT_ERROR << "Error parsing JSON payload error='"<< status.ToString() << "'" << " channel=" << name << " timestamp=" << timestamp << " operation=" << operation << " payload=" << payload; } } //////////////////////////////////////////////////////////////////////////////// DbListener::DbListener() : QThread(), mpStartSemaphore(new QSemaphore()), mpConnection() { qRegisterMetaType<std::shared_ptr<google::protobuf::Message>>(); start(); // avoid race condition on start, wait until we're connected mpStartSemaphore->acquire(1); // move this object to "this" thread so that signals cross the right boundaries moveToThread(this); } DbListener& DbListener::instance() { static DbListener thread; return thread; } void DbListener::run() { AXT_DEBUG << "In DbListener thread" << QString("autoxtime::thread_") + QString::number((intptr_t)QThread::currentThreadId()); { std::unique_lock<std::mutex> lock(mConnectionMutex); mpConnection = std::make_unique<DbConnection>(this); } // hook up our listener before subscribing connect(mpConnection->database().driver(), qOverload<const QString&, QSqlDriver::NotificationSource , const QVariant&>(&QSqlDriver::notification), this, &DbListener::recvNotification); connect(this, &DbListener::subscribeSignal, this, &DbListener::subscribeSlot); // avoid race condition on start, wait until we're connected mpStartSemaphore->release(1); // run our event loop QThread::run(); { AXT_DEBUG << "Stopping DbListener thread" << QString("autoxtime::thread_") + QString::number((intptr_t)QThread::currentThreadId()); // destroy the connection, still in our thread, to avoid warnings about tearing // down the QTimers in another thread std::unique_lock<std::mutex> lock(mConnectionMutex); mpConnection.reset(); } } DbEmitter* DbListener::emitter(const google::protobuf::Message& prototype, const QString& tableName) { std::unique_lock<std::mutex> lock(mEmitterMutex); std::unordered_map<QString, std::unique_ptr<DbEmitter>>::iterator iter = mEmitters.find(tableName); if (iter != mEmitters.end()) { return iter->second.get(); } else { mEmitters[tableName] = std::make_unique<DbEmitter>(prototype); return mEmitters[tableName].get(); } } void DbListener::subscribe(const google::protobuf::Message& prototype, const QString& tableName) { AXT_DEBUG << "subscribe for channel " << tableName << " called from thread: " << QString("autoxtime::thread_") + QString::number((intptr_t)QThread::currentThreadId()); // create an emitter for this subscription, just in case one doesn't exist emitter(prototype, tableName); // send signal to our background thread that we want to subscribe to this new channel emit subscribeSignal(tableName); } void DbListener::subscribeSlot(const QString& channel) { AXT_DEBUG << "subscribeSlot for channel " << channel << " called in thread: " << QString("autoxtime::thread_") + QString::number((intptr_t)QThread::currentThreadId()); std::unique_lock<std::mutex> lock(mConnectionMutex); if (mpConnection) { mpConnection->database().driver()->subscribeToNotification(channel); } } void DbListener::recvNotification(const QString& name, QSqlDriver::NotificationSource source, const QVariant& payload) { std::unique_lock<std::mutex> lock(mEmitterMutex); std::unordered_map<QString, std::unique_ptr<DbEmitter>>::iterator iter = mEmitters.find(name); if (iter != mEmitters.end()) { AXT_DEBUG << "Notification found_emitter=true name=" << name << " thread= " << QString("autoxtime::thread_") + QString::number((intptr_t)QThread::currentThreadId()) << " payload=" << payload.toString(); iter->second->emitNotification(name, source, payload); } else { AXT_DEBUG << "Notification found_emitter=false name=" << name << " thread= " << QString("autoxtime::thread_") + QString::number((intptr_t)QThread::currentThreadId()) << " payload=" << payload.toString(); } emit notification(name, source, payload); } AUTOXTIME_DB_NAMESPACE_END
35.326425
128
0.652977
27f2e20ee83b2678a10d6728ab2b4ca3b15b0503
580
cpp
C++
ports/esp32/src/hSystem.cpp
ygjukim/hFramework
994ea7550c34b4943e2fa2d5e9ca447aa555f39e
[ "MIT" ]
33
2017-07-03T22:49:30.000Z
2022-03-31T19:32:55.000Z
ports/esp32/src/hSystem.cpp
ygjukim/hFramework
994ea7550c34b4943e2fa2d5e9ca447aa555f39e
[ "MIT" ]
6
2017-07-13T13:23:22.000Z
2019-10-25T17:51:28.000Z
ports/esp32/src/hSystem.cpp
ygjukim/hFramework
994ea7550c34b4943e2fa2d5e9ca447aa555f39e
[ "MIT" ]
17
2017-07-01T05:35:47.000Z
2022-03-22T23:33:00.000Z
/** * Copyright (c) 2013-2017 Husarion Sp. z o.o. * Distributed under the MIT license. * For full terms see the file LICENSE.md. */ #include "hSystem.h" #include <cstring> extern "C" { #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_system.h" }; namespace hFramework { uint32_t hSystem::getRandNr() { return (uint32_t)esp_random(); } uint64_t hSystem::getSerialNum() { uint8_t mac[8]; esp_efuse_read_mac(mac); uint64_t id; memcpy(&id, mac, 8); return id; } void hSystem::reset() { system_restart(); } hSystem sys; }
15.675676
46
0.663793
27f85a367dbf23a4e12bc9099bddd1f19dd96cbe
5,936
hpp
C++
sol/function_types_member.hpp
SuperV1234/sol2
76b73bdfab4475933c42e715fd98737a4699794a
[ "MIT" ]
null
null
null
sol/function_types_member.hpp
SuperV1234/sol2
76b73bdfab4475933c42e715fd98737a4699794a
[ "MIT" ]
null
null
null
sol/function_types_member.hpp
SuperV1234/sol2
76b73bdfab4475933c42e715fd98737a4699794a
[ "MIT" ]
1
2021-05-02T15:57:13.000Z
2021-05-02T15:57:13.000Z
// The MIT License (MIT) // Copyright (c) 2013-2016 Rapptz, ThePhD and contributors // 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. #ifndef SOL_FUNCTION_TYPES_MEMBER_HPP #define SOL_FUNCTION_TYPES_MEMBER_HPP #include "function_types_core.hpp" namespace sol { namespace function_detail { template<typename Func> struct free_function : public base_function { typedef meta::unwrapped_t<meta::unqualified_t<Func>> Function; typedef meta::function_return_t<Function> return_type; typedef meta::function_args_t<Function> args_lists; Function fx; template<typename... Args> free_function(Args&&... args): fx(std::forward<Args>(args)...) {} int call(lua_State* L) { return stack::call_into_lua(meta::tuple_types<return_type>(), args_lists(), L, 1, fx); } virtual int operator()(lua_State* L) override { auto f = [&](lua_State* L) -> int { return this->call(L);}; return detail::trampoline(L, f); } }; template<typename Func> struct functor_function : public base_function { typedef meta::unwrapped_t<meta::unqualified_t<Func>> Function; typedef decltype(&Function::operator()) function_type; typedef meta::function_return_t<function_type> return_type; typedef meta::function_args_t<function_type> args_lists; Function fx; template<typename... Args> functor_function(Args&&... args): fx(std::forward<Args>(args)...) {} int call(lua_State* L) { return stack::call_into_lua(meta::tuple_types<return_type>(), args_lists(), L, 1, fx); } virtual int operator()(lua_State* L) override { auto f = [&](lua_State* L) -> int { return this->call(L);}; return detail::trampoline(L, f); } }; template<typename T, typename Function> struct member_function : public base_function { typedef std::remove_pointer_t<std::decay_t<Function>> function_type; typedef meta::function_return_t<function_type> return_type; typedef meta::function_args_t<function_type> args_lists; struct functor { function_type invocation; T member; template<typename F, typename... Args> functor(F&& f, Args&&... args): invocation(std::forward<F>(f)), member(std::forward<Args>(args)...) {} template<typename... Args> return_type operator()(Args&&... args) { auto& mem = detail::unwrap(detail::deref(member)); return (mem.*invocation)(std::forward<Args>(args)...); } } fx; template<typename F, typename... Args> member_function(F&& f, Args&&... args) : fx(std::forward<F>(f), std::forward<Args>(args)...) {} int call(lua_State* L) { return stack::call_into_lua(meta::tuple_types<return_type>(), args_lists(), L, 1, fx); } virtual int operator()(lua_State* L) override { auto f = [&](lua_State* L) -> int { return this->call(L);}; return detail::trampoline(L, f); } }; template<typename T, typename Function> struct member_variable : public base_function { typedef std::remove_pointer_t<std::decay_t<Function>> function_type; typedef typename meta::bind_traits<function_type>::return_type return_type; typedef typename meta::bind_traits<function_type>::args_list args_lists; function_type var; T member; typedef std::add_lvalue_reference_t<meta::unwrapped_t<std::remove_reference_t<decltype(detail::deref(member))>>> M; template<typename V, typename... Args> member_variable(V&& v, Args&&... args): var(std::forward<V>(v)), member(std::forward<Args>(args)...) {} int set_assignable(std::false_type, lua_State* L, M) { lua_pop(L, 1); return luaL_error(L, "sol: cannot write to this type: copy assignment/constructor not available"); } int set_assignable(std::true_type, lua_State* L, M mem) { (mem.*var) = stack::get<return_type>(L, 1); lua_pop(L, 1); return 0; } int set_variable(std::true_type, lua_State* L, M mem) { return set_assignable(std::is_assignable<std::add_lvalue_reference_t<return_type>, return_type>(), L, mem); } int set_variable(std::false_type, lua_State* L, M) { lua_pop(L, 1); return luaL_error(L, "sol: cannot write to a const variable"); } int call(lua_State* L) { M mem = detail::unwrap(detail::deref(member)); switch (lua_gettop(L)) { case 0: stack::push(L, (mem.*var)); return 1; case 1: return set_variable(meta::neg<std::is_const<return_type>>(), L, mem); default: return luaL_error(L, "sol: incorrect number of arguments to member variable function"); } } virtual int operator()(lua_State* L) override { auto f = [&](lua_State* L) -> int { return this->call(L);}; return detail::trampoline(L, f); } }; } // function_detail } // sol #endif // SOL_FUNCTION_TYPES_MEMBER_HPP
38.051282
119
0.673349
27f90f4cda72a862e2d5853d1e85cef25c5ee71a
552
hpp
C++
P4/usuario_pedido.hpp
moooises/Practica-Global-de-Programacion-Orientada-a-Objetos
534f909c6cd731482baaf9682feb6d07d9d35fa6
[ "MIT" ]
null
null
null
P4/usuario_pedido.hpp
moooises/Practica-Global-de-Programacion-Orientada-a-Objetos
534f909c6cd731482baaf9682feb6d07d9d35fa6
[ "MIT" ]
null
null
null
P4/usuario_pedido.hpp
moooises/Practica-Global-de-Programacion-Orientada-a-Objetos
534f909c6cd731482baaf9682feb6d07d9d35fa6
[ "MIT" ]
null
null
null
#ifndef USUARIO_PEDIDO_HPP_ #define USUARIO_PEDIDO_HPP_ #include "usuario.hpp" #include "pedido.hpp" #include<set> #include<map> class Usuario; class Pedido; class Usuario_Pedido{ public: typedef set<Pedido*> Pedidos; void asocia(Usuario& user, Pedido& p); void asocia(Pedido& p,Usuario& user){asocia(user,p);} Pedidos pedidos(Usuario& user); Usuario* cliente(Pedido& p); private: map<Usuario*,Pedidos> UP;//insert se usa para los set map<Pedido*,Usuario*> PU; }; #endif // USUARIO_PEDIDO_HPP_
21.230769
58
0.681159
27fb12c20936fbd399932af3586df1acb164d0df
29,028
inl
C++
include/sre/impl/ShaderSource.inl
KasperHdL/SimpleRenderEngine
2d7edeead1d14e00c3d41a29cf9880e216d366e0
[ "MIT" ]
null
null
null
include/sre/impl/ShaderSource.inl
KasperHdL/SimpleRenderEngine
2d7edeead1d14e00c3d41a29cf9880e216d366e0
[ "MIT" ]
null
null
null
include/sre/impl/ShaderSource.inl
KasperHdL/SimpleRenderEngine
2d7edeead1d14e00c3d41a29cf9880e216d366e0
[ "MIT" ]
null
null
null
// autogenerated by // files_to_cpp shader src/embedded_deps/skybox_frag.glsl skybox_frag.glsl src/embedded_deps/skybox_vert.glsl skybox_vert.glsl src/embedded_deps/sre_utils_incl.glsl sre_utils_incl.glsl src/embedded_deps/debug_normal_frag.glsl debug_normal_frag.glsl src/embedded_deps/debug_normal_vert.glsl debug_normal_vert.glsl src/embedded_deps/debug_uv_frag.glsl debug_uv_frag.glsl src/embedded_deps/debug_uv_vert.glsl debug_uv_vert.glsl src/embedded_deps/light_incl.glsl light_incl.glsl src/embedded_deps/particles_frag.glsl particles_frag.glsl src/embedded_deps/particles_vert.glsl particles_vert.glsl src/embedded_deps/sprite_frag.glsl sprite_frag.glsl src/embedded_deps/sprite_vert.glsl sprite_vert.glsl src/embedded_deps/standard_pbr_frag.glsl standard_pbr_frag.glsl src/embedded_deps/standard_pbr_vert.glsl standard_pbr_vert.glsl src/embedded_deps/standard_blinn_phong_frag.glsl standard_blinn_phong_frag.glsl src/embedded_deps/standard_blinn_phong_vert.glsl standard_blinn_phong_vert.glsl src/embedded_deps/standard_phong_frag.glsl standard_phong_frag.glsl src/embedded_deps/standard_phong_vert.glsl standard_phong_vert.glsl src/embedded_deps/blit_frag.glsl blit_frag.glsl src/embedded_deps/blit_vert.glsl blit_vert.glsl src/embedded_deps/unlit_frag.glsl unlit_frag.glsl src/embedded_deps/unlit_vert.glsl unlit_vert.glsl src/embedded_deps/debug_tangent_frag.glsl debug_tangent_frag.glsl src/embedded_deps/debug_tangent_vert.glsl debug_tangent_vert.glsl src/embedded_deps/normalmap_incl.glsl normalmap_incl.glsl src/embedded_deps/global_uniforms_incl.glsl global_uniforms_incl.glsl include/sre/impl/ShaderSource.inl #include <map> #include <utility> #include <string> std::map<std::string, std::string> builtInShaderSource { std::make_pair<std::string,std::string>("skybox_frag.glsl",R"(#version 330 out vec4 fragColor; in vec3 vUV; uniform vec4 color; uniform samplerCube tex; #pragma include "sre_utils_incl.glsl" void main(void) { fragColor = color * toLinear(texture(tex, vUV)); //fragColor = toOutput(fragColor); })"), std::make_pair<std::string,std::string>("skybox_vert.glsl",R"(#version 330 in vec3 position; out vec3 vUV; #pragma include "global_uniforms_incl.glsl" void main(void) { vec4 eyespacePos = (g_view * vec4(position, 0.0)); eyespacePos.w = 1.0; gl_Position = g_model * eyespacePos; // model matrix here contains the infinite projection vUV = position; })"), std::make_pair<std::string,std::string>("sre_utils_incl.glsl",R"(vec4 toLinear(vec4 col){ #ifndef SI_TEX_SAMPLER_SRGB float gamma = 2.2; return vec4 ( col.xyz = pow(col.xyz, vec3(gamma)), col.w ); #else return col; #endif } vec4 toOutput(vec4 colorLinear){ #ifndef SI_FRAMEBUFFER_SRGB float gamma = 2.2; return vec4(pow(colorLinear.xyz,vec3(1.0/gamma)), colorLinear.a); // gamma correction #else return colorLinear; #endif } vec4 toOutput(vec3 colorLinear, float alpha){ #ifndef SI_FRAMEBUFFER_SRGB float gamma = 2.2; return vec4(pow(colorLinear,vec3(1.0/gamma)), alpha); // gamma correction #else return vec4(colorLinear, alpha); // pass through #endif })"), std::make_pair<std::string,std::string>("debug_normal_frag.glsl",R"(#version 330 out vec4 fragColor; in vec3 vNormal; #pragma include "sre_utils_incl.glsl" void main(void) { fragColor = vec4(vNormal*0.5+0.5,1.0); fragColor = toOutput(fragColor); })"), std::make_pair<std::string,std::string>("debug_normal_vert.glsl",R"(#version 330 in vec3 position; in vec3 normal; out vec3 vNormal; #pragma include "global_uniforms_incl.glsl" void main(void) { gl_Position = g_projection * g_view * g_model * vec4(position,1.0); vNormal = normal; })"), std::make_pair<std::string,std::string>("debug_uv_frag.glsl",R"(#version 330 out vec4 fragColor; in vec4 vUV; #pragma include "sre_utils_incl.glsl" void main(void) { fragColor = vUV; fragColor = toOutput(fragColor); })"), std::make_pair<std::string,std::string>("debug_uv_vert.glsl",R"(#version 330 in vec3 position; in vec4 uv; out vec4 vUV; #pragma include "global_uniforms_incl.glsl" void main(void) { gl_Position = g_projection * g_view * g_model * vec4(position,1.0); vUV = uv; })"), std::make_pair<std::string,std::string>("light_incl.glsl",R"( in vec4 vLightDir[SI_LIGHTS]; uniform vec4 specularity; void lightDirectionAndAttenuation(vec4 lightPosType, float lightRange, vec3 pos, out vec3 lightDirection, out float attenuation){ bool isDirectional = lightPosType.w == 0.0; bool isPoint = lightPosType.w == 1.0; if (isDirectional){ lightDirection = lightPosType.xyz; attenuation = 1.0; } else if (isPoint) { vec3 lightVector = lightPosType.xyz - pos; float lightVectorLength = length(lightVector); lightDirection = lightVector / lightVectorLength; // normalize if (lightRange <= 0.0){ // attenuation disabled attenuation = 1.0; } else if (lightVectorLength >= lightRange){ attenuation = 0.0; return; } else { attenuation = pow(1.0 - (lightVectorLength / lightRange), 1.5); // non physical range based attenuation } } else { attenuation = 0.0; lightDirection = vec3(0.0, 0.0, 0.0); } } vec3 computeLightBlinnPhong(vec3 wsPos, vec3 wsCameraPos, vec3 normal, out vec3 specularityOut){ specularityOut = vec3(0.0, 0.0, 0.0); vec3 lightColor = vec3(0.0,0.0,0.0); vec3 cam = normalize(wsCameraPos - wsPos); for (int i=0;i<SI_LIGHTS;i++){ vec3 lightDirection = vec3(0.0,0.0,0.0); float att = 0.0; lightDirectionAndAttenuation(g_lightPosType[i], g_lightColorRange[i].w, wsPos, lightDirection, att); if (att <= 0.0){ continue; } // diffuse light float diffuse = dot(lightDirection, normal); if (diffuse > 0.0){ lightColor += (att * diffuse) * g_lightColorRange[i].xyz; } // specular light if (specularity.a > 0.0){ vec3 H = normalize(lightDirection + cam); float nDotHV = dot(normal, H); if (nDotHV > 0.0){ float pf = pow(nDotHV, specularity.a); specularityOut += specularity.rgb * pf * att * diffuse; // white specular highlights } } } lightColor = max(g_ambientLight.xyz, lightColor); return lightColor; } vec3 computeLightBlinn(vec3 wsPos, vec3 wsCameraPos, vec3 normal){ vec3 lightColor = vec3(0.0,0.0,0.0); for (int i=0;i<SI_LIGHTS;i++){ vec3 lightDirection = vec3(0.0,0.0,0.0); float att = 0.0; lightDirectionAndAttenuation(g_lightPosType[i], g_lightColorRange[i].w, wsPos, lightDirection, att); if (att <= 0.0){ continue; } // diffuse light float diffuse = dot(lightDirection, normal); if (diffuse > 0.0){ lightColor += (att * diffuse) * g_lightColorRange[i].xyz; } } lightColor = max(g_ambientLight.xyz, lightColor); return lightColor; } vec3 computeLightPhong(vec3 wsPos, vec3 wsCameraPos, vec3 normal, out vec3 specularityOut){ specularityOut = vec3(0.0, 0.0, 0.0); vec3 lightColor = vec3(0.0,0.0,0.0); vec3 cam = normalize(wsCameraPos - wsPos); for (int i=0;i<SI_LIGHTS;i++){ vec3 lightDirection = vec3(0.0,0.0,0.0); float att = 0.0; lightDirectionAndAttenuation(g_lightPosType[i], g_lightColorRange[i].w, wsPos, lightDirection, att); if (att <= 0.0){ continue; } // diffuse light float diffuse = dot(lightDirection, normal); if (diffuse > 0.0){ lightColor += (att * diffuse) * g_lightColorRange[i].xyz; } // specular light if (specularity.a > 0.0){ vec3 R = reflect(-lightDirection, normal); float nDotRV = dot(cam, R); if (nDotRV > 0.0){ float pf = pow(nDotRV, specularity.a); specularityOut += specularity.rgb * (pf * att); // white specular highlights } } } lightColor = max(g_ambientLight.xyz, lightColor); return lightColor; })"), std::make_pair<std::string,std::string>("particles_frag.glsl",R"(#version 330 out vec4 fragColor; in mat3 vUVMat; in vec3 uvSize; in vec4 vColor; #pragma include "global_uniforms_incl.glsl" uniform sampler2D tex; #pragma include "sre_utils_incl.glsl" void main(void) { vec2 uv = (vUVMat * vec3(gl_PointCoord,1.0)).xy; if (uv != clamp(uv, uvSize.xy, uvSize.xy + uvSize.zz)){ discard; } vec4 c = vColor * toLinear(texture(tex, uv)); fragColor = c; fragColor = toOutput(fragColor); })"), std::make_pair<std::string,std::string>("particles_vert.glsl",R"(#version 330 in vec3 position; in float particleSize; in vec4 uv; in vec4 vertex_color; out mat3 vUVMat; out vec4 vColor; out vec3 uvSize; #pragma include "global_uniforms_incl.glsl" mat3 translate(vec2 p){ return mat3(1.0,0.0,0.0,0.0,1.0,0.0,p.x,p.y,1.0); } mat3 rotate(float rad){ float s = sin(rad); float c = cos(rad); return mat3(c,s,0.0,-s,c,0.0,0.0,0.0,1.0); } mat3 scale(float s){ return mat3(s,0.0,0.0,0.0,s,0.0,0.0,0.0,1.0); } void main(void) { vec4 pos = vec4( position, 1.0); vec4 eyeSpacePos = g_view * g_model * pos; gl_Position = g_projection * eyeSpacePos; if (g_projection[2][3] != 0.0){ // if perspective projection gl_PointSize = (g_viewport.y / 600.0) * particleSize * 1.0 / -eyeSpacePos.z; } else { gl_PointSize = particleSize*(g_viewport.y / 600.0); } vUVMat = translate(uv.xy)*scale(uv.z) * translate(vec2(0.5,0.5))*rotate(uv.w) * translate(vec2(-0.5,-0.5)); vColor = vertex_color; uvSize = uv.xyz; })"), std::make_pair<std::string,std::string>("sprite_frag.glsl",R"(#version 330 out vec4 fragColor; in vec2 vUV; in vec4 vColor; uniform sampler2D tex; #pragma include "sre_utils_incl.glsl" void main(void) { fragColor = vColor * toLinear(texture(tex, vUV)); fragColor = toOutput(fragColor); })"), std::make_pair<std::string,std::string>("sprite_vert.glsl",R"(#version 330 in vec3 position; in vec4 uv; in vec4 vertex_color; out vec2 vUV; out vec4 vColor; #pragma include "global_uniforms_incl.glsl" void main(void) { gl_Position = g_projection * g_view * g_model * vec4(position,1.0); vUV = uv.xy; vColor = vertex_color; })"), std::make_pair<std::string,std::string>("standard_pbr_frag.glsl",R"(#version 330 #extension GL_EXT_shader_texture_lod: enable #extension GL_OES_standard_derivatives : enable out vec4 fragColor; #if defined(S_TANGENTS) && defined(S_NORMALMAP) in mat3 vTBN; #else in vec3 vNormal; #endif in vec2 vUV; in vec3 vWsPos; uniform vec4 color; uniform vec4 metallicRoughness; uniform sampler2D tex; #ifdef S_METALROUGHNESSMAP uniform sampler2D mrTex; #endif #ifdef S_NORMALMAP uniform sampler2D normalTex; uniform float normalScale; #endif #ifdef S_EMISSIVEMAP uniform sampler2D emissiveTex; uniform vec4 emissiveFactor; #endif #ifdef S_OCCLUSIONMAP uniform sampler2D occlusionTex; uniform float occlusionStrength; #endif #ifdef S_VERTEX_COLOR in vec4 vColor; #endif #pragma include "global_uniforms_incl.glsl" #pragma include "normalmap_incl.glsl" #pragma include "light_incl.glsl" #pragma include "sre_utils_incl.glsl" // Encapsulate the various inputs used by the various functions in the shading equation // We store values in this struct to simplify the integration of alternative implementations // of the shading terms, outlined in the Readme.MD Appendix. struct PBRInfo { float NdotL; // cos angle between normal and light direction float NdotV; // cos angle between normal and view direction float NdotH; // cos angle between normal and half vector float LdotH; // cos angle between light direction and half vector float VdotH; // cos angle between view direction and half vector float perceptualRoughness; // roughness value, as authored by the model creator (input to shader) float metalness; // metallic value at the surface vec3 reflectance0; // full reflectance color (normal incidence angle) vec3 reflectance90; // reflectance color at grazing angle float alphaRoughness; // roughness mapped to a more linear change in the roughness (proposed by [2]) vec3 diffuseColor; // color contribution from diffuse lighting vec3 specularColor; // color contribution from specular lighting }; const float M_PI = 3.141592653589793; const float c_MinRoughness = 0.04; // The following equation models the Fresnel reflectance term of the spec equation (aka F()) // Implementation of fresnel from [4], Equation 15 vec3 specularReflection(PBRInfo pbrInputs) { return pbrInputs.reflectance0 + (pbrInputs.reflectance90 - pbrInputs.reflectance0) * pow(clamp(1.0 - pbrInputs.VdotH, 0.0, 1.0), 5.0); } // Basic Lambertian diffuse // Implementation from Lambert's Photometria https://archive.org/details/lambertsphotome00lambgoog // See also [1], Equation 1 vec3 diffuse(PBRInfo pbrInputs) { return pbrInputs.diffuseColor / M_PI; } // This calculates the specular geometric attenuation (aka G()), // where rougher material will reflect less light back to the viewer. // This implementation is based on [1] Equation 4, and we adopt their modifications to // alphaRoughness as input as originally proposed in [2]. float geometricOcclusion(PBRInfo pbrInputs) { float NdotL = pbrInputs.NdotL; float NdotV = pbrInputs.NdotV; float r = pbrInputs.alphaRoughness; float attenuationL = 2.0 * NdotL / (NdotL + sqrt(r * r + (1.0 - r * r) * (NdotL * NdotL))); float attenuationV = 2.0 * NdotV / (NdotV + sqrt(r * r + (1.0 - r * r) * (NdotV * NdotV))); return attenuationL * attenuationV; } // The following equation(s) model the distribution of microfacet normals across the area being drawn (aka D()) // Implementation from "Average Irregularity Representation of a Roughened Surface for Ray Reflection" by T. S. Trowbridge, and K. P. Reitz // Follows the distribution function recommended in the SIGGRAPH 2013 course notes from EPIC Games [1], Equation 3. float microfacetDistribution(PBRInfo pbrInputs) { float roughnessSq = pbrInputs.alphaRoughness * pbrInputs.alphaRoughness; float f = (pbrInputs.NdotH * roughnessSq - pbrInputs.NdotH) * pbrInputs.NdotH + 1.0; return roughnessSq / (M_PI * f * f); } void main(void) { float perceptualRoughness = metallicRoughness.y; float metallic = metallicRoughness.x; #ifdef S_METALROUGHNESSMAP // Roughness is stored in the 'g' channel, metallic is stored in the 'b' channel. // This layout intentionally reserves the 'r' channel for (optional) occlusion map data vec4 mrSample = texture(mrTex, vUV); perceptualRoughness = mrSample.g * perceptualRoughness; metallic = mrSample.b * metallic; #endif perceptualRoughness = clamp(perceptualRoughness, c_MinRoughness, 1.0); metallic = clamp(metallic, 0.0, 1.0); // Roughness is authored as perceptual roughness; as is convention, // convert to material roughness by squaring the perceptual roughness [2]. float alphaRoughness = perceptualRoughness * perceptualRoughness; #ifndef S_NO_BASECOLORMAP vec4 baseColor = toLinear(texture(tex, vUV)) * color; #else vec4 baseColor = color; #endif #ifdef S_VERTEX_COLOR baseColor = baseColor * vColor; #endif vec3 f0 = vec3(0.04); vec3 diffuseColor = baseColor.rgb * (vec3(1.0) - f0); diffuseColor *= 1.0 - metallic; vec3 specularColor = mix(f0, baseColor.rgb, metallic); // Compute reflectance. float reflectance = max(max(specularColor.r, specularColor.g), specularColor.b); // For typical incident reflectance range (between 4% to 100%) set the grazing reflectance to 100% for typical fresnel effect. // For very low reflectance range on highly diffuse objects (below 4%), incrementally reduce grazing reflectance to 0%. float reflectance90 = clamp(reflectance * 25.0, 0.0, 1.0); vec3 specularEnvironmentR0 = specularColor.rgb; vec3 specularEnvironmentR90 = vec3(1.0, 1.0, 1.0) * reflectance90; vec3 color = baseColor.rgb * g_ambientLight.rgb; // non pbr vec3 n = getNormal(); // Normal at surface point vec3 v = normalize(g_cameraPos.xyz - vWsPos.xyz); // Vector from surface point to camera for (int i=0;i<SI_LIGHTS;i++) { float attenuation = 0.0; vec3 l = vec3(0.0,0.0,0.0); lightDirectionAndAttenuation(g_lightPosType[i], g_lightColorRange[i].w, vWsPos, l, attenuation); if (attenuation <= 0.0){ continue; } vec3 h = normalize(l+v); // Half vector between both l and v vec3 reflection = -normalize(reflect(v, n)); float NdotL = clamp(dot(n, l), 0.0001, 1.0); float NdotV = abs(dot(n, v)) + 0.0001; float NdotH = clamp(dot(n, h), 0.0, 1.0); float LdotH = clamp(dot(l, h), 0.0, 1.0); float VdotH = clamp(dot(v, h), 0.0, 1.0); PBRInfo pbrInputs = PBRInfo( NdotL, NdotV, NdotH, LdotH, VdotH, perceptualRoughness, metallic, specularEnvironmentR0, specularEnvironmentR90, alphaRoughness, diffuseColor, specularColor ); // Calculate the shading terms for the microfacet specular shading model vec3 F = specularReflection(pbrInputs); float G = geometricOcclusion(pbrInputs); float D = microfacetDistribution(pbrInputs); // Calculation of analytical lighting contribution vec3 diffuseContrib = (1.0 - F) * diffuse(pbrInputs); vec3 specContrib = F * G * D / (4.0 * NdotL * NdotV); color += attenuation * NdotL * g_lightColorRange[i].xyz * (diffuseContrib + specContrib); } // Apply optional PBR terms for additional (optional) shading #ifdef S_OCCLUSIONMAP float ao = texture(occlusionTex, vUV).r; color = mix(color, color * ao, occlusionStrength); #endif #ifdef S_EMISSIVEMAP vec3 emissive = toLinear(texture(emissiveTex, vUV)).rgb * emissiveFactor.xyz; color += emissive; #endif fragColor = toOutput(color,baseColor.a); })"), std::make_pair<std::string,std::string>("standard_pbr_vert.glsl",R"(#version 330 in vec3 position; in vec3 normal; in vec4 uv; #if defined(S_TANGENTS) && defined(S_NORMALMAP) in vec4 tangent; out mat3 vTBN; #else out vec3 vNormal; #endif #ifdef S_VERTEX_COLOR in vec4 vertex_color; out vec4 vColor; #endif out vec2 vUV; out vec3 vWsPos; #pragma include "global_uniforms_incl.glsl" #pragma include "normalmap_incl.glsl" void main(void) { vec4 wsPos = g_model * vec4(position,1.0); vWsPos = wsPos.xyz; gl_Position = g_projection * g_view * wsPos; #if defined(S_TANGENTS) && defined(S_NORMALMAP) vTBN = computeTBN(g_model_it, normal, tangent); #else vNormal = normalize(g_model_it * normal); #endif vUV = uv.xy; #ifdef S_VERTEX_COLOR vColor = vertex_color; #endif })"), std::make_pair<std::string,std::string>("standard_blinn_phong_frag.glsl",R"(#version 330 out vec4 fragColor; #if defined(S_TANGENTS) && defined(S_NORMALMAP) in mat3 vTBN; #else in vec3 vNormal; #endif in vec2 vUV; in vec3 vWsPos; #ifdef S_NORMALMAP uniform sampler2D normalTex; uniform float normalScale; #endif #ifdef S_VERTEX_COLOR in vec4 vColor; #endif uniform vec4 color; uniform sampler2D tex; #pragma include "global_uniforms_incl.glsl" #pragma include "light_incl.glsl" #pragma include "normalmap_incl.glsl" #pragma include "sre_utils_incl.glsl" void main() { vec4 c = color * toLinear(texture(tex, vUV)); #ifdef S_VERTEX_COLOR c = c * vColor; #endif vec3 normal = getNormal(); vec3 specularLight = vec3(0.0,0.0,0.0); vec3 l = computeLightBlinnPhong(vWsPos, g_cameraPos.xyz, normal, specularLight); fragColor = c * vec4(l, 1.0) + vec4(specularLight,0); fragColor = toOutput(fragColor); })"), std::make_pair<std::string,std::string>("standard_blinn_phong_vert.glsl",R"(#version 330 in vec3 position; in vec3 normal; in vec4 uv; out vec2 vUV; #if defined(S_TANGENTS) && defined(S_NORMALMAP) in vec4 tangent; out mat3 vTBN; #else out vec3 vNormal; #endif out vec3 vWsPos; #ifdef S_VERTEX_COLOR in vec4 vertex_color; out vec4 vColor; #endif #pragma include "global_uniforms_incl.glsl" #pragma include "normalmap_incl.glsl" void main(void) { vec4 wsPos = g_model * vec4(position,1.0); gl_Position = g_projection * g_view * wsPos; #if defined(S_TANGENTS) && defined(S_NORMALMAP) vTBN = computeTBN(g_model_it, normal, tangent); #else vNormal = normalize(g_model_it * normal); #endif vUV = uv.xy; vWsPos = wsPos.xyz; #ifdef S_VERTEX_COLOR vColor = vertex_color; #endif })"), std::make_pair<std::string,std::string>("standard_phong_frag.glsl",R"(#version 330 out vec4 fragColor; #if defined(S_TANGENTS) && defined(S_NORMALMAP) in mat3 vTBN; #else in vec3 vNormal; #endif in vec2 vUV; in vec3 vWsPos; #ifdef S_NORMALMAP uniform sampler2D normalTex; uniform float normalScale; #endif #ifdef S_VERTEX_COLOR in vec4 vColor; #endif uniform vec4 color; uniform sampler2D tex; #pragma include "global_uniforms_incl.glsl" #pragma include "light_incl.glsl" #pragma include "normalmap_incl.glsl" #pragma include "sre_utils_incl.glsl" void main() { vec4 c = color * toLinear(texture(tex, vUV)); #ifdef S_VERTEX_COLOR c = c * vColor; #endif vec3 normal = getNormal(); vec3 specularLight = vec3(0.0,0.0,0.0); vec3 l = computeLightPhong(vWsPos, g_cameraPos.xyz, normal, specularLight); fragColor = c * vec4(l, 1.0) + vec4(specularLight,0); fragColor = toOutput(fragColor); })"), std::make_pair<std::string,std::string>("standard_phong_vert.glsl",R"(#version 330 in vec3 position; in vec3 normal; in vec4 uv; out vec2 vUV; #if defined(S_TANGENTS) && defined(S_NORMALMAP) in vec4 tangent; out mat3 vTBN; #else out vec3 vNormal; #endif out vec3 vWsPos; #ifdef S_VERTEX_COLOR in vec4 vertex_color; out vec4 vColor; #endif #pragma include "global_uniforms_incl.glsl" #pragma include "normalmap_incl.glsl" void main(void) { vec4 wsPos = g_model * vec4(position,1.0); gl_Position = g_projection * g_view * wsPos; #if defined(S_TANGENTS) && defined(S_NORMALMAP) vTBN = computeTBN(g_model_it, normal, tangent); #else vNormal = normalize(g_model_it * normal); #endif vUV = uv.xy; vWsPos = wsPos.xyz; #ifdef S_VERTEX_COLOR vColor = vertex_color; #endif })"), std::make_pair<std::string,std::string>("blit_frag.glsl",R"(#version 330 out vec4 fragColor; in vec2 vUV; uniform sampler2D tex; #pragma include "sre_utils_incl.glsl" void main(void) { fragColor = toLinear(texture(tex, vUV)); fragColor = toOutput(fragColor); })"), std::make_pair<std::string,std::string>("blit_vert.glsl",R"(#version 330 in vec3 position; in vec3 normal; in vec4 uv; out vec2 vUV; #pragma include "global_uniforms_incl.glsl" void main(void) { gl_Position = g_model * vec4(position,1.0); vUV = uv.xy; })"), std::make_pair<std::string,std::string>("unlit_frag.glsl",R"(#version 330 out vec4 fragColor; in vec2 vUV; #ifdef S_VERTEX_COLOR in vec4 vColor; #endif uniform vec4 color; uniform sampler2D tex; #pragma include "sre_utils_incl.glsl" void main(void) { fragColor = color * toLinear(texture(tex, vUV)); #ifdef S_VERTEX_COLOR fragColor = fragColor * vColor; #endif //fragColor = toOutput(fragColor); })"), std::make_pair<std::string,std::string>("unlit_vert.glsl",R"(#version 330 in vec3 position; in vec3 normal; #ifdef S_VERTEX_COLOR in vec4 vertex_color; out vec4 vColor; #endif in vec4 uv; out vec2 vUV; #pragma include "global_uniforms_incl.glsl" void main(void) { gl_Position = g_projection * g_view * g_model * vec4(position,1.0); vUV = uv.xy; #ifdef S_VERTEX_COLOR vColor = vertex_color; #endif })"), std::make_pair<std::string,std::string>("debug_tangent_frag.glsl",R"(#version 330 out vec4 fragColor; in vec3 vTangent; #pragma include "sre_utils_incl.glsl" void main(void) { fragColor = vec4(vTangent*0.5+0.5,1.0); fragColor = toOutput(fragColor); })"), std::make_pair<std::string,std::string>("debug_tangent_vert.glsl",R"(#version 330 in vec3 position; in vec4 tangent; out vec3 vTangent; #pragma include "global_uniforms_incl.glsl" void main(void) { gl_Position = g_projection * g_view * g_model * vec4(position,1.0); vTangent = tangent.xyz * tangent.w; })"), std::make_pair<std::string,std::string>("normalmap_incl.glsl",R"(#ifdef SI_VERTEX mat3 computeTBN(mat3 g_model_it, vec3 normal, vec4 tangent){ vec3 wsNormal = normalize(g_model_it * normal); vec3 wsTangent = normalize(g_model_it * tangent.xyz); vec3 wsBitangent = cross(wsNormal, wsTangent) * tangent.w; return mat3(wsTangent, wsBitangent, wsNormal); } #endif #ifdef SI_FRAGMENT // Find the normal for this fragment, pulling either from a predefined normal map // or from the interpolated mesh normal and tangent attributes. vec3 getNormal() { #ifdef S_NORMALMAP // Retrieve the tangent space matrix #ifndef S_TANGENTS vec3 pos_dx = dFdx(vWsPos); vec3 pos_dy = dFdy(vWsPos); vec3 tex_dx = dFdx(vec3(vUV, 0.0)); vec3 tex_dy = dFdy(vec3(vUV, 0.0)); vec3 t = (tex_dy.t * pos_dx - tex_dx.t * pos_dy) / (tex_dx.s * tex_dy.t - tex_dy.s * tex_dx.t); vec3 ng = normalize(vNormal); t = normalize(t - ng * dot(ng, t)); vec3 b = normalize(cross(ng, t)); mat3 tbn = mat3(t, b, ng); #else // S_TANGENTS mat3 tbn = vTBN; #endif vec3 n = texture(normalTex, vUV).rgb; n = normalize(tbn * ((2.0 * n - 1.0) * vec3(normalScale, normalScale, 1.0))); #else vec3 n = normalize(vNormal); #endif return n; } #endif)"), std::make_pair<std::string,std::string>("global_uniforms_incl.glsl",R"(// Per render-pass uniforms #if __VERSION__ > 100 layout(std140) uniform g_global_uniforms { #endif #ifdef GL_ES #ifdef GL_FRAGMENT_PRECISION_HIGH uniform highp mat4 g_view; uniform highp mat4 g_projection; uniform highp vec4 g_viewport; uniform highp vec4 g_cameraPos; uniform highp vec4 g_ambientLight; uniform highp vec4 g_lightColorRange[SI_LIGHTS]; uniform highp vec4 g_lightPosType[SI_LIGHTS]; #else uniform mediump mat4 g_view; uniform mediump mat4 g_projection; uniform mediump vec4 g_viewport; uniform mediump vec4 g_cameraPos; uniform mediump vec4 g_ambientLight; uniform mediump vec4 g_lightColorRange[SI_LIGHTS]; uniform mediump vec4 g_lightPosType[SI_LIGHTS]; #endif #else uniform mat4 g_view; uniform mat4 g_projection; uniform vec4 g_viewport; uniform vec4 g_cameraPos; uniform vec4 g_ambientLight; uniform vec4 g_lightColorRange[SI_LIGHTS]; uniform vec4 g_lightPosType[SI_LIGHTS]; #endif #if __VERSION__ > 100 }; #endif #ifdef GL_ES // Per draw call uniforms #ifdef GL_FRAGMENT_PRECISION_HIGH uniform highp mat4 g_model; uniform highp mat3 g_model_it; uniform highp mat3 g_model_view_it; #else uniform mediump mat4 g_model; uniform mediump mat3 g_model_it; uniform mediump mat3 g_model_view_it; #endif #else uniform mat4 g_model; uniform mat3 g_model_it; uniform mat3 g_model_view_it; #endif)"), std::make_pair<std::string,std::string>("standard_blinn_frag.glsl",R"(#version 330 out vec4 fragColor; #if defined(S_TANGENTS) && defined(S_NORMALMAP) in mat3 vTBN; #else in vec3 vNormal; #endif in vec2 vUV; in vec3 vWsPos; #ifdef S_NORMALMAP uniform sampler2D normalTex; uniform float normalScale; #endif #ifdef S_VERTEX_COLOR in vec4 vColor; #endif uniform vec4 color; uniform sampler2D tex; #pragma include "global_uniforms_incl.glsl" #pragma include "light_incl.glsl" #pragma include "normalmap_incl.glsl" #pragma include "sre_utils_incl.glsl" void main() { vec4 c = color * toLinear(texture(tex, vUV)); #ifdef S_VERTEX_COLOR c = c * vColor; #endif vec3 normal = getNormal(); vec3 l = computeLightBlinn(vWsPos, g_cameraPos.xyz, normal); fragColor = c * vec4(l, 1.0); //fragColor = toOutput(fragColor); })"), std::make_pair<std::string,std::string>("standard_blinn_vert.glsl",R"(#version 330 in vec3 position; in vec3 normal; in vec4 uv; out vec2 vUV; #if defined(S_TANGENTS) && defined(S_NORMALMAP) in vec4 tangent; out mat3 vTBN; #else out vec3 vNormal; #endif out vec3 vWsPos; #ifdef S_VERTEX_COLOR in vec4 vertex_color; out vec4 vColor; #endif #pragma include "global_uniforms_incl.glsl" #pragma include "normalmap_incl.glsl" void main(void) { vec4 wsPos = g_model * vec4(position,1.0); gl_Position = g_projection * g_view * wsPos; #if defined(S_TANGENTS) && defined(S_NORMALMAP) vTBN = computeTBN(g_model_it, normal, tangent); #else vNormal = normalize(g_model_it * normal); #endif vUV = uv.xy; vWsPos = wsPos.xyz; #ifdef S_VERTEX_COLOR vColor = vertex_color; #endif })"), };
30.427673
1,608
0.701805
27fb453dc6c7a40951d513a131c0e349d4c57920
1,040
hpp
C++
Pi/server.hpp
FundCompXbee/XBeeMessenger
f3210077cb82e1597980b33bc6e2f8f9cf7bc042
[ "MIT" ]
1
2016-04-29T22:30:58.000Z
2016-04-29T22:30:58.000Z
Pi/server.hpp
FundCompXbee/XBeeMessenger
f3210077cb82e1597980b33bc6e2f8f9cf7bc042
[ "MIT" ]
null
null
null
Pi/server.hpp
FundCompXbee/XBeeMessenger
f3210077cb82e1597980b33bc6e2f8f9cf7bc042
[ "MIT" ]
null
null
null
// Team: XBeeMessenger // Course: Fundamentals of Computing II // Assignment: Final Project // Purpose: Interface for a server which receives requests, handles // requests, and broadcasts responses #ifndef SERVER #define SERVER #include <string> #include <unistd.h> #include <cstdlib> #include "IRCCommandHandler.hpp" #include "serial.hpp" #include "envelope.hpp" class Server { public: Server(int baud); // contructor, initializes serial and gets hostname void run(); // Sets the server into action private: static const char delimiter; // signals the end of a serial transmission std::string name; // The server's name. By default this is retrieved from the // server's hostname IRCCommandHandler IRCHandler; // Handles commands Serial serial; // Handles data transmission std::string retrieveSerialData(); // retrieves raw JSON-string from serial void broadcastSerialData(std::string broadcastMessage); // broadcasts message std::string validateRequest(Envelope& request); }; #endif
28.888889
79
0.735577
7e0119a4fd94dd780940a2fc66941202f79fc7b6
2,088
cpp
C++
libs/libvtrutil/src/vtr_list.cpp
rding2454/IndeStudy
c27be794bc2ce5ada93b16c92569a4bcafc8a21c
[ "MIT" ]
null
null
null
libs/libvtrutil/src/vtr_list.cpp
rding2454/IndeStudy
c27be794bc2ce5ada93b16c92569a4bcafc8a21c
[ "MIT" ]
null
null
null
libs/libvtrutil/src/vtr_list.cpp
rding2454/IndeStudy
c27be794bc2ce5ada93b16c92569a4bcafc8a21c
[ "MIT" ]
null
null
null
#include <cstdlib> #include "vtr_list.h" #include "vtr_memory.h" namespace vtr { t_linked_vptr *insert_in_vptr_list(t_linked_vptr *head, void *vptr_to_add) { /* Inserts a new element at the head of a linked list of void pointers. * * Returns the new head of the list. */ t_linked_vptr *linked_vptr; linked_vptr = (t_linked_vptr *) vtr::malloc(sizeof(t_linked_vptr)); linked_vptr->data_vptr = vptr_to_add; linked_vptr->next = head; return (linked_vptr); /* New head of the list */ } /* Deletes the element at the head of a linked list of void pointers. * * Returns the new head of the list. */ t_linked_vptr *delete_in_vptr_list(t_linked_vptr *head) { t_linked_vptr *linked_vptr; if (head == NULL ) return NULL ; linked_vptr = head->next; free(head); return linked_vptr; /* New head of the list */ } t_linked_int *insert_in_int_list(t_linked_int * head, int data, t_linked_int ** free_list_head_ptr) { /* Inserts a new element at the head of a linked list of integers. Returns * * the new head of the list. One argument is the address of the head of * * a list of free ilist elements. If there are any elements on this free * * list, the new element is taken from it. Otherwise a new one is malloced. */ t_linked_int *linked_int; if (*free_list_head_ptr != NULL ) { linked_int = *free_list_head_ptr; *free_list_head_ptr = linked_int->next; } else { linked_int = (t_linked_int *) vtr::malloc(sizeof(t_linked_int)); } linked_int->data = data; linked_int->next = head; return (linked_int); } void free_int_list(t_linked_int ** int_list_head_ptr) { /* This routine truly frees (calls free) all the integer list elements * * on the linked list pointed to by *head, and sets head = NULL. */ t_linked_int *linked_int, *next_linked_int; linked_int = *int_list_head_ptr; while (linked_int != NULL ) { next_linked_int = linked_int->next; free(linked_int); linked_int = next_linked_int; } *int_list_head_ptr = NULL; } } //namespace
27.84
80
0.688218
7e02f72ff574211551d229e1e0fc74712916682b
4,370
hxx
C++
opencascade/HLRBRep_EdgeData.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
117
2020-03-07T12:07:05.000Z
2022-03-27T07:35:22.000Z
opencascade/HLRBRep_EdgeData.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
66
2019-12-20T16:07:36.000Z
2022-03-15T21:56:10.000Z
opencascade/HLRBRep_EdgeData.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
76
2020-03-16T01:47:46.000Z
2022-03-21T16:37:07.000Z
// Created on: 1997-04-17 // Created by: Christophe MARION // Copyright (c) 1997-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _HLRBRep_EdgeData_HeaderFile #define _HLRBRep_EdgeData_HeaderFile #include <HLRAlgo_WiresBlock.hxx> #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Standard_Boolean.hxx> #include <Standard_Integer.hxx> #include <HLRAlgo_EdgeStatus.hxx> #include <HLRBRep_Curve.hxx> #include <Standard_ShortReal.hxx> #include <Standard_Real.hxx> class TopoDS_Edge; // resolve name collisions with X11 headers #ifdef Status #undef Status #endif class HLRBRep_EdgeData { public: DEFINE_STANDARD_ALLOC HLRBRep_EdgeData() : myFlags(0), myHideCount(0) { Selected(Standard_True); } Standard_EXPORT void Set (const Standard_Boolean Reg1, const Standard_Boolean RegN, const TopoDS_Edge& EG, const Standard_Integer V1, const Standard_Integer V2, const Standard_Boolean Out1, const Standard_Boolean Out2, const Standard_Boolean Cut1, const Standard_Boolean Cut2, const Standard_Real Start, const Standard_ShortReal TolStart, const Standard_Real End, const Standard_ShortReal TolEnd); Standard_Boolean Selected() const; void Selected (const Standard_Boolean B); Standard_Boolean Rg1Line() const; void Rg1Line (const Standard_Boolean B); Standard_Boolean RgNLine() const; void RgNLine (const Standard_Boolean B); Standard_Boolean Vertical() const; void Vertical (const Standard_Boolean B); Standard_Boolean Simple() const; void Simple (const Standard_Boolean B); Standard_Boolean OutLVSta() const; void OutLVSta (const Standard_Boolean B); Standard_Boolean OutLVEnd() const; void OutLVEnd (const Standard_Boolean B); Standard_Boolean CutAtSta() const; void CutAtSta (const Standard_Boolean B); Standard_Boolean CutAtEnd() const; void CutAtEnd (const Standard_Boolean B); Standard_Boolean VerAtSta() const; void VerAtSta (const Standard_Boolean B); Standard_Boolean VerAtEnd() const; void VerAtEnd (const Standard_Boolean B); Standard_Boolean AutoIntersectionDone() const; void AutoIntersectionDone (const Standard_Boolean B); Standard_Boolean Used() const; void Used (const Standard_Boolean B); Standard_Integer HideCount() const; void HideCount (const Standard_Integer I); Standard_Integer VSta() const; void VSta (const Standard_Integer I); Standard_Integer VEnd() const; void VEnd (const Standard_Integer I); void UpdateMinMax (const HLRAlgo_EdgesBlock::MinMaxIndices& theTotMinMax) { myMinMax = theTotMinMax; } HLRAlgo_EdgesBlock::MinMaxIndices& MinMax() { return myMinMax; } HLRAlgo_EdgeStatus& Status(); HLRBRep_Curve& ChangeGeometry(); const HLRBRep_Curve& Geometry() const; HLRBRep_Curve* Curve() { return &myGeometry; } Standard_ShortReal Tolerance() const; protected: enum EMaskFlags { EMaskSelected = 1, EMaskUsed = 2, EMaskRg1Line = 4, EMaskVertical = 8, EMaskSimple = 16, EMaskOutLVSta = 32, EMaskOutLVEnd = 64, EMaskIntDone = 128, EMaskCutAtSta = 256, EMaskCutAtEnd = 512, EMaskVerAtSta = 1024, EMaskVerAtEnd = 2048, EMaskRgNLine = 4096 }; private: Standard_Integer myFlags; Standard_Integer myHideCount; Standard_Integer myVSta; Standard_Integer myVEnd; HLRAlgo_EdgesBlock::MinMaxIndices myMinMax; HLRAlgo_EdgeStatus myStatus; HLRBRep_Curve myGeometry; Standard_ShortReal myTolerance; }; #include <HLRBRep_EdgeData.lxx> #endif // _HLRBRep_EdgeData_HeaderFile
24.829545
399
0.731579
7e03a73e36dc22f3de69ca364f53f10da5f6634b
769
cpp
C++
dbms/src/Parsers/ASTTTLElement.cpp
sunadm/ClickHouse
55903fbe23ef6dff8fc7ec25ae68e04919bc9b7f
[ "Apache-2.0" ]
7
2021-02-26T04:34:22.000Z
2021-12-31T08:15:47.000Z
dbms/src/Parsers/ASTTTLElement.cpp
sunadm/ClickHouse
55903fbe23ef6dff8fc7ec25ae68e04919bc9b7f
[ "Apache-2.0" ]
1
2019-10-13T16:06:13.000Z
2019-10-13T16:06:13.000Z
dbms/src/Parsers/ASTTTLElement.cpp
sunadm/ClickHouse
55903fbe23ef6dff8fc7ec25ae68e04919bc9b7f
[ "Apache-2.0" ]
3
2020-02-24T12:57:54.000Z
2021-10-04T13:29:00.000Z
#include <Columns/Collator.h> #include <Common/quoteString.h> #include <Parsers/ASTTTLElement.h> namespace DB { void ASTTTLElement::formatImpl(const FormatSettings & settings, FormatState & state, FormatStateStacked frame) const { children.front()->formatImpl(settings, state, frame); if (destination_type == PartDestinationType::DISK) { settings.ostr << " TO DISK " << quoteString(destination_name); } else if (destination_type == PartDestinationType::VOLUME) { settings.ostr << " TO VOLUME " << quoteString(destination_name); } else if (destination_type == PartDestinationType::DELETE) { /// It would be better to output "DELETE" here but that will break compatibility with earlier versions. } } }
27.464286
116
0.694408
7e042ee4252496e14df8e3c73c6b1adecbcd3299
1,248
cc
C++
StatModules/src/ToyMCLikelihoodEvaluator.cc
GooStats/GooStats
5a8bc35736eb390d658c790fa0026b576898a462
[ "MIT" ]
3
2020-01-28T21:51:46.000Z
2021-09-06T18:43:00.000Z
StatModules/src/ToyMCLikelihoodEvaluator.cc
GooStats/GooStats
5a8bc35736eb390d658c790fa0026b576898a462
[ "MIT" ]
12
2019-08-09T08:58:49.000Z
2022-03-16T04:00:11.000Z
StatModules/src/ToyMCLikelihoodEvaluator.cc
GooStats/GooStats
5a8bc35736eb390d658c790fa0026b576898a462
[ "MIT" ]
3
2018-04-12T11:53:55.000Z
2022-03-17T13:06:06.000Z
/*****************************************************************************/ // Author: Xuefeng Ding <xuefeng.ding.physics@gmail.com> // Insitute: Gran Sasso Science Institute, L'Aquila, 67100, Italy // Date: 2018 April 7th // Version: v1.0 // Description: GooStats, a statistical analysis toolkit that runs on GPU. // // All rights reserved. 2018 copyrighted. /*****************************************************************************/ #include "ToyMCLikelihoodEvaluator.h" #include "InputManager.h" #include "SumLikelihoodPdf.h" #include "GSFitManager.h" void ToyMCLikelihoodEvaluator::get_p_value(GSFitManager *gsFitManager,InputManager *manager,double LL,double &p,double &perr,FitControl *fit) { const OptionManager *gOp = manager->GlobalOption(); int N = gOp->has("toyMC_size")?gOp->get<double>("toyMC_size"):100; if(N==0) return; SumLikelihoodPdf *totalPdf = manager->getTotalPdf(); totalPdf->setFitControl(fit); totalPdf->copyParams(); totalPdf->cache(); LLs.clear(); int n = 0; for(int i = 0;i<N;++i) { manager->fillRandomData(); LLs.push_back(totalPdf->calculateNLL()); if(LLs.back()>LL) ++n; } totalPdf->restore(); gsFitManager->restoreFitControl(); p = n*1./N; perr = sqrt(p*(1-p)/N); }
36.705882
143
0.614583
7e06656f021627fc251d7c71b350492b3a325178
7,917
cpp
C++
test/stkdatatest/ManyRecords.cpp
Aekras1a/YaizuComLib
470d33376add0d448002221b75f7efd40eec506f
[ "MIT" ]
1
2022-01-30T20:17:16.000Z
2022-01-30T20:17:16.000Z
test/stkdatatest/ManyRecords.cpp
Aekras1a/YaizuComLib
470d33376add0d448002221b75f7efd40eec506f
[ "MIT" ]
null
null
null
test/stkdatatest/ManyRecords.cpp
Aekras1a/YaizuComLib
470d33376add0d448002221b75f7efd40eec506f
[ "MIT" ]
null
null
null
#include "../../src/stkpl/StkPl.h" #include "../../src/stkdata/stkdata.h" #include "../../src/stkdata/stkdataapi.h" /* ManyRecords ・WStr(256)×32カラム×16383レコードのテーブルを作成することができる。InsertRecordを16383回繰り返しレコードを追加できる ・既存の[焼津沼津辰口町和泉町中田北白楽]テーブルから10レコードを削除できる。条件として連結されたレコードを指定する ・存在しないカラム名を指定してZaSortRecordを実行したとき,-1が返却される。 */ int ManyRecords() { { StkPlPrintf("Table can be created defined as WStr(256) x 32 columns×16383 records. Records can be inserted 16383 times using InsertRecord."); ColumnDefWStr* ColDef[32]; TableDef LargeTable(L"焼津沼津辰口町和泉町中田北白楽", 16383); for (int i = 0; i < 32; i++) { wchar_t ColName[16]; StkPlSwPrintf(ColName, 16, L"東西南北老若男女焼肉定食愛%d", i); ColDef[i] = new ColumnDefWStr(ColName, 256); LargeTable.AddColumnDef(ColDef[i]); } if (CreateTable(&LargeTable) != 0) { StkPlPrintf("...[NG]\n"); return -1; } for (int i = 0; i < 32; i++) { delete ColDef[i]; } for (int k = 0; k < 16383; k++) { RecordData* RecDat; ColumnData* ColDat[32]; for (int i = 0; i < 32; i++) { wchar_t ColName[16]; wchar_t Val[256] = L""; StkPlSwPrintf(ColName, 16, L"東西南北老若男女焼肉定食愛%d", i); StkPlSwPrintf(Val, 256, L"%d %d :12345", k, i); for (int j = 0; j < 24; j++) { StkPlWcsCat(Val, 256, L"一二三四五六七八九十"); } ColDat[i] = new ColumnDataWStr(ColName, Val); } RecDat = new RecordData(L"焼津沼津辰口町和泉町中田北白楽", ColDat, 32); LockTable(L"焼津沼津辰口町和泉町中田北白楽", 2); if (InsertRecord(RecDat) != 0) { StkPlPrintf("...[NG]\n"); return -1; } UnlockTable(L"焼津沼津辰口町和泉町中田北白楽"); delete RecDat; } StkPlPrintf("...[OK]\n"); } { StkPlPrintf("Records can be acquired from exising table."); LockTable(L"焼津沼津辰口町和泉町中田北白楽", LOCK_SHARE); RecordData* RecDat = GetRecord(L"焼津沼津辰口町和泉町中田北白楽"); UnlockTable(L"焼津沼津辰口町和泉町中田北白楽"); RecordData* CurRecDat = RecDat; StkPlPrintf("Column information can be acquired with column name specification."); do { ColumnDataWStr* ColDat0 = (ColumnDataWStr*)CurRecDat->GetColumn(L"東西南北老若男女焼肉定食愛0"); if (ColDat0 == NULL) { StkPlPrintf("...[NG]\n"); return -1; } wchar_t* ColDat0Value = ColDat0->GetValue(); if (ColDat0Value == NULL || StkPlWcsLen(ColDat0Value) == 0) { StkPlPrintf("...[NG]\n"); return -1; } ColumnDataWStr* ColDat31 = (ColumnDataWStr*)CurRecDat->GetColumn(L"東西南北老若男女焼肉定食愛31"); if (ColDat31 == NULL) { StkPlPrintf("...[NG]\n"); return -1; } wchar_t* ColDat31Value = ColDat0->GetValue(); if (ColDat31Value == NULL || StkPlWcsLen(ColDat31Value) == 0) { StkPlPrintf("...[NG]\n"); return -1; } } while (CurRecDat = CurRecDat->GetNextRecord()); StkPlPrintf("...[OK]\n"); delete RecDat; } { StkPlPrintf("Search records from existing table. Search criteria=WStr:multi+CONTAIN"); ColumnData* ColDat[2]; ColDat[0] = new ColumnDataWStr(L"東西南北老若男女焼肉定食愛2", L"100 2 :"); ColDat[0]->SetComparisonOperator(COMP_CONTAIN); ColDat[1] = new ColumnDataWStr(L"東西南北老若男女焼肉定食愛3", L"100 3 :"); ColDat[1]->SetComparisonOperator(COMP_CONTAIN); RecordData* RecDatSch = new RecordData(L"焼津沼津辰口町和泉町中田北白楽", ColDat, 2); LockTable(L"焼津沼津辰口町和泉町中田北白楽", LOCK_SHARE); RecordData* RecDatRet = GetRecord(RecDatSch); UnlockTable(L"焼津沼津辰口町和泉町中田北白楽"); RecordData* CurRecDat = RecDatRet; do { ColumnDataWStr* ColDat2 = (ColumnDataWStr*)CurRecDat->GetColumn(L"東西南北老若男女焼肉定食愛2"); ColumnDataWStr* ColDat3 = (ColumnDataWStr*)CurRecDat->GetColumn(L"東西南北老若男女焼肉定食愛3"); if (ColDat2 == NULL || ColDat3 == NULL) { StkPlPrintf("...[NG]\n"); return -1; } wchar_t* ColDat0Value2 = ColDat2->GetValue(); wchar_t* ColDat0Value3 = ColDat3->GetValue(); if (StkPlWcsStr(ColDat0Value2, L"100 2 :") == NULL) { StkPlPrintf("...[NG]\n"); return -1; } if (StkPlWcsStr(ColDat0Value3, L"100 3 :") == NULL) { StkPlPrintf("...[NG]\n"); return -1; } } while (CurRecDat = CurRecDat->GetNextRecord()); delete RecDatSch; delete RecDatRet; StkPlPrintf("...[OK]\n"); } { StkPlPrintf("Search records from existing table. Search criteria=WStr:multi+EQUAL(invalid)"); ColumnData* ColDat[1]; ColDat[0] = new ColumnDataWStr(L"東西南北老若男女焼肉定食愛2", L"100 2 :"); ColDat[0]->SetComparisonOperator(COMP_EQUAL); RecordData* RecDatSch = new RecordData(L"焼津沼津辰口町和泉町中田北白楽", ColDat, 1); LockTable(L"焼津沼津辰口町和泉町中田北白楽", LOCK_SHARE); RecordData* RecDatRet = GetRecord(RecDatSch); UnlockTable(L"焼津沼津辰口町和泉町中田北白楽"); if (RecDatRet != NULL) { StkPlPrintf("...[NG]\n"); return -1; } delete RecDatSch; StkPlPrintf("...[OK]\n"); } { StkPlPrintf("Search records from existing table. Search criteria=WStr:multi+NOT CONTAIN"); ColumnData* ColDat[2]; ColDat[0] = new ColumnDataWStr(L"東西南北老若男女焼肉定食愛2", L"100 2 :", COMP_NOT_CONTAIN); ColDat[1] = new ColumnDataWStr(L"東西南北老若男女焼肉定食愛3", L"100 3 :", COMP_NOT_CONTAIN); RecordData* RecDatSch = new RecordData(L"焼津沼津辰口町和泉町中田北白楽", ColDat, 2); LockTable(L"焼津沼津辰口町和泉町中田北白楽", LOCK_SHARE); RecordData* RecDatRet = GetRecord(RecDatSch); UnlockTable(L"焼津沼津辰口町和泉町中田北白楽"); RecordData* CurRecDat = RecDatRet; int NumOfDat = 0; do { ColumnDataWStr* ColDat2 = (ColumnDataWStr*)CurRecDat->GetColumn(L"東西南北老若男女焼肉定食愛2"); ColumnDataWStr* ColDat3 = (ColumnDataWStr*)CurRecDat->GetColumn(L"東西南北老若男女焼肉定食愛3"); if (ColDat2 == NULL || ColDat3 == NULL) { StkPlPrintf("...[NG]\n"); return -1; } wchar_t* ColDat0Value2 = ColDat2->GetValue(); wchar_t* ColDat0Value3 = ColDat3->GetValue(); if (StkPlWcsStr(ColDat0Value2, L"100 2 :") != NULL) { StkPlPrintf("...[NG]\n"); return -1; } if (StkPlWcsStr(ColDat0Value3, L"100 3 :") != NULL) { StkPlPrintf("...[NG]\n"); return -1; } NumOfDat++; } while (CurRecDat = CurRecDat->GetNextRecord()); delete RecDatSch; delete RecDatRet; StkPlPrintf("...%d[OK]\n", NumOfDat); } { StkPlPrintf("Search records from existing table. Search criteria=WStr:multi(invalid)"); ColumnData* ColDat[2]; ColDat[0] = new ColumnDataWStr(L"東西南北老若男女焼肉定食愛2", L"100 2 :", COMP_CONTAIN); ColDat[1] = new ColumnDataWStr(L"東西南北老若男女焼肉定食愛3", L"100 3 :", COMP_NOT_CONTAIN); RecordData* RecDatSch = new RecordData(L"焼津沼津辰口町和泉町中田北白楽", ColDat, 2); LockTable(L"焼津沼津辰口町和泉町中田北白楽", LOCK_SHARE); RecordData* RecDatRet = GetRecord(RecDatSch); UnlockTable(L"焼津沼津辰口町和泉町中田北白楽"); if (RecDatRet != NULL) { StkPlPrintf("...[NG]\n"); return -1; } delete RecDatSch; StkPlPrintf("...[OK]\n"); } { StkPlPrintf("10 records can be acquired from specified table. Connected records are specified."); RecordData* RecDat; RecordData* TopRecDat; RecordData* PrvRecDat; ColumnData* ColDat; for (int i = 0; i < 10; i ++) { wchar_t ColName[16]; wchar_t Val[256] = L""; StkPlSwPrintf(ColName, 16, L"東西南北老若男女焼肉定食愛%d", 0); StkPlSwPrintf(Val, 256, L"%d %d :12345", i, 0); for (int j = 0; j < 24; j++) { StkPlWcsCat(Val, 256, L"一二三四五六七八九十"); } ColDat = new ColumnDataWStr(ColName, Val); RecDat = new RecordData(L"焼津沼津辰口町和泉町中田北白楽", &ColDat, 1); if (i == 0) { TopRecDat = RecDat; } if (i >= 1) { PrvRecDat->SetNextRecord(RecDat); } PrvRecDat = RecDat; } LockTable(L"焼津沼津辰口町和泉町中田北白楽", 2); DeleteRecord(TopRecDat); UnlockTable(L"焼津沼津辰口町和泉町中田北白楽"); delete TopRecDat; if (GetNumOfRecords(L"焼津沼津辰口町和泉町中田北白楽") != 16373) { StkPlPrintf("...[NG]\n"); return -1; } StkPlPrintf("...[OK]\n"); } { StkPlPrintf("-1 is returned if non existing column name is specified to ZaSortRecord."); LockTable(L"焼津沼津辰口町和泉町中田北白楽", LOCK_EXCLUSIVE); if (ZaSortRecord(L"焼津沼津辰口町和泉町中田北白楽", L"aaa") != -1) { StkPlPrintf("...[NG]\n"); return -1; } UnlockTable(L"焼津沼津辰口町和泉町中田北白楽"); StkPlPrintf("...[OK]\n"); } StkPlPrintf("Delete a table which contains large number of records."); if (DeleteTable(L"焼津沼津辰口町和泉町中田北白楽") != 0) { StkPlPrintf("...[NG]\n"); return -1; } StkPlPrintf("...[OK]\n"); return 0; }
31.795181
143
0.662372
7e0671a6332d41f1426f827a417780c062d6f38d
35,068
cpp
C++
earth_enterprise/src/fusion/gst/gstGeometryChecker_unittest.cpp
ezeeyahoo/earthenterprise
b6cac9e6228946f2f17d1edb75e118aeb3e8e8c9
[ "Apache-2.0" ]
2,661
2017-03-20T22:12:50.000Z
2022-03-30T09:43:19.000Z
earth_enterprise/src/fusion/gst/gstGeometryChecker_unittest.cpp
ezeeyahoo/earthenterprise
b6cac9e6228946f2f17d1edb75e118aeb3e8e8c9
[ "Apache-2.0" ]
1,531
2017-03-24T17:20:32.000Z
2022-03-16T18:11:14.000Z
earth_enterprise/src/fusion/gst/gstGeometryChecker_unittest.cpp
ezeeyahoo/earthenterprise
b6cac9e6228946f2f17d1edb75e118aeb3e8e8c9
[ "Apache-2.0" ]
990
2017-03-24T11:54:28.000Z
2022-03-22T11:51:47.000Z
// Copyright 2017 Google 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. // Unit tests for GeometryChecker functionality. #include <gtest/gtest.h> #include <string> #include "fusion/gst/gstVertex.h" #include "fusion/gst/gstGeode.h" #include "fusion/gst/gstMathUtils.h" #include "fusion/gst/gstGeometryChecker.h" #include "fusion/gst/gstUnitTestUtils.h" namespace fusion_gst { // GeometryChecker test class. class GeometryCheckerTest : public testing::Test { protected: // Utility method for checking the result of // RemoveCoincidentVertex()-function. void CheckRemoveCoincidentVertex(const gstGeodeHandle &geodeh, const gstGeodeHandle &expected_geodeh, const std::string &message) const; // Utility method for checking the result of RemoveSpike()-function. void CheckRemoveSpikes(const gstGeodeHandle &geodeh, const gstGeodeHandle &expected_geodeh, const std::string &message) const; // Utility method for checking the result of // CheckAndFixCycleOrientation()-function. void CheckAndFixCycleOrientation(const gstGeodeHandle &geodeh, const gstGeodeHandle &expected_geodeh, const std::string &message) const; private: GeometryChecker checker_; }; // Utility method for checking the result of RemoveCoincidentVertex-function. void GeometryCheckerTest::CheckRemoveCoincidentVertex( const gstGeodeHandle &geodeh, const gstGeodeHandle &expected_geodeh, const std::string &message) const { gstGeodeHandle gh = geodeh->Duplicate(); checker_.RemoveCoincidentVertices(&gh); TestUtils::CompareGeodes(gh, expected_geodeh, message); } // Utility method for checking the result of RemoveSpikes-function. void GeometryCheckerTest::CheckRemoveSpikes( const gstGeodeHandle &geodeh, const gstGeodeHandle &expected_geodeh, const std::string &message) const { gstGeodeHandle gh = geodeh->Duplicate(); checker_.RemoveSpikes(&gh); TestUtils::CompareGeodes(gh, expected_geodeh, message); } // Utility method for checking the result of CheckAndFixCycleOrientation() // -fucntion. void GeometryCheckerTest::CheckAndFixCycleOrientation( const gstGeodeHandle &geodeh, const gstGeodeHandle &expected_geodeh, const std::string &message) const { gstGeodeHandle gh = geodeh->Duplicate(); checker_.CheckAndFixCycleOrientation(&gh); TestUtils::CompareGeodes(gh, expected_geodeh, message); } // Tests RemoveCoincidentVertex-functionality. TEST_F(GeometryCheckerTest, RemoveCoincidentVertexTest) { gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *geode = static_cast<gstGeode*>(&(*geodeh)); gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh)); exp_geode->AddPart(5); exp_geode->AddVertex(gstVertex(0.100, 0.100, .0)); exp_geode->AddVertex(gstVertex(0.220, 0.100, .0)); exp_geode->AddVertex(gstVertex(0.220, 0.200, .0)); exp_geode->AddVertex(gstVertex(0.100, 0.200, .0)); exp_geode->AddVertex(gstVertex(0.100, 0.100, .0)); exp_geode->AddPart(5); exp_geode->AddVertex(gstVertex(0.120, 0.120, .0)); exp_geode->AddVertex(gstVertex(0.120, 0.180, .0)); exp_geode->AddVertex(gstVertex(0.200, 0.180, .0)); exp_geode->AddVertex(gstVertex(0.200, 0.120, .0)); exp_geode->AddVertex(gstVertex(0.120, 0.120, .0)); { geode->Clear(); geode->AddPart(6); geode->AddVertex(gstVertex(0.100, 0.100, .0)); geode->AddVertex(gstVertex(0.100, 0.100, .0)); geode->AddVertex(gstVertex(0.220, 0.100, .0)); geode->AddVertex(gstVertex(0.220, 0.200, .0)); geode->AddVertex(gstVertex(0.100, 0.200, .0)); geode->AddVertex(gstVertex(0.100, 0.100, .0)); geode->AddPart(6); geode->AddVertex(gstVertex(0.120, 0.120, .0)); geode->AddVertex(gstVertex(0.120, 0.120, .0)); geode->AddVertex(gstVertex(0.120, 0.180, .0)); geode->AddVertex(gstVertex(0.200, 0.180, .0)); geode->AddVertex(gstVertex(0.200, 0.120, .0)); geode->AddVertex(gstVertex(0.120, 0.120, .0)); CheckRemoveCoincidentVertex( geodeh, exp_geodeh, "Coincident vertex removing: coincident vertices at the beginning."); } { geode->Clear(); geode->AddPart(6); geode->AddVertex(gstVertex(0.100, 0.100, .0)); geode->AddVertex(gstVertex(0.220, 0.100, .0)); geode->AddVertex(gstVertex(0.220, 0.200, .0)); geode->AddVertex(gstVertex(0.100, 0.200, .0)); geode->AddVertex(gstVertex(0.100, 0.100, .0)); geode->AddVertex(gstVertex(0.100, 0.100, .0)); geode->AddPart(6); geode->AddVertex(gstVertex(0.120, 0.120, .0)); geode->AddVertex(gstVertex(0.120, 0.180, .0)); geode->AddVertex(gstVertex(0.200, 0.180, .0)); geode->AddVertex(gstVertex(0.200, 0.120, .0)); geode->AddVertex(gstVertex(0.120, 0.120, .0)); geode->AddVertex(gstVertex(0.120, 0.120, .0)); CheckRemoveCoincidentVertex( geodeh, exp_geodeh, "Coincident vertex removing: coincident vertices at the end."); } { geode->Clear(); geode->AddPart(8); geode->AddVertex(gstVertex(0.100, 0.100, .0)); geode->AddVertex(gstVertex(0.220, 0.100, .0)); geode->AddVertex(gstVertex(0.220, 0.200, .0)); geode->AddVertex(gstVertex(0.220, 0.200, .0)); geode->AddVertex(gstVertex(0.220, 0.200, .0)); geode->AddVertex(gstVertex(0.100, 0.200, .0)); geode->AddVertex(gstVertex(0.100, 0.200, .0)); geode->AddVertex(gstVertex(0.100, 0.100, .0)); geode->AddPart(8); geode->AddVertex(gstVertex(0.120, 0.120, .0)); geode->AddVertex(gstVertex(0.120, 0.180, .0)); geode->AddVertex(gstVertex(0.120, 0.180, .0)); geode->AddVertex(gstVertex(0.120, 0.180, .0)); geode->AddVertex(gstVertex(0.200, 0.180, .0)); geode->AddVertex(gstVertex(0.200, 0.120, .0)); geode->AddVertex(gstVertex(0.200, 0.120, .0)); geode->AddVertex(gstVertex(0.120, 0.120, .0)); CheckRemoveCoincidentVertex( geodeh, exp_geodeh, "Coincident vertex removing: coincident vertices in the middle."); } { geode->Clear(); geode->AddPart(11); geode->AddVertex(gstVertex(0.100, 0.100, .0)); geode->AddVertex(gstVertex(0.100, 0.100, .0)); geode->AddVertex(gstVertex(0.220, 0.100, .0)); geode->AddVertex(gstVertex(0.220, 0.200, .0)); geode->AddVertex(gstVertex(0.220, 0.200, .0)); geode->AddVertex(gstVertex(0.220, 0.200, .0)); geode->AddVertex(gstVertex(0.100, 0.200, .0)); geode->AddVertex(gstVertex(0.100, 0.200, .0)); geode->AddVertex(gstVertex(0.100, 0.100, .0)); geode->AddVertex(gstVertex(0.100, 0.100, .0)); geode->AddVertex(gstVertex(0.100, 0.100, .0)); geode->AddPart(11); geode->AddVertex(gstVertex(0.120, 0.120, .0)); geode->AddVertex(gstVertex(0.120, 0.120, .0)); geode->AddVertex(gstVertex(0.120, 0.120, .0)); geode->AddVertex(gstVertex(0.120, 0.180, .0)); geode->AddVertex(gstVertex(0.120, 0.180, .0)); geode->AddVertex(gstVertex(0.120, 0.180, .0)); geode->AddVertex(gstVertex(0.200, 0.180, .0)); geode->AddVertex(gstVertex(0.200, 0.120, .0)); geode->AddVertex(gstVertex(0.200, 0.120, .0)); geode->AddVertex(gstVertex(0.120, 0.120, .0)); geode->AddVertex(gstVertex(0.120, 0.120, .0)); CheckRemoveCoincidentVertex( geodeh, exp_geodeh, "Coincident vertex removing: coincident vertices everewhere."); } } // CheckRemoveSpikesTest1 - generic test 1. TEST_F(GeometryCheckerTest, CheckRemoveSpikesTest1) { gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *geode = static_cast<gstGeode*>(&(*geodeh)); gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh)); exp_geode->AddPart(5); exp_geode->AddVertex(gstVertex(0.100, 0.100, .0)); exp_geode->AddVertex(gstVertex(0.220, 0.100, .0)); exp_geode->AddVertex(gstVertex(0.220, 0.200, .0)); exp_geode->AddVertex(gstVertex(0.100, 0.200, .0)); exp_geode->AddVertex(gstVertex(0.100, 0.100, .0)); exp_geode->AddPart(5); exp_geode->AddVertex(gstVertex(0.120, 0.120, .0)); exp_geode->AddVertex(gstVertex(0.120, 0.180, .0)); exp_geode->AddVertex(gstVertex(0.200, 0.180, .0)); exp_geode->AddVertex(gstVertex(0.200, 0.120, .0)); exp_geode->AddVertex(gstVertex(0.120, 0.120, .0)); { geode->Clear(); geode->AddPart(7); geode->AddVertex(gstVertex(0.100, 0.100, .0)); geode->AddVertex(gstVertex(0.320, 0.100, .0)); geode->AddVertex(gstVertex(0.220, 0.100, .0)); geode->AddVertex(gstVertex(0.220, 0.200, .0)); geode->AddVertex(gstVertex(0.100, 0.200, .0)); geode->AddVertex(gstVertex(0.100, 0.50, .0)); geode->AddVertex(gstVertex(0.100, 0.100, .0)); geode->AddPart(7); geode->AddVertex(gstVertex(0.120, 0.120, .0)); geode->AddVertex(gstVertex(0.120, 0.220, .0)); geode->AddVertex(gstVertex(0.120, 0.180, .0)); geode->AddVertex(gstVertex(0.200, 0.180, .0)); geode->AddVertex(gstVertex(0.200, 0.120, .0)); geode->AddVertex(gstVertex(0.050, 0.120, .0)); geode->AddVertex(gstVertex(0.120, 0.120, .0)); CheckRemoveSpikes( geodeh, exp_geodeh, "Spikes removing: generic test 1."); } } // CheckRemoveSpikesTest2 - generic test 2. TEST_F(GeometryCheckerTest, CheckRemoveSpikesTest2) { gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *geode = static_cast<gstGeode*>(&(*geodeh)); gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh)); exp_geode->AddPart(5); exp_geode->AddVertex(gstVertex(0.100, 0.100, .0)); exp_geode->AddVertex(gstVertex(0.220, 0.100, .0)); exp_geode->AddVertex(gstVertex(0.220, 0.200, .0)); exp_geode->AddVertex(gstVertex(0.100, 0.200, .0)); exp_geode->AddVertex(gstVertex(0.100, 0.100, .0)); exp_geode->AddPart(5); exp_geode->AddVertex(gstVertex(0.120, 0.120, .0)); exp_geode->AddVertex(gstVertex(0.120, 0.180, .0)); exp_geode->AddVertex(gstVertex(0.200, 0.180, .0)); exp_geode->AddVertex(gstVertex(0.200, 0.120, .0)); exp_geode->AddVertex(gstVertex(0.120, 0.120, .0)); { geode->Clear(); geode->AddPart(9); geode->AddVertex(gstVertex(0.100, 0.100, .0)); geode->AddVertex(gstVertex(0.320, 0.100, .0)); geode->AddVertex(gstVertex(0.220, 0.100, .0)); geode->AddVertex(gstVertex(0.220, 0.400, .0)); geode->AddVertex(gstVertex(0.220, 0.200, .0)); geode->AddVertex(gstVertex(0.040, 0.200, .0)); geode->AddVertex(gstVertex(0.100, 0.200, .0)); geode->AddVertex(gstVertex(0.100, 0.50, .0)); geode->AddVertex(gstVertex(0.100, 0.100, .0)); geode->AddPart(9); geode->AddVertex(gstVertex(0.120, 0.120, .0)); geode->AddVertex(gstVertex(0.120, 0.220, .0)); geode->AddVertex(gstVertex(0.120, 0.180, .0)); geode->AddVertex(gstVertex(0.350, 0.180, .0)); geode->AddVertex(gstVertex(0.200, 0.180, .0)); geode->AddVertex(gstVertex(0.200, 0.110, .0)); geode->AddVertex(gstVertex(0.200, 0.120, .0)); geode->AddVertex(gstVertex(0.050, 0.120, .0)); geode->AddVertex(gstVertex(0.120, 0.120, .0)); CheckRemoveSpikes( geodeh, exp_geodeh, "Spikes removing: generic test 2."); } } // CheckRemoveSpikesTest3 - generic test 3. TEST_F(GeometryCheckerTest, CheckRemoveSpikesTest3) { gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *geode = static_cast<gstGeode*>(&(*geodeh)); gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh)); exp_geode->AddPart(5); exp_geode->AddVertex(gstVertex(0.100, 0.100, .0)); exp_geode->AddVertex(gstVertex(0.220, 0.220, .0)); exp_geode->AddVertex(gstVertex(0.100, 0.220, .0)); exp_geode->AddVertex(gstVertex(0.100, 0.100, .0)); exp_geode->AddPart(5); exp_geode->AddVertex(gstVertex(0.120, 0.120, .0)); exp_geode->AddVertex(gstVertex(0.160, 0.160, .0)); exp_geode->AddVertex(gstVertex(0.160, 0.120, .0)); exp_geode->AddVertex(gstVertex(0.120, 0.120, .0)); { geode->Clear(); geode->AddPart(7); geode->AddVertex(gstVertex(0.100, 0.100, .0)); geode->AddVertex(gstVertex(0.280, 0.280, .0)); geode->AddVertex(gstVertex(0.220, 0.220, .0)); geode->AddVertex(gstVertex(0.040, 0.220, .0)); geode->AddVertex(gstVertex(0.100, 0.220, .0)); geode->AddVertex(gstVertex(0.100, 0.50, .0)); geode->AddVertex(gstVertex(0.100, 0.100, .0)); geode->AddPart(7); geode->AddVertex(gstVertex(0.120, 0.120, .0)); geode->AddVertex(gstVertex(0.180, 0.180, .0)); geode->AddVertex(gstVertex(0.160, 0.160, .0)); geode->AddVertex(gstVertex(0.160, 0.120, .0)); geode->AddVertex(gstVertex(0.180, 0.120, .0)); geode->AddVertex(gstVertex(0.050, 0.120, .0)); geode->AddVertex(gstVertex(0.120, 0.120, .0)); CheckRemoveSpikes( geodeh, exp_geodeh, "Spikes removing: generic test 3."); } } // CheckRemoveSpikesTest4 - polygon cycles with collinear points. TEST_F(GeometryCheckerTest, CheckRemoveSpikesTest4) { gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *geode = static_cast<gstGeode*>(&(*geodeh)); gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh)); exp_geode->AddPart(5); exp_geode->AddVertex(gstVertex(0.100, 0.100, .0)); exp_geode->AddVertex(gstVertex(0.170, 0.100, .0)); exp_geode->AddVertex(gstVertex(0.220, 0.100, .0)); exp_geode->AddVertex(gstVertex(0.220, 0.150, .0)); exp_geode->AddVertex(gstVertex(0.220, 0.200, .0)); exp_geode->AddVertex(gstVertex(0.180, 0.200, .0)); exp_geode->AddVertex(gstVertex(0.100, 0.200, .0)); exp_geode->AddVertex(gstVertex(0.100, 0.130, .0)); exp_geode->AddVertex(gstVertex(0.100, 0.100, .0)); exp_geode->AddPart(5); exp_geode->AddVertex(gstVertex(0.120, 0.120, .0)); exp_geode->AddVertex(gstVertex(0.120, 0.140, .0)); exp_geode->AddVertex(gstVertex(0.120, 0.180, .0)); exp_geode->AddVertex(gstVertex(0.170, 0.180, .0)); exp_geode->AddVertex(gstVertex(0.200, 0.180, .0)); exp_geode->AddVertex(gstVertex(0.200, 0.145, .0)); exp_geode->AddVertex(gstVertex(0.200, 0.120, .0)); exp_geode->AddVertex(gstVertex(0.135, 0.120, .0)); exp_geode->AddVertex(gstVertex(0.120, 0.120, .0)); { geode->Clear(); geode->AddPart(7); geode->AddVertex(gstVertex(0.100, 0.100, .0)); geode->AddVertex(gstVertex(0.170, 0.100, .0)); geode->AddVertex(gstVertex(0.320, 0.100, .0)); geode->AddVertex(gstVertex(0.220, 0.100, .0)); geode->AddVertex(gstVertex(0.220, 0.150, .0)); geode->AddVertex(gstVertex(0.220, 0.200, .0)); geode->AddVertex(gstVertex(0.180, 0.200, .0)); geode->AddVertex(gstVertex(0.100, 0.200, .0)); geode->AddVertex(gstVertex(0.100, 0.130, .0)); geode->AddVertex(gstVertex(0.100, 0.050, .0)); geode->AddVertex(gstVertex(0.100, 0.100, .0)); geode->AddPart(7); geode->AddVertex(gstVertex(0.120, 0.120, .0)); geode->AddVertex(gstVertex(0.120, 0.140, .0)); geode->AddVertex(gstVertex(0.120, 0.220, .0)); geode->AddVertex(gstVertex(0.120, 0.180, .0)); geode->AddVertex(gstVertex(0.170, 0.180, .0)); geode->AddVertex(gstVertex(0.200, 0.180, .0)); geode->AddVertex(gstVertex(0.200, 0.145, .0)); geode->AddVertex(gstVertex(0.200, 0.120, .0)); geode->AddVertex(gstVertex(0.135, 0.120, .0)); geode->AddVertex(gstVertex(0.050, 0.120, .0)); geode->AddVertex(gstVertex(0.120, 0.120, .0)); CheckRemoveSpikes( geodeh, exp_geodeh, "Spikes removing: collinear points test."); } } // CheckRemoveSpikesTest5 - small triangle from real data set. TEST_F(GeometryCheckerTest, CheckRemoveSpikesTest5) { gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *geode = static_cast<gstGeode*>(&(*geodeh)); gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh)); gstVertex pt1 = gstVertex( khTilespaceBase::Normalize(-90.6035304620), khTilespaceBase::Normalize(34.9918161022), .0); gstVertex pt2 = gstVertex( khTilespaceBase::Normalize(-90.6035310000), khTilespaceBase::Normalize(34.9918180000), .0); gstVertex pt3 = gstVertex( khTilespaceBase::Normalize(-90.6035342156), khTilespaceBase::Normalize(34.9918172140), .0); exp_geode->AddPart(4); exp_geode->AddVertex(pt1); exp_geode->AddVertex(pt2); exp_geode->AddVertex(pt3); exp_geode->AddVertex(pt1); { geode->Clear(); geode->AddPart(4); geode->AddVertex(pt1); geode->AddVertex(pt2); geode->AddVertex(pt3); geode->AddVertex(pt1); CheckRemoveSpikes( geodeh, exp_geodeh, "Spikes removing: small triangle from real data set."); } } // CheckRemoveSpikesTest6 - polygon w/ spike from real data set 1. TEST_F(GeometryCheckerTest, CheckRemoveSpikesTest6) { gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *geode = static_cast<gstGeode*>(&(*geodeh)); gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh)); gstVertex pt1 = gstVertex( khTilespaceBase::Normalize(106.8182506368), khTilespaceBase::Normalize(10.6542182242), .0); gstVertex pt2 = gstVertex( khTilespaceBase::Normalize(106.8124851861), khTilespaceBase::Normalize(10.6542509147), .0); gstVertex pt3 = gstVertex( khTilespaceBase::Normalize(106.8155637637), khTilespaceBase::Normalize(10.6542318523), .0); gstVertex pt4 = gstVertex( khTilespaceBase::Normalize(106.8159899627), khTilespaceBase::Normalize(10.6527421661), .0); exp_geode->AddPart(5); exp_geode->AddVertex(pt1); // exp_geode->AddVertex(pt2); // spike vertex. exp_geode->AddVertex(pt3); exp_geode->AddVertex(pt4); exp_geode->AddVertex(pt1); { geode->Clear(); geode->AddPart(5); geode->AddVertex(pt1); geode->AddVertex(pt2); geode->AddVertex(pt3); geode->AddVertex(pt4); geode->AddVertex(pt1); CheckRemoveSpikes( geodeh, exp_geodeh, "Spikes removing: polygon w/ spike from real data set 1."); } } // CheckRemoveSpikesTest7 - polygon w/ spike from real data set 2. TEST_F(GeometryCheckerTest, CheckRemoveSpikesTest7) { gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *geode = static_cast<gstGeode*>(&(*geodeh)); gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh)); gstVertex pt1 = gstVertex( khTilespaceBase::Normalize(-8.9993160617), khTilespaceBase::Normalize(43.2081516536), .0); gstVertex pt2 = gstVertex( khTilespaceBase::Normalize(-8.9994751791), khTilespaceBase::Normalize(43.2077953989), .0); gstVertex pt3 = gstVertex( khTilespaceBase::Normalize(-8.9994724853), khTilespaceBase::Normalize(43.2078014303), .0); gstVertex pt4 = gstVertex( khTilespaceBase::Normalize(-8.9993440068), khTilespaceBase::Normalize(43.2074263067), .0); exp_geode->AddPart(5); exp_geode->AddVertex(pt1); // exp_geode->AddVertex(pt2); // spike vertex. exp_geode->AddVertex(pt3); exp_geode->AddVertex(pt4); exp_geode->AddVertex(pt1); { geode->Clear(); geode->AddPart(5); geode->AddVertex(pt1); geode->AddVertex(pt2); geode->AddVertex(pt3); geode->AddVertex(pt4); geode->AddVertex(pt1); CheckRemoveSpikes( geodeh, exp_geodeh, "Spikes removing: simple polygon w/ spike from real data set 2."); } } // CheckRemoveSpikesTest8 - collinear vertices at the end of cycle. TEST_F(GeometryCheckerTest, CheckRemoveSpikesTest8) { gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *geode = static_cast<gstGeode*>(&(*geodeh)); gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh)); exp_geode->AddPart(5); exp_geode->AddVertex(gstVertex(0.100, 0.100, .0)); exp_geode->AddVertex(gstVertex(0.220, 0.100, .0)); exp_geode->AddVertex(gstVertex(0.220, 0.200, .0)); exp_geode->AddVertex(gstVertex(0.100, 0.200, .0)); exp_geode->AddVertex(gstVertex(0.100, 0.100, .0)); { geode->Clear(); geode->AddPart(9); geode->AddVertex(gstVertex(0.100, 0.100, .0)); geode->AddVertex(gstVertex(0.220, 0.100, .0)); geode->AddVertex(gstVertex(0.320, 0.100, .0)); geode->AddVertex(gstVertex(0.220, 0.100, .0)); geode->AddVertex(gstVertex(0.220, 0.200, .0)); geode->AddVertex(gstVertex(0.100, 0.200, .0)); geode->AddVertex(gstVertex(0.100, 0.100, .0)); geode->AddVertex(gstVertex(0.100, 0.50, .0)); geode->AddVertex(gstVertex(0.100, 0.100, .0)); CheckRemoveSpikes( geodeh, exp_geodeh, "Spikes removing: collinear vertices at the end of cycle 8."); } } // CheckAndFixCycleOrientationTest1 - single-part geode with correct // orientation - rectangle. TEST_F(GeometryCheckerTest, CheckAndFixCycleOrientationTest1) { gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *geode = static_cast<gstGeode*>(&(*geodeh)); gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh)); exp_geode->AddPart(5); exp_geode->AddVertex(gstVertex(0.100, 0.100, .0)); exp_geode->AddVertex(gstVertex(0.220, 0.100, .0)); exp_geode->AddVertex(gstVertex(0.220, 0.200, .0)); exp_geode->AddVertex(gstVertex(0.100, 0.200, .0)); exp_geode->AddVertex(gstVertex(0.100, 0.100, .0)); { geode->Clear(); geode->AddPart(5); geode->AddVertex(gstVertex(0.100, 0.100, .0)); geode->AddVertex(gstVertex(0.220, 0.100, .0)); geode->AddVertex(gstVertex(0.220, 0.200, .0)); geode->AddVertex(gstVertex(0.100, 0.200, .0)); geode->AddVertex(gstVertex(0.100, 0.100, .0)); CheckAndFixCycleOrientation( geodeh, exp_geodeh, "CheckAndFix cycle orientation: single-part geode with correct" " orientation - rectangle."); } } // CheckAndFixCycleOrientationTest2 - single-part geode with correct // orientation - obtuse angle is incident to most left-lower vertex. TEST_F(GeometryCheckerTest, CheckAndFixCycleOrientationTest2) { gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *geode = static_cast<gstGeode*>(&(*geodeh)); gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh)); exp_geode->AddPart(5); exp_geode->AddVertex(gstVertex(0.100, 0.100, .0)); exp_geode->AddVertex(gstVertex(0.220, 0.050, .0)); exp_geode->AddVertex(gstVertex(0.220, 0.200, .0)); exp_geode->AddVertex(gstVertex(0.100, 0.200, .0)); exp_geode->AddVertex(gstVertex(0.100, 0.100, .0)); { geode->Clear(); geode->AddPart(5); geode->AddVertex(gstVertex(0.100, 0.100, .0)); geode->AddVertex(gstVertex(0.220, 0.050, .0)); geode->AddVertex(gstVertex(0.220, 0.200, .0)); geode->AddVertex(gstVertex(0.100, 0.200, .0)); geode->AddVertex(gstVertex(0.100, 0.100, .0)); CheckAndFixCycleOrientation( geodeh, exp_geodeh, "CheckAndFix cycle orientation: single-part geode with correct" " orientation and obtuse angle 1."); } } // CheckAndFixCycleOrientationTest3 - single-part geode with correct // orientation - obtuse angle is incident to most left-lower vertex. TEST_F(GeometryCheckerTest, CheckAndFixCycleOrientationTest3) { gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *geode = static_cast<gstGeode*>(&(*geodeh)); gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh)); exp_geode->AddPart(5); exp_geode->AddVertex(gstVertex(0.100, 0.100, .0)); exp_geode->AddVertex(gstVertex(0.220, 0.050, .0)); exp_geode->AddVertex(gstVertex(0.220, 0.200, .0)); exp_geode->AddVertex(gstVertex(0.050, 0.200, .0)); exp_geode->AddVertex(gstVertex(0.100, 0.100, .0)); { geode->Clear(); geode->AddPart(6); geode->AddVertex(gstVertex(0.100, 0.100, .0)); geode->AddVertex(gstVertex(0.220, 0.050, .0)); geode->AddVertex(gstVertex(0.220, 0.200, .0)); geode->AddVertex(gstVertex(0.050, 0.200, .0)); geode->AddVertex(gstVertex(0.100, 0.100, .0)); CheckAndFixCycleOrientation( geodeh, exp_geodeh, "CheckAndFix cycle orientation: single-part geode with correct" " orientation and obtuse angle 2."); } } // CheckAndFixCycleOrientationTest4 - single-part geode with incorrect // orientation - rectangle. TEST_F(GeometryCheckerTest, CheckAndFixCycleOrientationTest4) { gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *geode = static_cast<gstGeode*>(&(*geodeh)); gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh)); exp_geode->AddPart(5); exp_geode->AddVertex(gstVertex(0.120, 0.120, .0)); exp_geode->AddVertex(gstVertex(0.200, 0.120, .0)); exp_geode->AddVertex(gstVertex(0.200, 0.180, .0)); exp_geode->AddVertex(gstVertex(0.120, 0.180, .0)); exp_geode->AddVertex(gstVertex(0.120, 0.120, .0)); { geode->Clear(); geode->AddPart(5); geode->AddVertex(gstVertex(0.120, 0.120, .0)); geode->AddVertex(gstVertex(0.120, 0.180, .0)); geode->AddVertex(gstVertex(0.200, 0.180, .0)); geode->AddVertex(gstVertex(0.200, 0.120, .0)); geode->AddVertex(gstVertex(0.120, 0.120, .0)); CheckAndFixCycleOrientation( geodeh, exp_geodeh, "CheckAndFix cycle orientation: single-part geode with incorrect" " orientation - rectangle."); } } // CheckAndFixCycleOrientationTest5 - single-part geode with incorrect // orientation - obtuse angle is incident to most left-lower vertex. TEST_F(GeometryCheckerTest, CheckAndFixCycleOrientationTest5) { gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *geode = static_cast<gstGeode*>(&(*geodeh)); gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh)); exp_geode->AddPart(5); exp_geode->AddVertex(gstVertex(0.120, 0.120, .0)); exp_geode->AddVertex(gstVertex(0.200, 0.120, .0)); exp_geode->AddVertex(gstVertex(0.200, 0.180, .0)); exp_geode->AddVertex(gstVertex(0.60, 0.180, .0)); exp_geode->AddVertex(gstVertex(0.120, 0.120, .0)); { geode->Clear(); geode->AddPart(5); geode->AddVertex(gstVertex(0.120, 0.120, .0)); geode->AddVertex(gstVertex(0.60, 0.180, .0)); geode->AddVertex(gstVertex(0.200, 0.180, .0)); geode->AddVertex(gstVertex(0.200, 0.120, .0)); geode->AddVertex(gstVertex(0.120, 0.120, .0)); CheckAndFixCycleOrientation( geodeh, exp_geodeh, "CheckAndFix cycle orientation: single-part geode with incorrect" " orientation - obtuse angle."); } } // CheckAndFixCycleOrientationTest6 - single-part geode with incorrect // orientation - acute angle is incident to most left lower vertex. TEST_F(GeometryCheckerTest, CheckAndFixCycleOrientationTest6) { gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *geode = static_cast<gstGeode*>(&(*geodeh)); gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh)); exp_geode->AddPart(5); exp_geode->AddVertex(gstVertex(0.120, 0.120, .0)); exp_geode->AddVertex(gstVertex(0.200, 0.120, .0)); exp_geode->AddVertex(gstVertex(0.200, 0.180, .0)); exp_geode->AddVertex(gstVertex(0.180, 0.180, .0)); exp_geode->AddVertex(gstVertex(0.120, 0.120, .0)); { geode->Clear(); geode->AddPart(5); geode->AddVertex(gstVertex(0.120, 0.120, .0)); geode->AddVertex(gstVertex(0.180, 0.180, .0)); geode->AddVertex(gstVertex(0.200, 0.180, .0)); geode->AddVertex(gstVertex(0.200, 0.120, .0)); geode->AddVertex(gstVertex(0.120, 0.120, .0)); CheckAndFixCycleOrientation( geodeh, exp_geodeh, "CheckAndFix cycle orientation: single-part geode with incorrect" " orientation - acute angle 1."); } } // CheckAndFixCycleOrientationTest7 - single-part geode with incorrect // orientation - acute angle is incident to most left lower vertex. TEST_F(GeometryCheckerTest, CheckAndFixCycleOrientationTest7) { gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *geode = static_cast<gstGeode*>(&(*geodeh)); gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh)); exp_geode->AddPart(5); exp_geode->AddVertex(gstVertex(0.120, 0.120, .0)); exp_geode->AddVertex(gstVertex(0.200, 0.160, .0)); exp_geode->AddVertex(gstVertex(0.200, 0.180, .0)); exp_geode->AddVertex(gstVertex(0.180, 0.180, .0)); exp_geode->AddVertex(gstVertex(0.120, 0.120, .0)); { geode->Clear(); geode->AddPart(5); geode->AddVertex(gstVertex(0.120, 0.120, .0)); geode->AddVertex(gstVertex(0.180, 0.180, .0)); geode->AddVertex(gstVertex(0.200, 0.180, .0)); geode->AddVertex(gstVertex(0.200, 0.160, .0)); geode->AddVertex(gstVertex(0.120, 0.120, .0)); CheckAndFixCycleOrientation( geodeh, exp_geodeh, "CheckAndFix cycle orientation: single-part geode with incorrect" " orientation - acute angle 2."); } } // CheckAndFixCycleOrientationTest8 - single-part geode with incorrect // orientation - right angle is incident to most left lower vertex. TEST_F(GeometryCheckerTest, CheckAndFixCycleOrientationTest8) { gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *geode = static_cast<gstGeode*>(&(*geodeh)); gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh)); exp_geode->AddPart(5); exp_geode->AddVertex(gstVertex(0.120, 0.120, .0)); exp_geode->AddVertex(gstVertex(0.200, .0, .0)); exp_geode->AddVertex(gstVertex(0.200, 0.180, .0)); exp_geode->AddVertex(gstVertex(0.180, 0.180, .0)); exp_geode->AddVertex(gstVertex(0.120, 0.120, .0)); { geode->Clear(); geode->AddPart(5); geode->AddVertex(gstVertex(0.120, 0.120, .0)); geode->AddVertex(gstVertex(0.180, 0.180, .0)); geode->AddVertex(gstVertex(0.200, 0.180, .0)); geode->AddVertex(gstVertex(0.200, .0, .0)); geode->AddVertex(gstVertex(0.120, 0.120, .0)); CheckAndFixCycleOrientation( geodeh, exp_geodeh, "CheckAndFix cycle orientation: single-part geode with incorrect" " orientation - right angle."); } } // CheckAndFixCycleOrientationMultiPartGeodeTest1 - multi-part geode with // incorrect orientation - rectangles. TEST_F(GeometryCheckerTest, CheckAndFixCycleOrientationMultiPartGeodeTest1) { gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *geode = static_cast<gstGeode*>(&(*geodeh)); gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh)); exp_geode->AddPart(5); exp_geode->AddVertex(gstVertex(0.020, 0.050, .0)); exp_geode->AddVertex(gstVertex(0.400, 0.050, .0)); exp_geode->AddVertex(gstVertex(0.400, 0.400, .0)); exp_geode->AddVertex(gstVertex(0.020, 0.400, .0)); exp_geode->AddVertex(gstVertex(0.020, 0.050, .0)); exp_geode->AddPart(5); exp_geode->AddVertex(gstVertex(0.120, 0.120, .0)); exp_geode->AddVertex(gstVertex(0.120, 0.180, .0)); exp_geode->AddVertex(gstVertex(0.200, 0.180, .0)); exp_geode->AddVertex(gstVertex(0.200, 0.120, .0)); exp_geode->AddVertex(gstVertex(0.120, 0.120, .0)); { geode->Clear(); geode->AddPart(5); geode->AddVertex(gstVertex(0.020, 0.050, .0)); geode->AddVertex(gstVertex(0.020, 0.400, .0)); geode->AddVertex(gstVertex(0.400, 0.400, .0)); geode->AddVertex(gstVertex(0.400, 0.050, .0)); geode->AddVertex(gstVertex(0.020, 0.050, .0)); geode->AddPart(5); geode->AddVertex(gstVertex(0.120, 0.120, .0)); geode->AddVertex(gstVertex(0.200, 0.120, .0)); geode->AddVertex(gstVertex(0.200, 0.180, .0)); geode->AddVertex(gstVertex(0.120, 0.180, .0)); geode->AddVertex(gstVertex(0.120, 0.120, .0)); CheckAndFixCycleOrientation( geodeh, exp_geodeh, "CheckAndFix cycle orientation: multi-part geode with incorrect" " orientation - rectangles."); } } // CheckAndFixCycleOrientationMultiPartGeodeTest2 - multi-part geode with // incorrect orientation - acute/obtuse angles are incident to most left // lower vertex. TEST_F(GeometryCheckerTest, CheckAndFixCycleOrientationMultiPartGeodeTest2) { gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *geode = static_cast<gstGeode*>(&(*geodeh)); gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon); gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh)); exp_geode->AddPart(5); exp_geode->AddVertex(gstVertex(0.010, 0.020, .0)); exp_geode->AddVertex(gstVertex(0.400, 0.050, .0)); exp_geode->AddVertex(gstVertex(0.400, 0.400, .0)); exp_geode->AddVertex(gstVertex(0.020, 0.400, .0)); exp_geode->AddVertex(gstVertex(0.010, 0.020, .0)); exp_geode->AddPart(5); exp_geode->AddVertex(gstVertex(0.120, 0.120, .0)); exp_geode->AddVertex(gstVertex(0.050, 0.150, .0)); exp_geode->AddVertex(gstVertex(0.200, 0.180, .0)); exp_geode->AddVertex(gstVertex(0.200, 0.120, .0)); exp_geode->AddVertex(gstVertex(0.120, 0.120, .0)); { geode->Clear(); geode->AddPart(5); geode->AddVertex(gstVertex(0.010, 0.020, .0)); geode->AddVertex(gstVertex(0.020, 0.400, .0)); geode->AddVertex(gstVertex(0.400, 0.400, .0)); geode->AddVertex(gstVertex(0.400, 0.050, .0)); geode->AddVertex(gstVertex(0.010, 0.020, .0)); geode->AddPart(5); geode->AddVertex(gstVertex(0.120, 0.120, .0)); geode->AddVertex(gstVertex(0.200, 0.120, .0)); geode->AddVertex(gstVertex(0.200, 0.180, .0)); geode->AddVertex(gstVertex(0.050, 0.150, .0)); geode->AddVertex(gstVertex(0.120, 0.120, .0)); CheckAndFixCycleOrientation( geodeh, exp_geodeh, "CheckAndFix cycle orientation: multi-part geode with incorrect" " orientation - acute/obtuse angles."); } } } // namespace fusion_gst int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
35.820225
77
0.678767
7e0765782b6bd26a518cb85d5d7cc059157aefbb
1,148
hpp
C++
_engine/code/include/global/component/profiler.hpp
Shelim/pixie_engine
bf1d80f3f03bd3d6890f4dfc63440f7dd0ff34a1
[ "MIT" ]
null
null
null
_engine/code/include/global/component/profiler.hpp
Shelim/pixie_engine
bf1d80f3f03bd3d6890f4dfc63440f7dd0ff34a1
[ "MIT" ]
null
null
null
_engine/code/include/global/component/profiler.hpp
Shelim/pixie_engine
bf1d80f3f03bd3d6890f4dfc63440f7dd0ff34a1
[ "MIT" ]
null
null
null
#ifndef ENGINE_GLOBAL_COMPONENT_PROFILER_HPP #define ENGINE_GLOBAL_COMPONENT_PROFILER_HPP #pragma once #include "utility/text/ustring.hpp" namespace engine { class profiler_t { public: virtual ~profiler_t() { } virtual void prof_begin_section(const char * name) { } virtual void prof_end_section() { } virtual void name_current_thread(const ustring_t & name) { } class section_t { public: section_t(std::shared_ptr<profiler_t> profiler, const char * name) : profiler(profiler) { profiler->prof_begin_section(name); } ~section_t() { profiler->prof_end_section(); } private: std::shared_ptr<profiler_t> profiler; }; }; } #define prof_function(profiler) engine::profiler_t::section_t _function_section_at_##__LINE__(profiler, __FUNCTION__) #include "global/component/profiler/dummy.hpp" #include "global/component/profiler/real.hpp" #endif
17.661538
117
0.577526
7e086850a54e4560c0bc1ff6f6ab4de9098222e9
2,803
hxx
C++
src/control/genai/c_frontal.hxx
AltSysrq/Abendstern
106e1ad2457f7bfd90080eecf49a33f6079f8e1e
[ "BSD-3-Clause" ]
null
null
null
src/control/genai/c_frontal.hxx
AltSysrq/Abendstern
106e1ad2457f7bfd90080eecf49a33f6079f8e1e
[ "BSD-3-Clause" ]
null
null
null
src/control/genai/c_frontal.hxx
AltSysrq/Abendstern
106e1ad2457f7bfd90080eecf49a33f6079f8e1e
[ "BSD-3-Clause" ]
1
2022-01-29T11:54:41.000Z
2022-01-29T11:54:41.000Z
/** * @file * @author Jason Lingle * @brief Contains the FrontalCortex */ /* * c_frontal.hxx * * Created on: 02.11.2011 * Author: jason */ #ifndef C_FRONTAL_HXX_ #define C_FRONTAL_HXX_ #include "src/sim/objdl.hxx" #include "cortex.hxx" #include "ci_nil.hxx" #include "ci_self.hxx" #include "ci_objective.hxx" class GameObject; class Ship; /** * The FrontalCortex examines possible objectives and returns the one * given the highest score. * * All FrontalCortices maintain a global telepathy map of * (insignia,objective) --> cortices... */ class FrontalCortex: public Cortex, private cortex_input::Self <cortex_input::Objective <cortex_input::Nil> > { Ship*const ship; ObjDL objective; float objectiveScore; //Telepathy output const float distanceParm, scoreWeightParm, dislikeWeightParm, happyWeightParm; //The last known insignia of the ship //(Specifically, the insignia when we inserted ourselves // into the global map). //0 indicates not inserted unsigned long insertedInsignia; //The GameObject* used to insert us into the global map. //This may be a dangling pointer, never dereference GameObject* insertedObjective; //Milliseconds until the next scan float timeUntilRescan; //Add the opriority, ocurr, and otel inputs static const unsigned cipe_last = cip_last+3, cip_opriority = cip_last, cip_ocurr = cip_last+1, cip_otel = cip_last+2; enum Output { target = 0 }; static const unsigned numOutputs = 1+(unsigned)target; public: class input_map: public cip_input_map { public: input_map() { ins("opriority", cip_opriority); ins("ocurr", cip_ocurr); ins("otel", cip_otel); } }; /** Gives instructions on how to proceed */ struct Directive { /** The objective to persue. * If NULL, park. */ GameObject* objective; /** What to do to the objective. */ enum Mode { Attack, /// Proceed with the attack series of cortices Navigate /// Phoceed with the Navigation cortex } mode; }; /** * Constructs a new SelfSource. * @param species The root of the species data to read from * @param s The Ship to operate on * @param ss The SelfSource to use */ FrontalCortex(const libconfig::Setting& species, Ship* s, cortex_input::SelfSource* ss); ~FrontalCortex(); /** * Evaluates the cortex and returns its decision, given te elapsed time. */ Directive evaluate(float); /** Returns the score of the cortex. */ float getScore() const; private: //Remove from global multimap if inserted void unmap(); //Insert to global multimap; //if inserted, unmap first. //Does nothing if no objective. void mapins(); }; #endif /* C_FRONTAL_HXX_ */
24.80531
90
0.674278
7e0960ec09e3cb190439b783fe4f7141de760acb
2,479
cpp
C++
Infinit/src/Platform/OpenGL/OpenGLFrameBuffer.cpp
J4m3s00/Infinit
dd877100f8529e4a97c13f0d179b356800ef2eb9
[ "Apache-2.0" ]
null
null
null
Infinit/src/Platform/OpenGL/OpenGLFrameBuffer.cpp
J4m3s00/Infinit
dd877100f8529e4a97c13f0d179b356800ef2eb9
[ "Apache-2.0" ]
6
2019-07-03T14:21:06.000Z
2019-12-22T12:37:56.000Z
Infinit/src/Platform/OpenGL/OpenGLFrameBuffer.cpp
J4m3s00/Infinit
dd877100f8529e4a97c13f0d179b356800ef2eb9
[ "Apache-2.0" ]
null
null
null
#include "inpch.h" namespace Infinit { OpenGLFrameBuffer::OpenGLFrameBuffer(uint width, uint height, FramebufferFormat format) : m_Format(format), m_Width(0), m_Height(0), m_RendererID(0) { Resize(width, height); } OpenGLFrameBuffer::~OpenGLFrameBuffer() { } void OpenGLFrameBuffer::Resize(uint width, uint height) { if (width == m_Width && height == m_Height) return; m_Width = width; m_Height = height; if (m_RendererID) { IN_RENDER_S({ glDeleteFramebuffers(1, &self->m_RendererID); glDeleteTextures(1, &self->m_ColorAttachment); glDeleteTextures(1, &self->m_DepthAttachment); }) } IN_RENDER_S({ glGenFramebuffers(1, &self->m_RendererID); glBindFramebuffer(GL_FRAMEBUFFER, self->m_RendererID); glGenTextures(1, &self->m_ColorAttachment); glBindTexture(GL_TEXTURE_2D, self->m_ColorAttachment); if (self->m_Format == FramebufferFormat::RGBA16F) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, self->m_Width, self->m_Height, 0, GL_RGBA, GL_FLOAT, nullptr); } else if (self->m_Format == FramebufferFormat::RGBA8) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, self->m_Width, self->m_Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, self->m_ColorAttachment, 0); glGenTextures(1, &self->m_DepthAttachment); glBindTexture(GL_TEXTURE_2D, self->m_DepthAttachment); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, self->m_Width, self->m_Height, 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, NULL); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, self->m_DepthAttachment, 0); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) IN_CORE_ERROR("Framebuffer is incomplete!"); glBindFramebuffer(GL_FRAMEBUFFER, 0); }) } void OpenGLFrameBuffer::Bind() const { IN_RENDER_S({ glBindFramebuffer(GL_FRAMEBUFFER, self->m_RendererID); glViewport(0, 0, self->m_Width, self->m_Height); }) } void OpenGLFrameBuffer::Unbind() const { IN_RENDER({ glBindFramebuffer(GL_FRAMEBUFFER, 0); }) } void OpenGLFrameBuffer::BindTexture(uint slot) const { IN_RENDER_S1(slot, { glActiveTexture(GL_TEXTURE0 + slot); glBindTexture(GL_TEXTURE_2D, self->m_ColorAttachment); }) } }
28.170455
135
0.736587
7e182c2caf9e70471094294efe271e0b5c274604
10,961
cc
C++
chrome/browser/extensions/api/bluetooth/bluetooth_api.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
1
2019-04-23T15:57:04.000Z
2019-04-23T15:57:04.000Z
chrome/browser/extensions/api/bluetooth/bluetooth_api.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/extensions/api/bluetooth/bluetooth_api.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 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. #include "chrome/browser/extensions/api/bluetooth/bluetooth_api.h" #include "base/utf_string_conversions.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/extensions/api/experimental_bluetooth.h" #include "content/public/browser/browser_thread.h" #if defined(OS_CHROMEOS) #include "base/memory/ref_counted.h" #include "base/safe_strerror_posix.h" #include "base/synchronization/lock.h" #include "chrome/browser/chromeos/bluetooth/bluetooth_adapter.h" #include "chrome/browser/chromeos/bluetooth/bluetooth_device.h" #include "chrome/browser/chromeos/bluetooth/bluetooth_socket.h" #include "chrome/browser/chromeos/extensions/bluetooth_event_router.h" #include <errno.h> using chromeos::BluetoothAdapter; using chromeos::BluetoothDevice; namespace { chromeos::ExtensionBluetoothEventRouter* GetEventRouter(Profile* profile) { return profile->GetExtensionService()->bluetooth_event_router(); } const chromeos::BluetoothAdapter* GetAdapter(Profile* profile) { return GetEventRouter(profile)->adapter(); } chromeos::BluetoothAdapter* GetMutableAdapter(Profile* profile) { return GetEventRouter(profile)->GetMutableAdapter(); } } // namespace #endif namespace { const char kSocketNotFoundError[] = "Socket not found: invalid socket id"; } // namespace namespace Connect = extensions::api::experimental_bluetooth::Connect; namespace Disconnect = extensions::api::experimental_bluetooth::Disconnect; namespace GetDevicesWithServiceName = extensions::api::experimental_bluetooth::GetDevicesWithServiceName; namespace GetDevicesWithServiceUUID = extensions::api::experimental_bluetooth::GetDevicesWithServiceUUID; namespace Read = extensions::api::experimental_bluetooth::Read; namespace Write = extensions::api::experimental_bluetooth::Write; namespace extensions { namespace api { #if defined(OS_CHROMEOS) bool BluetoothIsAvailableFunction::RunImpl() { result_.reset(Value::CreateBooleanValue(GetAdapter(profile())->IsPresent())); return true; } bool BluetoothIsPoweredFunction::RunImpl() { result_.reset(Value::CreateBooleanValue(GetAdapter(profile())->IsPowered())); return true; } bool BluetoothGetAddressFunction::RunImpl() { result_.reset(Value::CreateStringValue(GetAdapter(profile())->address())); return true; } bool BluetoothGetDevicesWithServiceUUIDFunction::RunImpl() { scoped_ptr<GetDevicesWithServiceUUID::Params> params( GetDevicesWithServiceUUID::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); const BluetoothAdapter::ConstDeviceList& devices = GetAdapter(profile())->GetDevices(); ListValue* matches = new ListValue; for (BluetoothAdapter::ConstDeviceList::const_iterator i = devices.begin(); i != devices.end(); ++i) { if ((*i)->ProvidesServiceWithUUID(params->uuid)) { experimental_bluetooth::Device device; device.name = UTF16ToUTF8((*i)->GetName()); device.address = (*i)->address(); matches->Append(device.ToValue().release()); } } result_.reset(matches); return true; } BluetoothGetDevicesWithServiceNameFunction:: BluetoothGetDevicesWithServiceNameFunction() : callbacks_pending_(0) {} void BluetoothGetDevicesWithServiceNameFunction::AddDeviceIfTrue( ListValue* list, const BluetoothDevice* device, bool result) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); if (result) { experimental_bluetooth::Device device_result; device_result.name = UTF16ToUTF8(device->GetName()); device_result.address = device->address(); list->Append(device_result.ToValue().release()); } callbacks_pending_--; if (callbacks_pending_ == 0) { SendResponse(true); Release(); // Added in RunImpl } } bool BluetoothGetDevicesWithServiceNameFunction::RunImpl() { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); ListValue* matches = new ListValue; result_.reset(matches); BluetoothAdapter::DeviceList devices = GetMutableAdapter(profile())->GetDevices(); if (devices.empty()) { SendResponse(true); return true; } callbacks_pending_ = devices.size(); AddRef(); // Released in AddDeviceIfTrue when callbacks_pending_ == 0 scoped_ptr<GetDevicesWithServiceName::Params> params( GetDevicesWithServiceName::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); for (BluetoothAdapter::DeviceList::iterator i = devices.begin(); i != devices.end(); ++i) { (*i)->ProvidesServiceWithName(params->name, base::Bind(&BluetoothGetDevicesWithServiceNameFunction::AddDeviceIfTrue, this, matches, *i)); } return true; } void BluetoothConnectFunction::ConnectToServiceCallback( const chromeos::BluetoothDevice* device, const std::string& service_uuid, scoped_refptr<chromeos::BluetoothSocket> socket) { if (socket.get()) { int socket_id = GetEventRouter(profile())->RegisterSocket(socket); experimental_bluetooth::Socket result_socket; result_socket.device.address = device->address(); result_socket.device.name = UTF16ToUTF8(device->GetName()); result_socket.service_uuid = service_uuid; result_socket.id = socket_id; result_.reset(result_socket.ToValue().release()); SendResponse(true); } else { SendResponse(false); } Release(); // Added in RunImpl } bool BluetoothConnectFunction::RunImpl() { scoped_ptr<Connect::Params> params(Connect::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); chromeos::BluetoothDevice* device = GetMutableAdapter(profile())->GetDevice(params->device.address); if (!device) { SendResponse(false); return false; } AddRef(); device->ConnectToService(params->service, base::Bind(&BluetoothConnectFunction::ConnectToServiceCallback, this, device, params->service)); return true; } bool BluetoothDisconnectFunction::RunImpl() { scoped_ptr<Disconnect::Params> params(Disconnect::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); return GetEventRouter(profile())->ReleaseSocket(params->socket.id); } bool BluetoothReadFunction::Prepare() { scoped_ptr<Read::Params> params(Read::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); socket_ = GetEventRouter(profile())->GetSocket(params->socket.id); if (socket_.get() == NULL) { SetError(kSocketNotFoundError); return false; } success_ = false; return true; } void BluetoothReadFunction::Work() { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); CHECK(socket_.get() != NULL); char* all_bytes = NULL; ssize_t buffer_size = 0; ssize_t total_bytes_read = 0; int errsv; while (true) { buffer_size += 1024; all_bytes = static_cast<char*>(realloc(all_bytes, buffer_size)); CHECK(all_bytes) << "Failed to grow Bluetooth socket buffer"; // bluetooth sockets are non-blocking, so read until we hit an error ssize_t bytes_read = read(socket_->fd(), all_bytes + total_bytes_read, buffer_size - total_bytes_read); errsv = errno; if (bytes_read <= 0) break; total_bytes_read += bytes_read; } if (total_bytes_read > 0) { success_ = true; result_.reset(base::BinaryValue::Create(all_bytes, total_bytes_read)); } else { success_ = (errsv == EAGAIN || errsv == EWOULDBLOCK); free(all_bytes); } if (!success_) SetError(safe_strerror(errsv)); } bool BluetoothReadFunction::Respond() { return success_; } bool BluetoothWriteFunction::Prepare() { // TODO(bryeung): update to new-style parameter passing when ArrayBuffer // support is added DictionaryValue* socket; EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &socket)); int socket_id; EXTENSION_FUNCTION_VALIDATE(socket->GetInteger("id", &socket_id)); socket_ = GetEventRouter(profile())->GetSocket(socket_id); if (socket_.get() == NULL) { SetError(kSocketNotFoundError); return false; } base::BinaryValue* tmp_data; EXTENSION_FUNCTION_VALIDATE(args_->GetBinary(1, &tmp_data)); data_to_write_ = tmp_data; success_ = false; return socket_.get() != NULL; } void BluetoothWriteFunction::Work() { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); if (socket_.get() == NULL) return; ssize_t bytes_written = write(socket_->fd(), data_to_write_->GetBuffer(), data_to_write_->GetSize()); int errsv = errno; if (bytes_written > 0) { result_.reset(Value::CreateIntegerValue(bytes_written)); success_ = true; } else { result_.reset(0); success_ = (errsv == EAGAIN || errsv == EWOULDBLOCK); } if (!success_) SetError(safe_strerror(errsv)); } bool BluetoothWriteFunction::Respond() { return success_; } #else // ----------------------------------------------------------------------------- // NIY stubs // ----------------------------------------------------------------------------- bool BluetoothIsAvailableFunction::RunImpl() { NOTREACHED() << "Not implemented yet"; return false; } bool BluetoothIsPoweredFunction::RunImpl() { NOTREACHED() << "Not implemented yet"; return false; } bool BluetoothGetAddressFunction::RunImpl() { NOTREACHED() << "Not implemented yet"; return false; } bool BluetoothGetDevicesWithServiceUUIDFunction::RunImpl() { NOTREACHED() << "Not implemented yet"; return false; } bool BluetoothGetDevicesWithServiceNameFunction::RunImpl() { NOTREACHED() << "Not implemented yet"; return false; } bool BluetoothConnectFunction::RunImpl() { NOTREACHED() << "Not implemented yet"; return false; } bool BluetoothDisconnectFunction::RunImpl() { NOTREACHED() << "Not implemented yet"; return false; } bool BluetoothReadFunction::Prepare() { return true; } void BluetoothReadFunction::Work() { } bool BluetoothReadFunction::Respond() { NOTREACHED() << "Not implemented yet"; return false; } bool BluetoothWriteFunction::Prepare() { return true; } void BluetoothWriteFunction::Work() { } bool BluetoothWriteFunction::Respond() { NOTREACHED() << "Not implemented yet"; return false; } #endif BluetoothReadFunction::BluetoothReadFunction() {} BluetoothReadFunction::~BluetoothReadFunction() {} BluetoothWriteFunction::BluetoothWriteFunction() {} BluetoothWriteFunction::~BluetoothWriteFunction() {} bool BluetoothSetOutOfBandPairingDataFunction::RunImpl() { NOTREACHED() << "Not implemented yet"; return false; } bool BluetoothGetOutOfBandPairingDataFunction::RunImpl() { NOTREACHED() << "Not implemented yet"; return false; } } // namespace api } // namespace extensions
28.47013
80
0.716632
7e1a088a7797a422fe47eb3c8731608f189a1c84
3,975
cpp
C++
Firmware/Src/io/lcd/LcdDriver.cpp
borgu/midi-grid
ce65669f55d5d5598a8ff185debcec76ab001bfa
[ "BSD-3-Clause" ]
null
null
null
Firmware/Src/io/lcd/LcdDriver.cpp
borgu/midi-grid
ce65669f55d5d5598a8ff185debcec76ab001bfa
[ "BSD-3-Clause" ]
null
null
null
Firmware/Src/io/lcd/LcdDriver.cpp
borgu/midi-grid
ce65669f55d5d5598a8ff185debcec76ab001bfa
[ "BSD-3-Clause" ]
null
null
null
#include "io/lcd/LcdDriver.hpp" #include "system/gpio_definitions.h" #include "stm32f4xx_hal.h" namespace lcd { static DMA_HandleTypeDef lcdSpiDma; static SPI_HandleTypeDef lcdSpi; extern "C" void DMA1_Stream4_IRQHandler() { HAL_DMA_IRQHandler(&lcdSpiDma); } LcdDriver::LcdDriver() { } LcdDriver::~LcdDriver() { } void LcdDriver::initialize() { initializeGpio(); initializeSpi(); initializeDma(); resetController(); writeCommand( 0x21 ); // LCD extended commands. writeCommand( 0xB8 ); // set LCD Vop(Contrast). writeCommand( 0x04 ); // set temp coefficent. writeCommand( 0x15 ); // LCD bias mode 1:65. used to be 0x14 - 1:40 writeCommand( 0x20 ); // LCD basic commands. writeCommand( 0x0C ); // LCD normal. } void LcdDriver::transmit( uint8_t* const buffer ) { setCursor( 0, 0 ); while (HAL_DMA_STATE_BUSY == HAL_DMA_GetState( &lcdSpiDma )) { // wait until previous transfer is done } HAL_GPIO_WritePin( mcu::LCD_GPIO_Port, mcu::DC_Pin, GPIO_PIN_SET ); //data mode HAL_SPI_Transmit_DMA( &lcdSpi, &buffer[0], bufferSize ); } void LcdDriver::initializeDma() { __HAL_RCC_DMA1_CLK_ENABLE(); // SPI2 DMA Init // SPI2_TX Init lcdSpiDma.Instance = DMA1_Stream4; lcdSpiDma.Init.Channel = DMA_CHANNEL_0; lcdSpiDma.Init.Direction = DMA_MEMORY_TO_PERIPH; lcdSpiDma.Init.PeriphInc = DMA_PINC_DISABLE; lcdSpiDma.Init.MemInc = DMA_MINC_ENABLE; lcdSpiDma.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; lcdSpiDma.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; lcdSpiDma.Init.Mode = DMA_NORMAL; lcdSpiDma.Init.Priority = DMA_PRIORITY_LOW; lcdSpiDma.Init.FIFOMode = DMA_FIFOMODE_DISABLE; HAL_DMA_Init( &lcdSpiDma ); __HAL_LINKDMA( &lcdSpi, hdmatx, lcdSpiDma ); // DMA interrupt init // DMA1_Stream4_IRQn interrupt configuration HAL_NVIC_SetPriority( DMA1_Stream4_IRQn, 6, 0 ); HAL_NVIC_EnableIRQ( DMA1_Stream4_IRQn ); } void LcdDriver::initializeGpio() { static GPIO_InitTypeDef gpioConfiguration; __HAL_RCC_GPIOB_CLK_ENABLE(); gpioConfiguration.Pin = mcu::DC_Pin | mcu::RESET_Pin; gpioConfiguration.Mode = GPIO_MODE_OUTPUT_PP; gpioConfiguration.Pull = GPIO_NOPULL; gpioConfiguration.Speed = GPIO_SPEED_FREQ_VERY_HIGH; HAL_GPIO_Init( mcu::LCD_GPIO_Port, &gpioConfiguration ); gpioConfiguration.Pin = mcu::CS_Pin | mcu::SCK_Pin | mcu::MOSI_Pin; gpioConfiguration.Mode = GPIO_MODE_AF_PP; gpioConfiguration.Alternate = GPIO_AF5_SPI2; HAL_GPIO_Init( mcu::LCD_GPIO_Port, &gpioConfiguration ); } void LcdDriver::initializeSpi() { __HAL_RCC_SPI2_CLK_ENABLE(); // SPI2 parameter configuration lcdSpi.Instance = SPI2; lcdSpi.Init.Mode = SPI_MODE_MASTER; lcdSpi.Init.Direction = SPI_DIRECTION_2LINES; lcdSpi.Init.DataSize = SPI_DATASIZE_8BIT; lcdSpi.Init.CLKPolarity = SPI_POLARITY_LOW; lcdSpi.Init.CLKPhase = SPI_PHASE_1EDGE; lcdSpi.Init.NSS = SPI_NSS_HARD_OUTPUT; lcdSpi.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32; // 3MBbit? lcdSpi.Init.FirstBit = SPI_FIRSTBIT_MSB; lcdSpi.Init.TIMode = SPI_TIMODE_DISABLE; lcdSpi.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; HAL_SPI_Init( &lcdSpi ); } void LcdDriver::resetController() { HAL_GPIO_WritePin( mcu::LCD_GPIO_Port, mcu::RESET_Pin, GPIO_PIN_RESET ); HAL_GPIO_WritePin( mcu::LCD_GPIO_Port, mcu::RESET_Pin, GPIO_PIN_SET ); } void LcdDriver::setCursor( const uint8_t x, const uint8_t y ) { writeCommand( 0x80 | x ); // column. writeCommand( 0x40 | y ); // row. } void LcdDriver::writeCommand( const uint8_t command ) { uint8_t commandToWrite = command; while (HAL_DMA_STATE_BUSY == HAL_DMA_GetState( &lcdSpiDma )) { // wait until previous transfer is done } HAL_GPIO_WritePin( mcu::LCD_GPIO_Port, mcu::DC_Pin, GPIO_PIN_RESET ); //command mode HAL_SPI_Transmit_DMA( &lcdSpi, &commandToWrite, 1 ); } } // namespace lcd
27.797203
88
0.720755
7e1ae4aa4ceb168d6d7f5a29b2f60d26b7096f1f
9,157
cpp
C++
Source/dvlnet/tcp_server.cpp
pionere/devilutionX
63f8deb298a00b040010fc299c0568eae19522e1
[ "Unlicense" ]
2
2021-02-02T19:27:20.000Z
2022-03-07T16:50:55.000Z
Source/dvlnet/tcp_server.cpp
pionere/devilutionX
63f8deb298a00b040010fc299c0568eae19522e1
[ "Unlicense" ]
null
null
null
Source/dvlnet/tcp_server.cpp
pionere/devilutionX
63f8deb298a00b040010fc299c0568eae19522e1
[ "Unlicense" ]
1
2022-03-07T16:51:16.000Z
2022-03-07T16:51:16.000Z
#include "tcp_server.h" #ifdef TCPIP #include <chrono> #include <memory> #include "base.h" DEVILUTION_BEGIN_NAMESPACE namespace net { tcp_server::tcp_server(asio::io_context &ioc, buffer_t info, unsigned srvType) : ioc(ioc) , acceptor(ioc) , connTimer(ioc) , game_init_info(info) , serverType(srvType) { assert(game_init_info.size() == sizeof(SNetGameData)); } bool tcp_server::setup_server(const char* bindAddr, unsigned short port, const char* passwd) { pktfty.setup_password(passwd); asio::error_code err; auto addr = asio::ip::address::from_string(bindAddr, err); if (!err) { auto ep = asio::ip::tcp::endpoint(addr, port); connect_acceptor(acceptor, ep, err); } if (err) { SDL_SetError("%s", err.message().c_str()); close(); return false; } start_accept(); start_timeout(); return true; } void tcp_server::connect_acceptor(asio::ip::tcp::acceptor &acceptor, const asio::ip::tcp::endpoint& ep, asio::error_code &ec) { acceptor.open(ep.protocol(), ec); if (ec) return; acceptor.set_option(asio::socket_base::reuse_address(true), ec); assert(!ec); acceptor.bind(ep, ec); if (ec) return; acceptor.listen(2 * MAX_PLRS, ec); } void tcp_server::connect_socket(asio::ip::tcp::socket &sock, const char* addrstr, unsigned port, asio::io_context &ioc, asio::error_code &ec) { std::string strPort = std::to_string(port); auto resolver = asio::ip::tcp::resolver(ioc); auto addrList = resolver.resolve(addrstr, strPort, ec); if (ec) return; asio::connect(sock, addrList, ec); if (ec) return; asio::ip::tcp::no_delay option(true); sock.set_option(option, ec); assert(!ec); } void tcp_server::endpoint_to_string(const scc &con, std::string &addr) { asio::error_code err; const auto &ep = con->socket.remote_endpoint(err); assert(!err); char buf[PORT_LENGTH + 2]; snprintf(buf, sizeof(buf), ":%05d", ep.port()); addr = ep.address().to_string(); addr.append(buf); } void tcp_server::make_default_gamename(char (&gamename)[128]) { if (!getIniValue("Network", "Bind Address", gamename, sizeof(gamename) - 1)) { copy_cstr(gamename, "127.0.0.1"); //SStrCopy(gamename, asio::ip::address_v4::loopback().to_string().c_str(), sizeof(gamename)); } } tcp_server::scc tcp_server::make_connection(asio::io_context &ioc) { return std::make_shared<client_connection>(ioc); } plr_t tcp_server::next_free_conn() { plr_t i; for (i = 0; i < MAX_PLRS; i++) if (connections[i] == NULL) break; return i < ((SNetGameData*)game_init_info.data())->bMaxPlayers ? i : MAX_PLRS; } plr_t tcp_server::next_free_queue() { plr_t i; for (i = 0; i < MAX_PLRS; i++) if (pending_connections[i] == NULL) break; return i; } void tcp_server::start_recv(const scc &con) { con->socket.async_receive(asio::buffer(con->recv_buffer), std::bind(&tcp_server::handle_recv, this, con, std::placeholders::_1, std::placeholders::_2)); } void tcp_server::handle_recv(const scc &con, const asio::error_code &ec, size_t bytesRead) { if (ec || bytesRead == 0) { drop_connection(con); return; } con->timeout = TIMEOUT_ACTIVE; con->recv_buffer.resize(bytesRead); con->recv_queue.write(std::move(con->recv_buffer)); con->recv_buffer.resize(frame_queue::MAX_FRAME_SIZE); while (con->recv_queue.packet_ready()) { auto pkt = pktfty.make_in_packet(con->recv_queue.read_packet()); if (pkt == NULL || !handle_recv_packet(con, *pkt)) { drop_connection(con); return; } } start_recv(con); } /*void tcp_server::send_connect(const scc &con) { auto pkt = pktfty.make_out_packet<PT_CONNECT>(PLR_MASTER, PLR_BROADCAST, con->pnum); send_packet(*pkt); }*/ bool tcp_server::handle_recv_newplr(const scc &con, packet &pkt) { plr_t i, pnum; if (pkt.pktType() != PT_JOIN_REQUEST) { // SDL_Log("Invalid join packet."); return false; } pnum = next_free_conn(); for (i = 0; i < MAX_PLRS; i++) { if (pending_connections[i] == con) break; } if (pnum == MAX_PLRS || i == MAX_PLRS) { // SDL_Log(pnum == MAX_PLRS ? "Server is full." : "Dropped connection."); return false; } pending_connections[i] = NULL; connections[pnum] = con; con->pnum = pnum; auto reply = pktfty.make_out_packet<PT_JOIN_ACCEPT>(PLR_MASTER, PLR_BROADCAST, pkt.pktJoinReqCookie(), pnum, game_init_info); start_send(con, *reply); //send_connect(con); if (serverType == SRV_DIRECT) { std::string addr; for (i = 0; i < MAX_PLRS; i++) { if (connections[i] != NULL && connections[i] != con) { endpoint_to_string(connections[i], addr); auto oldConPkt = pktfty.make_out_packet<PT_CONNECT>(PLR_MASTER, PLR_BROADCAST, i, buffer_t(addr.begin(), addr.end())); start_send(con, *oldConPkt); } } } return true; } bool tcp_server::handle_recv_packet(const scc &con, packet &pkt) { if (con->pnum != PLR_BROADCAST) { return con->pnum == pkt.pktSrc() && send_packet(pkt); } else { return handle_recv_newplr(con, pkt); } } bool tcp_server::send_packet(packet &pkt) { plr_t dest = pkt.pktDest(); plr_t src = pkt.pktSrc(); if (dest == PLR_BROADCAST) { for (int i = 0; i < MAX_PLRS; i++) if (i != src && connections[i] != NULL) start_send(connections[i], pkt); } else { if (dest >= MAX_PLRS) { // SDL_Log("Invalid destination %d", dest); return false; } if ((dest != src) && connections[dest] != NULL) start_send(connections[dest], pkt); } return true; } void tcp_server::start_send(const scc &con, packet &pkt) { const auto *frame = new buffer_t(frame_queue::make_frame(pkt.encrypted_data())); auto buf = asio::buffer(*frame); asio::async_write(con->socket, buf, [frame](const asio::error_code &ec, size_t bytesSent) { delete frame; }); } void tcp_server::start_accept() { if (next_free_queue() != MAX_PLRS) { nextcon = make_connection(ioc); acceptor.async_accept(nextcon->socket, std::bind(&tcp_server::handle_accept, this, true, std::placeholders::_1)); } else { nextcon = NULL; connTimer.expires_after(std::chrono::seconds(10)); connTimer.async_wait(std::bind(&tcp_server::handle_accept, this, false, std::placeholders::_1)); } } void tcp_server::handle_accept(bool valid, const asio::error_code &ec) { if (ec) return; if (valid) { asio::error_code err; asio::ip::tcp::no_delay option(true); nextcon->socket.set_option(option, err); assert(!err); nextcon->timeout = TIMEOUT_CONNECT; pending_connections[next_free_queue()] = nextcon; start_recv(nextcon); } start_accept(); } void tcp_server::start_timeout() { connTimer.expires_after(std::chrono::seconds(1)); connTimer.async_wait(std::bind(&tcp_server::handle_timeout, this, std::placeholders::_1)); } void tcp_server::handle_timeout(const asio::error_code &ec) { int i, n; if (ec) return; scc expired_connections[2 * MAX_PLRS] = { }; n = 0; for (i = 0; i < MAX_PLRS; i++) { if (pending_connections[i] != NULL) { if (pending_connections[i]->timeout > 0) { pending_connections[i]->timeout--; } else { expired_connections[n] = pending_connections[i]; n++; } } } for (i = 0; i < MAX_PLRS; i++) { if (connections[i] != NULL) { if (connections[i]->timeout > 0) { connections[i]->timeout--; } else { expired_connections[n] = connections[i]; n++; } } } for (i = 0; i < n; i++) drop_connection(expired_connections[i]); start_timeout(); } void tcp_server::drop_connection(const scc &con) { plr_t i, pnum = con->pnum; if (pnum != PLR_BROADCAST) { // live connection if (connections[pnum] == con) { connections[pnum] = NULL; // notify the other clients auto pkt = pktfty.make_out_packet<PT_DISCONNECT>(PLR_MASTER, PLR_BROADCAST, pnum, (leaveinfo_t)LEAVE_DROP); send_packet(*pkt); } } else { // pending connection for (i = 0; i < MAX_PLRS; i++) { if (pending_connections[i] == con) { pending_connections[i] = NULL; } } } asio::error_code err; con->socket.close(err); } void tcp_server::close() { int i; asio::error_code err; if (acceptor.is_open()) { auto pkt = pktfty.make_out_packet<PT_DISCONNECT>(PLR_MASTER, PLR_BROADCAST, PLR_MASTER, (leaveinfo_t)LEAVE_DROP); send_packet(*pkt); ioc.poll(err); err.clear(); } acceptor.close(err); err.clear(); connTimer.cancel(err); err.clear(); ioc.poll(err); err.clear(); if (nextcon != NULL) { nextcon->socket.close(err); err.clear(); } for (i = 0; i < MAX_PLRS; i++) { if (connections[i] != NULL) { connections[i]->socket.shutdown(asio::socket_base::shutdown_both, err); err.clear(); connections[i]->socket.close(err); err.clear(); } } for (i = 0; i < MAX_PLRS; i++) { if (pending_connections[i] != NULL) { pending_connections[i]->socket.close(err); err.clear(); } } ioc.poll(err); } } // namespace net DEVILUTION_END_NAMESPACE #endif // TCPIP
24.748649
96
0.642569
7e1b2f410e7f84f5311dea12c79674b57900bc0a
758
cpp
C++
cpp/BalancedBinaryTree.cpp
thinksource/code_interview
08be992240508b73894eaf6b8c025168fd19df19
[ "Apache-2.0" ]
12
2015-03-12T03:27:26.000Z
2021-03-11T09:26:16.000Z
cpp/BalancedBinaryTree.cpp
thinksource/code_interview
08be992240508b73894eaf6b8c025168fd19df19
[ "Apache-2.0" ]
null
null
null
cpp/BalancedBinaryTree.cpp
thinksource/code_interview
08be992240508b73894eaf6b8c025168fd19df19
[ "Apache-2.0" ]
11
2015-01-28T16:45:40.000Z
2017-03-28T20:01:38.000Z
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isBalanced(TreeNode *root) { int h = 0; return isBalanced(root, h); } bool isBalanced(TreeNode* root, int& height) { if(root==NULL) { height = 0; return true; } int heightLeft = 0; int heightRight = 0; bool isBLeft = isBalanced(root->left, heightLeft); bool isBRight = isBalanced(root->right, heightRight); height = 1+max(heightLeft, heightRight); return abs(heightLeft-heightRight)<=1 && isBLeft && isBRight; } };
25.266667
69
0.555409
7e1be89d5ebd582653ffef7f21993d81a14d0ab8
5,033
cpp
C++
gui/statuses/LocalStatuses.cpp
mail-ru-im/im-desktop
d6bb606650ad84b31046fe39b81db1fec4e6050b
[ "Apache-2.0" ]
81
2019-09-18T13:53:17.000Z
2022-03-19T00:44:20.000Z
gui/statuses/LocalStatuses.cpp
mail-ru-im/im-desktop
d6bb606650ad84b31046fe39b81db1fec4e6050b
[ "Apache-2.0" ]
4
2019-10-03T15:17:00.000Z
2019-11-03T01:05:41.000Z
gui/statuses/LocalStatuses.cpp
mail-ru-im/im-desktop
d6bb606650ad84b31046fe39b81db1fec4e6050b
[ "Apache-2.0" ]
25
2019-09-27T16:56:02.000Z
2022-03-14T07:11:14.000Z
#include "stdafx.h" #include "utils/JsonUtils.h" #include "../utils/features.h" #include "LocalStatuses.h" #include "gui_settings.h" #include "utils/utils.h" #include "utils/InterConnector.h" #include "rapidjson/writer.h" namespace { inline QString getDefaultJSONPath() { return (Ui::get_gui_settings()->get_value(settings_language, QString()) == u"ru") ? qsl(":/statuses/default_statuses") : qsl(":/statuses/default_statuses_eng"); } std::vector<Statuses::LocalStatus> defaultStatuses() { std::vector<Statuses::LocalStatus> statuses; rapidjson::Document doc; doc.Parse(Features::getStatusJson()); if (doc.HasParseError()) { im_assert(QFile::exists(getDefaultJSONPath())); QFile file(getDefaultJSONPath()); if (!file.open(QFile::ReadOnly | QFile::Text)) return statuses; const auto json = file.readAll(); doc.Parse(json.constData(), json.size()); if (doc.HasParseError()) { im_assert(false); return statuses; } file.close(); } if (doc.IsArray()) { statuses.reserve(doc.Size()); for (const auto& item : doc.GetArray()) { Statuses::LocalStatus status; JsonUtils::unserialize_value(item, "status", status.status_); JsonUtils::unserialize_value(item, "text", status.description_); JsonUtils::unserialize_value(item, "duration", status.duration_); statuses.push_back(std::move(status)); } } return statuses; } } namespace Statuses { using namespace Ui; class LocalStatuses_p { public: void updateIndex() { index_.clear(); for (auto i = 0u; i < statuses_.size(); i++) index_[statuses_[i].status_] = i; } void overrideStatusDurationsFromSettings() { for (auto& status : statuses_) { if (get_gui_settings()->contains_value(status_duration, status.status_)) status.duration_ = std::chrono::seconds(get_gui_settings()->get_value<int64_t>(status_duration, 0, status.status_)); } } void load() { statuses_ = defaultStatuses(); migrateOldSettingsData(); overrideStatusDurationsFromSettings(); updateIndex(); } void resetToDefaults() { statuses_ = defaultStatuses(); updateIndex(); } void migrateOldSettingsData() { const auto statusesStr = get_gui_settings()->get_value<QString>(statuses_user_statuses, QString()); const auto statuses = statusesStr.splitRef(ql1c(';'), QString::SkipEmptyParts); for (const auto& s : boost::adaptors::reverse(statuses)) { const auto& stat = s.split(ql1c(':'), QString::SkipEmptyParts); if (!stat.isEmpty() && stat.size() == 2) get_gui_settings()->set_value<int64_t>(status_duration, stat[1].toLongLong(), stat[0].toString()); } get_gui_settings()->set_value(statuses_user_statuses, QString()); } std::vector<LocalStatus> statuses_; std::unordered_map<QString, size_t, Utils::QStringHasher> index_; }; LocalStatuses::LocalStatuses() : d(std::make_unique<LocalStatuses_p>()) { d->load(); connect(&Utils::InterConnector::instance(), &Utils::InterConnector::omicronUpdated, this, &LocalStatuses::onOmicronUpdated); } LocalStatuses::~LocalStatuses() = default; LocalStatuses* LocalStatuses::instance() { static LocalStatuses localStatuses; return &localStatuses; } const LocalStatus& LocalStatuses::getStatus(const QString& _statusCode) const { auto it = d->index_.find(_statusCode); if (it != d->index_.end()) return d->statuses_[it->second]; static LocalStatus empty; return empty; } void LocalStatuses::setDuration(const QString& _statusCode, std::chrono::seconds _duration) { auto it = d->index_.find(_statusCode); if (it != d->index_.end()) { d->statuses_[it->second].duration_ = _duration; get_gui_settings()->set_value<int64_t>(status_duration, _duration.count(), _statusCode); } } std::chrono::seconds LocalStatuses::statusDuration(const QString& _statusCode) const { auto it = d->index_.find(_statusCode); if (it != d->index_.end()) return d->statuses_[it->second].duration_; return std::chrono::seconds::zero(); } const QString& LocalStatuses::statusDescription(const QString& _statusCode) const { auto it = d->index_.find(_statusCode); if (it != d->index_.end()) return d->statuses_[it->second].description_; static QString empty; return empty; } const std::vector<LocalStatus>& LocalStatuses::statuses() const { return d->statuses_; } void LocalStatuses::resetToDefaults() { d->resetToDefaults(); } void LocalStatuses::onOmicronUpdated() { d->load(); } }
25.943299
168
0.622293
7e1caedc68709129a2d488241201b6042bf4625e
1,608
cpp
C++
Native/Framework/source/Library.Shared/SpriteManager.cpp
btrowbridge/DirectX.2D.Bespoke.Games
382728f7c9d50597f9fc84e222efd468c33716a5
[ "MS-PL" ]
null
null
null
Native/Framework/source/Library.Shared/SpriteManager.cpp
btrowbridge/DirectX.2D.Bespoke.Games
382728f7c9d50597f9fc84e222efd468c33716a5
[ "MS-PL" ]
null
null
null
Native/Framework/source/Library.Shared/SpriteManager.cpp
btrowbridge/DirectX.2D.Bespoke.Games
382728f7c9d50597f9fc84e222efd468c33716a5
[ "MS-PL" ]
null
null
null
#include "pch.h" #include "SpriteManager.h" using namespace std; using namespace DirectX; namespace Library { unique_ptr<SpriteManager> SpriteManager::sInstance; SpriteManager::SpriteManager(Game& game) : mGame(&game), mSpriteBatch(make_shared<DirectX::SpriteBatch>(mGame->Direct3DDeviceContext())) { } shared_ptr<SpriteBatch> SpriteManager::SpriteBatch() { return sInstance->mSpriteBatch; } void SpriteManager::Initialize(Game& game) { sInstance = unique_ptr<SpriteManager>(new SpriteManager(game)); } void SpriteManager::Shutdown() { sInstance = nullptr; } void SpriteManager::DrawTexture2D(ID3D11ShaderResourceView* texture, const XMFLOAT2& position, FXMVECTOR color) { assert(sInstance != nullptr); sInstance->mSpriteBatch->Begin(); sInstance->mSpriteBatch->Draw(texture, position, color); sInstance->mSpriteBatch->End(); } void SpriteManager::DrawTexture2D(ID3D11ShaderResourceView* texture, const Rectangle& destinationRectangle, FXMVECTOR color) { assert(sInstance != nullptr); sInstance->mSpriteBatch->Begin(); RECT destinationRect = { destinationRectangle.X, destinationRectangle.Y, destinationRectangle.Width, destinationRectangle.Height }; sInstance->mSpriteBatch->Draw(texture, destinationRect, color); sInstance->mSpriteBatch->End(); } void SpriteManager::DrawString(shared_ptr<SpriteFont> font, const wstring& text, const XMFLOAT2& textPosition) { assert(sInstance != nullptr); sInstance->mSpriteBatch->Begin(); font->DrawString(sInstance->mSpriteBatch.get(), text.c_str(), textPosition); sInstance->mSpriteBatch->End(); } }
27.724138
133
0.75995
7e1dbbe5a0decdaec568540334ac2b00e0186796
5,991
cpp
C++
JNIManagedPeer.cpp
jessebenson/JNIManagedPeerBase
7188fc75ecd2010901c9baf98436e7f16eb488b2
[ "MIT" ]
null
null
null
JNIManagedPeer.cpp
jessebenson/JNIManagedPeerBase
7188fc75ecd2010901c9baf98436e7f16eb488b2
[ "MIT" ]
null
null
null
JNIManagedPeer.cpp
jessebenson/JNIManagedPeerBase
7188fc75ecd2010901c9baf98436e7f16eb488b2
[ "MIT" ]
1
2019-01-03T12:34:01.000Z
2019-01-03T12:34:01.000Z
/* * The MIT License (MIT) * * Copyright (c) 2014 Jesse Benson * * 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 "stdafx.h" #include "JNIManagedPeer.h" namespace JNI { static JavaVM* s_JVM = nullptr; void STDMETHODCALLTYPE SetJVM(JavaVM* jvm) { s_JVM = jvm; } JavaVM* STDMETHODCALLTYPE GetJVM() { return s_JVM; } static JNIEnv* GetEnvironment() { JNIEnv* env = nullptr; if (s_JVM != nullptr) s_JVM->AttachCurrentThread(reinterpret_cast<void**>(&env), nullptr); return env; } JNIEnv& STDMETHODCALLTYPE GetEnv() { return *GetEnvironment(); } JObject::JObject() { } JObject::JObject(jobject object, bool releaseLocalRef) { JNIEnv* env = GetEnvironment(); AttachObject(env, object); if (releaseLocalRef) { env->DeleteLocalRef(object); } } JObject::JObject(const JObject& object) { AttachObject(GetEnvironment(), object.m_Object); } JObject::JObject(JObject&& object) : m_Object(object.m_Object) { object.m_Object = nullptr; } JObject::~JObject() { ReleaseObject(GetEnvironment()); } JObject& JObject::operator=(jobject object) { JNIEnv* env = GetEnvironment(); ReleaseObject(env); AttachObject(env, object); return *this; } JObject& JObject::operator=(const JObject& object) { if (this != &object) { JNIEnv* env = GetEnvironment(); ReleaseObject(env); AttachObject(env, object.m_Object); } return *this; } JObject& JObject::operator=(JObject&& object) { if (this != &object) { ReleaseObject(GetEnvironment()); m_Object = object.m_Object; object.m_Object = nullptr; } return *this; } void JObject::AttachObject(JNIEnv* env, jobject object) { if (object != nullptr) { m_Object = env->NewGlobalRef(object); } } void JObject::ReleaseObject(JNIEnv* env) { if (m_Object != nullptr) { env->DeleteGlobalRef(m_Object); m_Object = nullptr; } } void JObject::AttachLocalObject(JNIEnv* env, jobject object) { if (object != nullptr) { m_Object = env->NewGlobalRef(object); env->DeleteLocalRef(object); } } JClass::JClass(const char* className) : JObject(GetEnvironment()->FindClass(className), /*deleteLocalRef:*/ true) { } JClass::~JClass() { } JString::JString(jstring string, bool removeLocalRef) : JObject(string, removeLocalRef) { } JString::JString(const char* content) { JNIEnv* env = GetEnvironment(); AttachLocalObject(env, env->NewStringUTF(content)); } JString::JString(const wchar_t* content) { JNIEnv* env = GetEnvironment(); AttachLocalObject(env, env->NewString((const jchar *)content, wcslen(content))); } JString::~JString() { Clear(); } const char* JString::GetUTFString() const { if (m_pString == nullptr) { // Logically, this method doesn't change the JString const_cast<JString*>(this)->m_pString = GetEnvironment()->GetStringUTFChars(String(), nullptr); } return m_pString; } int JString::GetUTFLength() const { return (int)GetEnvironment()->GetStringUTFLength(String()); } const wchar_t* JString::GetStringChars() const { if (m_pWString == nullptr) { // Logically, this method doesn't change the JString const_cast<JString*>(this)->m_pWString = (const wchar_t*)GetEnvironment()->GetStringChars(String(), nullptr); } return m_pWString; } int JString::GetLength() const { return (int)GetEnvironment()->GetStringLength(String()); } void JString::Clear() { if (m_pString != nullptr && String() != nullptr) { GetEnvironment()->ReleaseStringUTFChars(String(), m_pString); m_pString = nullptr; } if (m_pWString != nullptr && String() != nullptr) { GetEnvironment()->ReleaseStringChars(String(), (const jchar*)m_pWString); m_pWString = nullptr; } } ManagedPeer::ManagedPeer() : m_Object(nullptr) { } ManagedPeer::ManagedPeer(jobject object) : m_Object(object) { } ManagedPeer::~ManagedPeer() { } ManagedPeer& ManagedPeer::operator=(jobject obj) { m_Object = obj; return *this; } JNIEnv& ManagedPeer::Env() { return *GetEnvironment(); } } // namespace JNI
24.157258
121
0.59122
7e249238e151222cbd66c831c38133c8da2bc74d
5,968
hpp
C++
include/gct/graphics_pipeline_create_info.hpp
Fadis/gct
bde211f9336e945e4db21f5abb4ce01dcad78049
[ "MIT" ]
1
2022-03-03T09:27:09.000Z
2022-03-03T09:27:09.000Z
include/gct/graphics_pipeline_create_info.hpp
Fadis/gct
bde211f9336e945e4db21f5abb4ce01dcad78049
[ "MIT" ]
1
2021-12-02T03:45:45.000Z
2021-12-03T23:44:37.000Z
include/gct/graphics_pipeline_create_info.hpp
Fadis/gct
bde211f9336e945e4db21f5abb4ce01dcad78049
[ "MIT" ]
null
null
null
#ifndef GCT_GRAPHICS_PIPELINE_CREATE_INFO_HPP #define GCT_GRAPHICS_PIPELINE_CREATE_INFO_HPP #include <memory> #include <optional> #include <vulkan/vulkan.hpp> #include <gct/extension.hpp> #include <gct/pipeline_shader_stage_create_info.hpp> #include <gct/pipeline_vertex_input_state_create_info.hpp> #include <gct/pipeline_input_assembly_state_create_info.hpp> #include <gct/pipeline_tessellation_state_create_info.hpp> #include <gct/pipeline_viewport_state_create_info.hpp> #include <gct/pipeline_rasterization_state_create_info.hpp> #include <gct/pipeline_multisample_state_create_info.hpp> #include <gct/pipeline_depth_stencil_state_create_info.hpp> #include <gct/pipeline_color_blend_state_create_info.hpp> #include <gct/pipeline_dynamic_state_create_info.hpp> namespace gct { class pipeline_layout_t; class render_pass_t; class graphics_pipeline_create_info_t : public chained_t { friend void to_json( nlohmann::json &root, const graphics_pipeline_create_info_t &v ); public: using self_type = graphics_pipeline_create_info_t; LIBGCT_EXTENSION_REBUILD_CHAIN_DEF LIBGCT_BASIC_SETTER( vk::GraphicsPipelineCreateInfo ) #ifdef VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME LIBGCT_EXTENSION_SETTER( vk::AttachmentSampleCountInfoAMD , attachment_sample_count ) #endif #ifdef VK_NV_DEVICE_GENERATED_COMMANDS_EXTENSION_NAME LIBGCT_EXTENSION_SETTER( vk::GraphicsPipelineShaderGroupsCreateInfoNV , shader_group ) #endif #if defined(VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME) && defined(VK_NVX_MULTIVIEW_PER_VIEW_ATTRIBUTES_EXTENSION_NAME) LIBGCT_EXTENSION_SETTER( vk::MultiviewPerViewAttributesInfoNVX , multiview_per_view_attributes ) #endif #ifdef VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME LIBGCT_EXTENSION_SETTER( vk::PipelineCreationFeedbackCreateInfoEXT, creation_feedback ) #endif #ifdef VK_AMD_PIPELINE_COMPILER_CONTROL_EXTENSION_NAME LIBGCT_EXTENSION_SETTER( vk::PipelineCompilerControlCreateInfoAMD , compiler_control ) #endif #ifdef VK_EXT_DISCARD_RECTANGLES_EXTENSION_NAME LIBGCT_EXTENSION_SETTER( vk::PipelineDiscardRectangleStateCreateInfoEXT , discard_rectangle ) #endif #ifdef VK_NV_FRAGMENT_SHADING_RATE_ENUMS_EXTENSION_NAME LIBGCT_EXTENSION_SETTER( vk::PipelineFragmentShadingRateEnumStateCreateInfoNV , fragment_shading_rate_nv ) #endif #ifdef VK_KHR_FRAGMENT_SHADING_RATE_EXTENSION_NAME LIBGCT_EXTENSION_SETTER( vk::PipelineFragmentShadingRateStateCreateInfoKHR, fragment_shading_rate ) #endif #ifdef VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME LIBGCT_EXTENSION_SETTER( vk::PipelineRenderingCreateInfoKHR, rendering ) #endif #ifdef VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME LIBGCT_EXTENSION_SETTER( vk::PipelineRepresentativeFragmentTestStateCreateInfoNV, representative_fragment_test ) #endif private: std::vector< pipeline_shader_stage_create_info_t > stage; std::vector< vk::PipelineShaderStageCreateInfo > raw_stage; deep_copy_unique_ptr< pipeline_vertex_input_state_create_info_t > vertex_input; deep_copy_unique_ptr< pipeline_input_assembly_state_create_info_t > input_assembly; deep_copy_unique_ptr< pipeline_tessellation_state_create_info_t > tessellation; deep_copy_unique_ptr< pipeline_viewport_state_create_info_t > viewport; deep_copy_unique_ptr< pipeline_rasterization_state_create_info_t > rasterization; deep_copy_unique_ptr< pipeline_multisample_state_create_info_t > multisample; deep_copy_unique_ptr< pipeline_depth_stencil_state_create_info_t > depth_stencil; deep_copy_unique_ptr< pipeline_color_blend_state_create_info_t > color_blend; deep_copy_unique_ptr< pipeline_dynamic_state_create_info_t > dynamic; std::shared_ptr< pipeline_layout_t > layout; std::shared_ptr< render_pass_t > render_pass; std::uint32_t subpass = 0u; public: graphics_pipeline_create_info_t &add_stage( const pipeline_shader_stage_create_info_t& ); graphics_pipeline_create_info_t &add_stage( const std::shared_ptr< shader_module_t >& ); graphics_pipeline_create_info_t &clear_stage(); graphics_pipeline_create_info_t &set_vertex_input( const pipeline_vertex_input_state_create_info_t& ); graphics_pipeline_create_info_t &clear_vertex_input(); graphics_pipeline_create_info_t &set_input_assembly( const pipeline_input_assembly_state_create_info_t& ); graphics_pipeline_create_info_t &clear_input_assembly(); graphics_pipeline_create_info_t &set_tessellation( const pipeline_tessellation_state_create_info_t& ); graphics_pipeline_create_info_t &clear_tessellation(); graphics_pipeline_create_info_t &set_viewport( const pipeline_viewport_state_create_info_t& ); graphics_pipeline_create_info_t &clear_viewport(); graphics_pipeline_create_info_t &set_rasterization( const pipeline_rasterization_state_create_info_t& ); graphics_pipeline_create_info_t &clear_rasterization(); graphics_pipeline_create_info_t &set_multisample( const pipeline_multisample_state_create_info_t& ); graphics_pipeline_create_info_t &clear_multisample(); graphics_pipeline_create_info_t &set_depth_stencil( const pipeline_depth_stencil_state_create_info_t& ); graphics_pipeline_create_info_t &clear_depth_stencil(); graphics_pipeline_create_info_t &set_color_blend( const pipeline_color_blend_state_create_info_t& ); graphics_pipeline_create_info_t &clear_color_blend(); graphics_pipeline_create_info_t &set_dynamic( const pipeline_dynamic_state_create_info_t& ); graphics_pipeline_create_info_t &clear_dynamic(); graphics_pipeline_create_info_t &set_layout( const std::shared_ptr< pipeline_layout_t >& ); graphics_pipeline_create_info_t &clear_layout(); graphics_pipeline_create_info_t &set_render_pass( const std::shared_ptr< render_pass_t >&, std::uint32_t ); graphics_pipeline_create_info_t &clear_render_pass(); void to_json( nlohmann::json &root ); }; void to_json( nlohmann::json &root, const graphics_pipeline_create_info_t &v ); } #endif
56.838095
116
0.847185
7e257d7e240a3539b250416a09ef45c6f35ba85d
345
hpp
C++
include/di/systems/display/opengl_profile.hpp
acdemiralp/nano_engine
64069cf300af574efb0c979dbc97eb0a03cdc7a3
[ "MIT" ]
4
2021-02-24T14:13:47.000Z
2022-02-06T12:02:24.000Z
include/di/systems/display/opengl_profile.hpp
acdemiralp/nano_engine
64069cf300af574efb0c979dbc97eb0a03cdc7a3
[ "MIT" ]
1
2018-01-06T11:52:16.000Z
2018-01-06T11:52:16.000Z
include/di/systems/display/opengl_profile.hpp
acdemiralp/nano_engine
64069cf300af574efb0c979dbc97eb0a03cdc7a3
[ "MIT" ]
2
2018-02-11T14:51:17.000Z
2021-02-24T14:13:49.000Z
#ifndef DI_SYSTEMS_DISPLAY_OPENGL_PROFILE_HPP_ #define DI_SYSTEMS_DISPLAY_OPENGL_PROFILE_HPP_ #include <SDL2/SDL_video.h> namespace di { enum class opengl_profile { core = SDL_GL_CONTEXT_PROFILE_CORE , compatibility = SDL_GL_CONTEXT_PROFILE_COMPATIBILITY, embedded_systems = SDL_GL_CONTEXT_PROFILE_ES }; } #endif
20.294118
58
0.77971
7e2b55280d92f7dfeaca8cb2e6e15423710fa09d
636
cpp
C++
Sources/11XXX/11651/11651.cpp
DDManager/Baekjoon-Online-Judge
7dd6d76838d3309bfe5bef46f1778c5776ebdf2a
[ "MIT" ]
1
2019-07-02T09:07:58.000Z
2019-07-02T09:07:58.000Z
Sources/11XXX/11651/11651.cpp
DDManager/Baekjoon-Online-Judge
7dd6d76838d3309bfe5bef46f1778c5776ebdf2a
[ "MIT" ]
null
null
null
Sources/11XXX/11651/11651.cpp
DDManager/Baekjoon-Online-Judge
7dd6d76838d3309bfe5bef46f1778c5776ebdf2a
[ "MIT" ]
1
2022-02-13T04:17:10.000Z
2022-02-13T04:17:10.000Z
/** * BOJ 11651번 C++ 소스 코드 * 작성자 : 동동매니저 (DDManager) * * ※ 실행 결과 * 사용 메모리 : 1,900 KB / 262,144 KB * 소요 시간 : 60 ms / 1,000 ms * * Copyright 2020. DDManager all rights reserved. */ #include <cstdio> #include <cstdlib> #include <algorithm> using namespace std; typedef struct{ int x,y; }Point; bool comp(const Point a,const Point b){ if(a.y==b.y) return a.x<b.x; return a.y<b.y; } int main(void){ int N; Point *PA; int i; scanf("%d",&N); PA=(Point*)calloc(N,sizeof(Point)); for(i=0;i<N;i++) scanf("%d %d",&PA[i].x,&PA[i].y); sort(PA,PA+N,comp); for(i=0;i<N;i++) printf("%d %d\n",PA[i].x,PA[i].y); return 0; }
17.666667
52
0.584906
7e2ed3b3ff7340e46e18f1daf504f0c2408c0eee
4,692
cpp
C++
src/slam/instance.cpp
01org/node-realsense
9c000380f61912415c2943a20f8caeb41d579f7b
[ "MIT" ]
12
2017-02-27T14:10:12.000Z
2017-09-25T08:02:07.000Z
src/slam/instance.cpp
01org/node-realsense
9c000380f61912415c2943a20f8caeb41d579f7b
[ "MIT" ]
209
2017-02-22T08:02:38.000Z
2017-09-27T09:26:24.000Z
src/slam/instance.cpp
01org/node-realsense
9c000380f61912415c2943a20f8caeb41d579f7b
[ "MIT" ]
18
2017-02-22T09:05:42.000Z
2017-09-21T07:52:40.000Z
// Copyright (c) 2016 Intel Corporation. All rights reserved. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. #include "instance.h" #include "gen/promise-helper.h" Instance::Instance() { } Instance& Instance::operator=(const Instance& rhs) { if (&rhs != this) { this->js_this_.Reset(Nan::New(rhs.js_this_)); } return *this; } Instance::~Instance() { SlamRunner::DestroySlamRunner(); js_this_.Reset(); } v8::Handle<v8::Promise> Instance::getCameraOptions() { return SlamRunner::GetSlamRunner()->getCameraOptions(); } v8::Handle<v8::Promise> Instance::getInstanceOptions() { return SlamRunner::GetSlamRunner()->getInstanceOptions(); } v8::Handle<v8::Promise> Instance::setCameraOptions( const CameraOptions& options) { std::string error; if (!options.CheckType(&error)) { PromiseHelper promise_helper; auto promise = promise_helper.CreatePromise(); promise_helper.RejectPromise(error); return promise; } return SlamRunner::GetSlamRunner()->setCameraOptions(options); } v8::Handle<v8::Promise> Instance::setInstanceOptions( const InstanceOptions& options) { std::string error; if (!options.CheckType(&error)) { PromiseHelper promise_helper; auto promise = promise_helper.CreatePromise(); promise_helper.RejectPromise(error); return promise; } return SlamRunner::GetSlamRunner()->setInstanceOptions(options); } v8::Handle<v8::Promise> Instance::setInstanceOptions() { PromiseHelper promise_helper; auto promise = promise_helper.CreatePromise(); promise_helper.ResolvePromise(); return promise; } v8::Handle<v8::Promise> Instance::start() { return SlamRunner::GetSlamRunner()->start(); } v8::Handle<v8::Promise> Instance::stop() { return SlamRunner::GetSlamRunner()->stop(); } v8::Handle<v8::Promise> Instance::pause() { // TODO(widl-nan): fill your code here } v8::Handle<v8::Promise> Instance::resume() { // TODO(widl-nan): fill your code here } v8::Handle<v8::Promise> Instance::reset() { return SlamRunner::GetSlamRunner()->reset(); } v8::Handle<v8::Promise> Instance::restartTracking() { return SlamRunner::GetSlamRunner()->restartTracking(); } v8::Handle<v8::Promise> Instance::getTrackingResult() { return SlamRunner::GetSlamRunner()->getTrackingResult(); } v8::Handle<v8::Promise> Instance::getOccupancyMap() { return SlamRunner::GetSlamRunner()->getOccupancyMap(nullptr); } v8::Handle<v8::Promise> Instance::getOccupancyMap( const RegionOfInterest& roi) { std::string error; if (!roi.CheckType(&error)) { PromiseHelper promise_helper; auto promise = promise_helper.CreatePromise(); promise_helper.RejectPromise(error); return promise; } return SlamRunner::GetSlamRunner()->getOccupancyMap(&roi); } v8::Handle<v8::Promise> Instance::getOccupancyMapAsRgba( const bool& drawPoseTrajectory, const bool& drawOccupancyMap) { return SlamRunner::GetSlamRunner()->getOccupancyMapAsRgba( drawPoseTrajectory, drawOccupancyMap); } v8::Handle<v8::Promise> Instance::getOccupancyMapUpdate( const RegionOfInterest& roi) { std::string error; if (!roi.CheckType(&error)) { PromiseHelper promise_helper; auto promise = promise_helper.CreatePromise(); promise_helper.RejectPromise(error); return promise; } return SlamRunner::GetSlamRunner()->getOccupancyMapUpdate(&roi); } v8::Handle<v8::Promise> Instance::getOccupancyMapUpdate() { return SlamRunner::GetSlamRunner()->getOccupancyMapUpdate(nullptr); } v8::Handle<v8::Promise> Instance::getOccupancyMapBounds() { return SlamRunner::GetSlamRunner()->getOccupancyMapBounds(); } v8::Handle<v8::Promise> Instance::loadOccupancyMap( const std::string& mapFileName) { return SlamRunner::GetSlamRunner()->loadOccupancyMap(mapFileName); } v8::Handle<v8::Promise> Instance::saveOccupancyMap( const std::string& mapFileName) { return SlamRunner::GetSlamRunner()->saveOccupancyMap(mapFileName); } v8::Handle<v8::Promise> Instance::saveOccupancyMapAsPpm( const std::string& mapFileName, const bool& drawCameraTrajectory) { return SlamRunner::GetSlamRunner()->saveOccupancyMapAsPpm( mapFileName, drawCameraTrajectory); } v8::Handle<v8::Promise> Instance::loadRelocalizationMap( const std::string& mapFileName) { return SlamRunner::GetSlamRunner()->loadRelocalizationMap(mapFileName); } v8::Handle<v8::Promise> Instance::saveRelocalizationMap( const std::string& mapFileName) { return SlamRunner::GetSlamRunner()->saveRelocalizationMap(mapFileName); } v8::Handle<v8::Promise> Instance::getRelocalizationPose() { return SlamRunner::GetSlamRunner()->getRelocalizationPose(); }
28.609756
73
0.734015
7e2ee7a99267f610e6b03bd97bb9fb7424d661bc
13,599
cpp
C++
src/plugins/summary/summarywidget.cpp
devel29a/leechcraft
faf5e856010fb785e4bbf3ce7b5c6a5c49f3239a
[ "BSL-1.0" ]
null
null
null
src/plugins/summary/summarywidget.cpp
devel29a/leechcraft
faf5e856010fb785e4bbf3ce7b5c6a5c49f3239a
[ "BSL-1.0" ]
null
null
null
src/plugins/summary/summarywidget.cpp
devel29a/leechcraft
faf5e856010fb785e4bbf3ce7b5c6a5c49f3239a
[ "BSL-1.0" ]
null
null
null
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. **********************************************************************/ #include "summarywidget.h" #include <QTimer> #include <QComboBox> #include <QMenu> #include <QToolBar> #include <QMainWindow> #include <QWidgetAction> #include <QCloseEvent> #include <QSortFilterProxyModel> #include <QLineEdit> #include <QtDebug> #include <interfaces/structures.h> #include <interfaces/ijobholder.h> #include <interfaces/core/icoreproxy.h> #include <interfaces/core/ipluginsmanager.h> #include <interfaces/core/irootwindowsmanager.h> #include <interfaces/core/iiconthememanager.h> #include <interfaces/imwproxy.h> #include <util/gui/clearlineeditaddon.h> #include "core.h" #include "summary.h" #include "modeldelegate.h" Q_DECLARE_METATYPE (QMenu*) namespace LeechCraft { namespace Summary { QObject *SummaryWidget::S_ParentMultiTabs_ = 0; class SearchWidget : public QWidget { QLineEdit *Edit_; public: SearchWidget (SummaryWidget *summary) : Edit_ (new QLineEdit) { auto lay = new QHBoxLayout; setLayout (lay); Edit_->setPlaceholderText (SummaryWidget::tr ("Search...")); Edit_->setMaximumWidth (400); Edit_->setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Fixed); lay->addStretch (); lay->addWidget (Edit_, 0, Qt::AlignRight); new Util::ClearLineEditAddon (Core::Instance ().GetProxy (), Edit_); connect (Edit_, SIGNAL (textChanged (QString)), summary, SLOT (filterParametersChanged ())); connect (Edit_, SIGNAL (returnPressed ()), summary, SLOT (feedFilterParameters ())); } QString GetText () const { return Edit_->text (); } void SetText (const QString& text) { Edit_->setText (text); } }; SummaryWidget::SummaryWidget (QWidget *parent) : QWidget (parent) , FilterTimer_ (new QTimer) , SearchWidget_ (CreateSearchWidget ()) , Toolbar_ (new QToolBar) , Sorter_ (Core::Instance ().GetTasksModel ()) { Toolbar_->setWindowTitle ("Summary"); connect (Toolbar_.get (), SIGNAL (actionTriggered (QAction*)), this, SLOT (handleActionTriggered (QAction*))); Toolbar_->addWidget (SearchWidget_); Ui_.setupUi (this); Ui_.PluginsTasksTree_->setItemDelegate (new ModelDelegate (this)); FilterTimer_->setSingleShot (true); FilterTimer_->setInterval (800); connect (FilterTimer_, SIGNAL (timeout ()), this, SLOT (feedFilterParameters ())); Ui_.ControlsDockWidget_->hide (); auto pm = Core::Instance ().GetProxy ()->GetPluginsManager (); for (const auto plugin : pm->GetAllCastableRoots<IJobHolder*> ()) ConnectObject (plugin); Ui_.PluginsTasksTree_->setModel (Sorter_); connect (Sorter_, SIGNAL (dataChanged (QModelIndex, QModelIndex)), this, SLOT (checkDataChanged (QModelIndex, QModelIndex))); connect (Sorter_, SIGNAL (modelAboutToBeReset ()), this, SLOT (handleReset ())); connect (Sorter_, SIGNAL (rowsAboutToBeRemoved (QModelIndex, int, int)), this, SLOT (checkRowsToBeRemoved (QModelIndex, int, int))); connect (Ui_.PluginsTasksTree_->selectionModel (), SIGNAL (currentRowChanged (QModelIndex, QModelIndex)), this, SLOT (updatePanes (QModelIndex, QModelIndex))); connect (Ui_.PluginsTasksTree_->selectionModel (), SIGNAL (currentRowChanged (QModelIndex, QModelIndex)), this, SLOT (syncSelection (QModelIndex)), Qt::QueuedConnection); const auto itemsHeader = Ui_.PluginsTasksTree_->header (); const auto& fm = fontMetrics (); itemsHeader->resizeSection (0, fm.width ("Average download job or torrent name is just like this.")); itemsHeader->resizeSection (1, fm.width ("Of the download.")); itemsHeader->resizeSection (2, fm.width ("99.99% (1024.0 kb from 1024.0 kb at 1024.0 kb/s)")); ReconnectModelSpecific (); } void SummaryWidget::ReconnectModelSpecific () { const auto sel = Ui_.PluginsTasksTree_->selectionModel (); #define C2(sig,sl,arg1,arg2) \ if (mo->indexOfMethod (QMetaObject::normalizedSignature ("handleTasksTreeSelection" #sl "(" #arg1 ", " #arg2 ")")) != -1) \ connect (sel, \ SIGNAL (sig (arg1, arg2)), \ object, \ SLOT (handleTasksTreeSelection##sl (arg1, arg2))); auto pm = Core::Instance ().GetProxy ()->GetPluginsManager (); Q_FOREACH (QObject *object, pm->GetAllCastableRoots<IJobHolder*> ()) { const auto *mo = object->metaObject (); C2 (currentChanged, CurrentChanged, QModelIndex, QModelIndex); C2 (currentColumnChanged, CurrentColumnChanged, QModelIndex, QModelIndex); C2 (currentRowChanged, CurrentRowChanged, QModelIndex, QModelIndex); } #undef C2 } void SummaryWidget::ConnectObject (QObject *object) { const auto *mo = object->metaObject (); #define C1(sig,sl,arg) \ if (mo->indexOfMethod (QMetaObject::normalizedSignature ("handleTasksTree" #sl "(" #arg ")")) != -1) \ connect (Ui_.PluginsTasksTree_, \ SIGNAL (sig (arg)), \ object, \ SLOT (handleTasksTree##sl (arg))); C1 (activated, Activated, QModelIndex); C1 (clicked, Clicked, QModelIndex); C1 (doubleClicked, DoubleClicked, QModelIndex); C1 (entered, Entered, QModelIndex); C1 (pressed, Pressed, QModelIndex); C1 (viewportEntered, ViewportEntered, ); #undef C1 } SummaryWidget::~SummaryWidget () { Toolbar_->clear (); QWidget *widget = Ui_.ControlsDockWidget_->widget (); Ui_.ControlsDockWidget_->setWidget (0); if (widget) widget->setParent (0); delete Sorter_; } void SummaryWidget::SetParentMultiTabs (QObject *parent) { S_ParentMultiTabs_ = parent; } void SummaryWidget::Remove () { emit needToClose (); } QToolBar* SummaryWidget::GetToolBar () const { return Toolbar_.get (); } QList<QAction*> SummaryWidget::GetTabBarContextMenuActions () const { return QList<QAction*> (); } QObject* SummaryWidget::ParentMultiTabs () { return S_ParentMultiTabs_; } TabClassInfo SummaryWidget::GetTabClassInfo () const { return qobject_cast<Summary*> (S_ParentMultiTabs_)->GetTabClasses ().first (); } SearchWidget* SummaryWidget::CreateSearchWidget () { return new SearchWidget (this); } void SummaryWidget::ReinitToolbar () { Q_FOREACH (QAction *action, Toolbar_->actions ()) { auto wa = qobject_cast<QWidgetAction*> (action); if (!wa || wa->defaultWidget () != SearchWidget_) { Toolbar_->removeAction (action); delete action; } else if (wa->defaultWidget () != SearchWidget_) Toolbar_->removeAction (action); } } QList<QAction*> SummaryWidget::CreateProxyActions (const QList<QAction*>& actions, QObject *parent) const { QList<QAction*> proxies; Q_FOREACH (QAction *action, actions) { if (qobject_cast<QWidgetAction*> (action)) { proxies << action; continue; } QAction *pa = new QAction (action->icon (), action->text (), parent); if (action->isSeparator ()) pa->setSeparator (true); else { pa->setCheckable (action->isCheckable ()); pa->setChecked (action->isChecked ()); pa->setShortcuts (action->shortcuts ()); pa->setStatusTip (action->statusTip ()); pa->setToolTip (action->toolTip ()); pa->setWhatsThis (action->whatsThis ()); pa->setData (QVariant::fromValue<QObject*> (action)); connect (pa, SIGNAL (hovered ()), action, SIGNAL (hovered ())); connect (pa, SIGNAL (toggled (bool)), action, SIGNAL (toggled (bool))); } proxies << pa; } return proxies; } QByteArray SummaryWidget::GetTabRecoverData () const { QByteArray result; QDataStream out (&result, QIODevice::WriteOnly); out << static_cast<quint8> (1); return result; } QString SummaryWidget::GetTabRecoverName () const { return GetTabClassInfo ().VisibleName_; } QIcon SummaryWidget::GetTabRecoverIcon () const { return GetTabClassInfo ().Icon_; } void SummaryWidget::RestoreState (const QByteArray& data) { QDataStream in (data); quint8 version = 0; in >> version; if (version != 1) { qWarning () << Q_FUNC_INFO << "unknown version"; return; } } void SummaryWidget::SetUpdatesEnabled (bool) { // TODO implement this } Ui::SummaryWidget SummaryWidget::GetUi () const { return Ui_; } void SummaryWidget::handleActionTriggered (QAction *proxyAction) { QAction *action = qobject_cast<QAction*> (proxyAction-> data ().value<QObject*> ()); QItemSelectionModel *selModel = Ui_.PluginsTasksTree_->selectionModel (); QModelIndexList indexes = selModel->selectedRows (); action->setProperty ("SelectedRows", QVariant::fromValue<QList<QModelIndex>> (indexes)); action->setProperty ("ItemSelectionModel", QVariant::fromValue<QObject*> (selModel)); action->activate (QAction::Trigger); } void SummaryWidget::checkDataChanged (const QModelIndex& topLeft, const QModelIndex& bottomRight) { const QModelIndex& cur = Ui_.PluginsTasksTree_-> selectionModel ()->currentIndex (); if (topLeft.row () <= cur.row () && bottomRight.row () >= cur.row ()) updatePanes (cur, cur); } void SummaryWidget::handleReset () { Ui_.PluginsTasksTree_->selectionModel ()->clear (); } void SummaryWidget::checkRowsToBeRemoved (const QModelIndex&, int begin, int end) { const QModelIndex& cur = Ui_.PluginsTasksTree_-> selectionModel ()->currentIndex (); if (begin <= cur.row () && end >= cur.row ()) Ui_.PluginsTasksTree_->selectionModel ()->clear (); } void SummaryWidget::updatePanes (const QModelIndex& newIndex, const QModelIndex& oldIndex) { QToolBar *controls = Core::Instance ().GetControls (newIndex); QWidget *addiInfo = Core::Instance ().GetAdditionalInfo (newIndex); if (oldIndex.isValid () && addiInfo != Ui_.ControlsDockWidget_->widget ()) Ui_.ControlsDockWidget_->hide (); if (Core::Instance ().SameModel (newIndex, oldIndex)) return; ReinitToolbar (); if (newIndex.isValid ()) { if (controls) { Q_FOREACH (QAction *action, controls->actions ()) { QString ai = action->property ("ActionIcon").toString (); if (!ai.isEmpty () && action->icon ().isNull ()) action->setIcon (Core::Instance ().GetProxy ()-> GetIconThemeManager ()->GetIcon (ai)); } const auto& proxies = CreateProxyActions (controls->actions (), Toolbar_.get ()); Toolbar_->insertActions (Toolbar_->actions ().first (), proxies); } if (addiInfo != Ui_.ControlsDockWidget_->widget ()) Ui_.ControlsDockWidget_->setWidget (addiInfo); if (addiInfo) { Ui_.ControlsDockWidget_->show (); Core::Instance ().GetProxy ()->GetIconThemeManager ()-> UpdateIconset (addiInfo->findChildren<QAction*> ()); } } } void SummaryWidget::filterParametersChanged () { FilterTimer_->stop (); FilterTimer_->start (); } void SummaryWidget::filterReturnPressed () { FilterTimer_->stop (); feedFilterParameters (); } void SummaryWidget::feedFilterParameters () { Sorter_->setFilterFixedString (SearchWidget_->GetText ()); } void SummaryWidget::on_PluginsTasksTree__customContextMenuRequested (const QPoint& pos) { QModelIndex current = Ui_.PluginsTasksTree_->currentIndex (); QMenu *sourceMenu = current.data (RoleContextMenu).value<QMenu*> (); if (!sourceMenu) return; QMenu *menu = new QMenu (); connect (menu, SIGNAL (triggered (QAction*)), this, SLOT (handleActionTriggered (QAction*))); menu->setAttribute (Qt::WA_DeleteOnClose, true); menu->addActions (CreateProxyActions (sourceMenu->actions (), menu)); menu->setTitle (sourceMenu->title ()); menu->popup (Ui_.PluginsTasksTree_->viewport ()->mapToGlobal (pos)); } void SummaryWidget::syncSelection (const QModelIndex& current) { QItemSelectionModel *selm = Ui_.PluginsTasksTree_->selectionModel (); const QModelIndex& now = selm->currentIndex (); if (current != now || (now.isValid () && !selm->rowIntersectsSelection (now.row (), QModelIndex ()))) { selm->select (now, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); updatePanes (now, current); } } } }
28.390397
125
0.686521
7e3044e1f0bee2fa979528e79a9b8a20527e7894
910
hpp
C++
mod08/ex02/mutantStack.hpp
paozer/piscine_cpp
449d4a60b3c50c7ba6d94e38a7b632b5f447a438
[ "Unlicense" ]
null
null
null
mod08/ex02/mutantStack.hpp
paozer/piscine_cpp
449d4a60b3c50c7ba6d94e38a7b632b5f447a438
[ "Unlicense" ]
null
null
null
mod08/ex02/mutantStack.hpp
paozer/piscine_cpp
449d4a60b3c50c7ba6d94e38a7b632b5f447a438
[ "Unlicense" ]
2
2021-01-31T13:52:11.000Z
2021-05-19T18:36:17.000Z
#pragma once #ifndef MUTANTSTACK_HPP #define MUTANTSTACK_HPP #include <iterator> #include <deque> #include <stack> template <typename T, typename Container = std::deque<T> > class mutantStack : public std::stack<T, Container> { public: mutantStack() {} mutantStack(const mutantStack & other) { *this = other; } ~mutantStack() {} mutantStack & operator=(const mutantStack & other) { // in stack class definition c is the underlying container here deque if (this != &other) std::stack<T, Container>::c = other.std::stack<T, Container>::c; return *this; } typedef typename Container::iterator iterator; // necessary for mutantStack<T>::iterator iterator begin() { return std::stack<T, Container>::c.begin(); } iterator end() { return std::stack<T, Container>::c.end(); } }; #endif
30.333333
96
0.617582
7e305c2400bc8774a10c5cc9dec4757f2847085b
1,031
hpp
C++
RayCharles/Sphere.hpp
CoderGirl42/RayTracer
4e370864ec6b9c02ea030a9cbe4354b2d55f3aba
[ "MIT" ]
null
null
null
RayCharles/Sphere.hpp
CoderGirl42/RayTracer
4e370864ec6b9c02ea030a9cbe4354b2d55f3aba
[ "MIT" ]
null
null
null
RayCharles/Sphere.hpp
CoderGirl42/RayTracer
4e370864ec6b9c02ea030a9cbe4354b2d55f3aba
[ "MIT" ]
null
null
null
#pragma once #include "Entity.hpp" class _MMX_ALIGN_ Sphere : public Entity { public: Sphere() {} Sphere(const Vec3& c, real r) : Center(c), Radius(r) {}; virtual bool Hit(const Ray& r, real t_min, real t_max, HitRecord& rec); Vec3 Center; real Radius; Entity *Entity; }; bool Sphere::Hit(const Ray& r, real t_min, real t_max, HitRecord& rec) { Vec3 oc = r.Origin() - Center; real a = r.Direction().Dot(r.Direction()); real b = oc.Dot(r.Direction()); real c = oc.Dot(oc) - Radius * Radius; real discriminant = b * b - a * c; if (discriminant > 0) { float temp = (-b - SQRT(b * b - a * c)) / a; if (temp < t_max && temp > t_min) { rec.t = temp; rec.p = r.PointAtParameter(rec.t); rec.normal = (rec.p - Center) / Radius; rec.e = this; return true; } temp = (-b + SQRT(b * b - a * c)) / a; if (temp < t_max && temp > t_min) { rec.t = temp; rec.p = r.PointAtParameter(rec.t); rec.normal = (rec.p - Center) / Radius; rec.e = this; return true; } } return false; }
19.092593
72
0.587779
cce1758fd8acd349c852f95809bfb32fcc86af24
51,552
cpp
C++
solarpilot/Toolbox.cpp
rchintala13/ssc
3424d9b1bfab50cc11d1895d0893cf1771fd3a5e
[ "BSD-3-Clause" ]
null
null
null
solarpilot/Toolbox.cpp
rchintala13/ssc
3424d9b1bfab50cc11d1895d0893cf1771fd3a5e
[ "BSD-3-Clause" ]
null
null
null
solarpilot/Toolbox.cpp
rchintala13/ssc
3424d9b1bfab50cc11d1895d0893cf1771fd3a5e
[ "BSD-3-Clause" ]
1
2017-10-01T08:36:05.000Z
2017-10-01T08:36:05.000Z
/** BSD-3-Clause Copyright 2019 Alliance for Sustainable Energy, LLC 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, CONTRIBUTORS, UNITED STATES GOVERNMENT OR UNITED STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 "math.h" #include <stdio.h> #include <ctime> #include <vector> #include <algorithm> #include "Toolbox.h" #include "definitions.h" using namespace std; // ----------- points and vectors ----------------------- sp_point::sp_point(){}; sp_point::sp_point( const sp_point &P ) : x(P.x), y(P.y), z(P.z) { } sp_point::sp_point(double X, double Y, double Z) : x(X), y(Y), z(Z) { } void sp_point::Set(double _x, double _y, double _z) { this->x = _x; this->y = _y; this->z = _z; } void sp_point::Set( sp_point &P ) { this->x = P.x; this->y = P.y; this->z = P.z; } void sp_point::Add( sp_point &P ) { this->x+=P.x; this->y+=P.y; this->z+=P.z; } void sp_point::Add(double _x, double _y, double _z) { this->x += _x; this->y += _y; this->z += _z; } void sp_point::Subtract( sp_point &P ) { this->x += -P.x; this->y += -P.y; this->z += -P.z; } double& sp_point::operator [](const int &index){ switch (index) { case 0: return x; break; case 1: return y; break; case 2: return z; break; default: throw spexception("Index out of range in sp_point()"); break; } }; bool sp_point::operator <(const sp_point &p) const { return this->x < p.x || (this->x == p.x && this->y < p.y); }; Vect::Vect(){}; Vect::Vect( const Vect &V ) : i(V.i), j(V.j), k(V.k) {} Vect::Vect(double i, double j, double k ) : i(i), j(j), k(k) { } void Vect::Set(double _i, double _j, double _k) { i=_i; j=_j; k=_k; } void Vect::Set( Vect &V ) { i = V.i; j = V.j; k = V.k; } void Vect::Add( Vect &V ) { i+=V.i; j+=V.j; k+=V.k; } void Vect::Subtract( Vect &V ) { i+=-V.i; j+=-V.j; k+=-V.k; } void Vect::Add(double _i, double _j, double _k) { i+=_i; j+=_j; k+=_k; } void Vect::Scale( double m ) { i *= m; j *= m; k *= m; } double &Vect::operator[](int index){ if( index == 0) return i; if( index == 1) return j; if( index == 2) return k; throw spexception("Index out of range in Vect()"); //range error }; PointVect::PointVect(const PointVect &v){ x = v.x; y=v.y; z=v.z; i = v.i; j=v.j; k=v.k; } PointVect& PointVect::operator= (const PointVect &v) { x = v.x; y=v.y; z=v.z; i = v.i; j=v.j; k=v.k; return *this; } PointVect::PointVect(double px, double py, double pz, double vi, double vj, double vk) { x=px; y=py; z=pz; i=vi; j=vj; k=vk; } sp_point *PointVect::point() { p.Set(x, y, z); return &p; }; Vect *PointVect::vect() { v.Set(i, j, k); return &v; }; //------------------------------------------------------- //------------------ DTObj class ------------------------------------- DTobj::DTobj() { setZero(); } void DTobj::setZero() { _year=0; _month=0; _yday=0; _mday=0; _wday=0; _hour=0; _min=0; _sec=0; _ms=0; } DTobj *DTobj::Now() { struct tm now; #ifdef _MSC_VER __time64_t long_time; // Get time as 64-bit integer. _time64( &long_time ); // Convert to local time. _localtime64_s( &now, &long_time ); #else time_t long_time; // Get time as 64-bit integer. time( &long_time ); // Convert to local time. now = *localtime(&long_time); #endif _year=now.tm_year+1900; _month=now.tm_mon; _yday=now.tm_yday; _mday=now.tm_mday; _wday=now.tm_wday; _hour=now.tm_hour; _min=now.tm_min; _sec=now.tm_sec; _ms=0; return this; } //------------------------------------------------------- //-----------------------DateTime class------------------- //accessors //GETS int DateTime::GetYear(){return _year;} int DateTime::GetMonth(){return _month;} int DateTime::GetYearDay(){return _yday;}; int DateTime::GetMonthDay(){return _mday;} int DateTime::GetWeekDay(){return _wday;} int DateTime::GetMinute(){return _min;}; int DateTime::GetSecond() {return _sec;}; int DateTime::GetMillisecond(){return _ms;}; // SETS void DateTime::SetYear(const int val){_year=val; SetMonthLengths(_year);} void DateTime::SetMonth(const int val){_month=val;} void DateTime::SetYearDay(const int val){_yday=val;} void DateTime::SetMonthDay(const int val){_mday=val;} void DateTime::SetWeekDay(const int val){_wday=val;} void DateTime::SetHour(const int val){_hour=val;} void DateTime::SetMinute(const int val){_min=val;} void DateTime::SetSecond(const int val){_sec=val;} void DateTime::SetMillisecond(const int val){_ms=val;} //Default constructor DateTime::DateTime(){ //Initialize all variables to the current date and time setDefaults(); } DateTime::DateTime(double doy, double hour){ //Convert from fractional hours to integer values for hr, min, sec int hr = int(floor(hour)); double minutes = 60. * (hour - double(hr)); int min = int(floor(minutes)); int sec = int(60.*(minutes - double(min))); setZero(); //Zero values SetYearDay(int(doy+.001)); //day of the year SetHour(hr); SetMinute(min); SetSecond(sec); } //Fully specified constructor DateTime::DateTime(DTobj &DT) { _year=DT._year; _month=DT._month; _yday=DT._yday; _mday=DT._mday; _wday=DT._wday; _hour=DT._hour; _min=DT._min; _sec=DT._sec; _ms=DT._ms; //Initialize the month lengths array SetMonthLengths(_year); } void DateTime::setDefaults(){ setZero(); //everything zeros but the day of year and year (hr=12 is noon) //Get the current year and set it as the default value DTobj N; N.Now(); //SetYear(N._year); SetYear(2011); //Choose a non-leap year SetMonth(6); SetMonthDay(21); SetYearDay( GetDayOfYear() ); //Summer solstice SetHour(12); } void DateTime::SetDate(int year, int month, int day) { //Given a year, month (1-12), and day of the month (1-N), set the values. Leave the time as it is SetYear(year); SetMonth(month); SetMonthDay(day); SetMonthLengths(_year); SetYearDay( GetDayOfYear(year, month, day) ); } void DateTime::SetMonthLengths(const int year){ /* Calculate the number of days in each month and assign the result to the monthLength[] array. Provide special handling for 4-year, 100-year, and 400-year leap years.*/ //Initialize the array of month lengths (accounting for leap year) for (int i=0; i<12; i+=2){ monthLength[i]=31; }; for (int i=1; i<12; i+=2){ monthLength[i]=30; }; //Given the year, determine how many days are in Feb. monthLength[1]=28; //Default if(year%4==0) {monthLength[1]=29;} //All years divisible by 4 are leap years if(year%100==0){ //All years divisible by 100 are not leap years, unless... if(year%400 == 0){monthLength[1]=29;} //.. the year is also divisible by 400. else {monthLength[1]=28;} }; } int DateTime::GetDayOfYear(){ int val = GetDayOfYear(_year, _month, _mday); return val; } int DateTime::GetDayOfYear(int /*year*/, int month, int mday){ //Return the day of the year specified by the class day/month/year class members //Day of the year runs from 1-365 int doy=0; if(month>1) { for (int i=0; i<month-1; i++) {doy+=monthLength[i];}; }; doy+= mday; return doy; } int DateTime::CalculateDayOfYear( int year, int month, int mday ){ //Static version int monthLength[12]; //Initialize the array of month lengths (accounting for leap year) for (int i=0; i<12; i+=2){ monthLength[i]=31; }; for (int i=1; i<12; i+=2){ monthLength[i]=30; }; //Given the year, determine how many days are in Feb. monthLength[1]=28; //Default if(year%4==0) {monthLength[1]=29;} //All years divisible by 4 are leap years if(year%100==0){ //All years divisible by 100 are not leap years, unless... if(year%400 == 0){monthLength[1]=29;} //.. the year is also divisible by 400. else {monthLength[1]=28;} }; int doy=0; if(month>1) { for (int i=0; i<month-1; i++) {doy+=monthLength[i];}; }; doy+= mday; return doy; } int DateTime::GetHourOfYear(){ //Return the hour of the year according to the values specified by the class members int doy = GetDayOfYear(); int hr = (doy-1)*24 + _hour; return hr; }; void DateTime::hours_to_date(double hours, int &month, int &day_of_month){ /* Take hour of the year (0-8759) and convert it to month and day of the month. If the year is not provided, the default is 2011 (no leap year) Month = 1-12 Day = 1-365 The monthLength[] array contains the number of days in each month. This array is taken from the DateTime class and accounts for leap years. To modify the year to not include leap year days, change the year in the DateTime instance. */ double days = hours/24.; int dsum=0; for(int i=0; i<12; i++){ dsum += monthLength[i]; if(days <= dsum){month = i+1; break;} } day_of_month = (int)floor(days - (dsum - monthLength[month-1]))+1; } std::string DateTime::GetMonthName(int month){ switch(month) { case 1: return "January"; case 2: return "February"; case 3: return "March"; case 4: return "April"; case 5: return "May"; case 6: return "June"; case 7: return "July"; case 8: return "August"; case 9: return "September"; case 10: return "October"; case 11: return "November"; case 12: return "December"; default: return ""; } } //---------Weather data object class -------------------- //Copy constructor WeatherData::WeatherData( const WeatherData &wd) : _N_items( wd._N_items ), Day( wd.Day ), Hour( wd.Hour ), Month( wd.Month ), DNI( wd.DNI ), T_db( wd.T_db ), Pres( wd.Pres ), V_wind( wd.V_wind ), Step_weight( wd.Step_weight ) { //Recreate the pointer array initPointers(); } WeatherData::WeatherData(){ initPointers(); }; void WeatherData::initPointers(){ //On initialization, create a vector of pointers to all of the data arrays v_ptrs.resize(8); v_ptrs.at(0) = &Day; v_ptrs.at(1) = &Hour; v_ptrs.at(2) = &Month; v_ptrs.at(3) = &DNI; v_ptrs.at(4) = &T_db; v_ptrs.at(5) = &Pres; v_ptrs.at(6) = &V_wind; v_ptrs.at(7) = &Step_weight; //Initialize the number of items _N_items = (int)Day.size(); } void WeatherData::resizeAll(int size, double val){ for(unsigned int i=0; i<v_ptrs.size(); i++){ v_ptrs.at(i)->resize(size, val); _N_items = size; } }; void WeatherData::clear() { for(unsigned int i=0; i<v_ptrs.size(); i++){ v_ptrs.at(i)->clear(); _N_items = 0; } } void WeatherData::getStep(int step, double &day, double &hour, double &dni, double &step_weight){ //retrieve weather data from the desired time step day = Day.at(step); hour = Hour.at(step); dni = DNI.at(step); step_weight = Step_weight.at(step); } void WeatherData::getStep(int step, double &day, double &hour, double &month, double &dni, double &tdb, double &pres, double &vwind, double &step_weight){ double *args[] = {&day, &hour, &month, &dni, &tdb, &pres, &vwind, &step_weight}; //retrieve weather data from the desired time step for(unsigned int i=0; i<v_ptrs.size(); i++){ *args[i] = v_ptrs.at(i)->at(step); } } void WeatherData::append(double day, double hour, double dni, double step_weight){ Day.push_back(day); Hour.push_back( hour ); DNI.push_back( dni ); Step_weight.push_back( step_weight ); _N_items ++; } void WeatherData::append(double day, double hour, double month, double dni, double tdb, double pres, double vwind, double step_weight){ Day.push_back( day ); Hour.push_back( hour ); Month.push_back( month ); DNI.push_back( dni ); T_db.push_back( tdb ); Pres.push_back( pres ); V_wind.push_back( vwind ); Step_weight.push_back( step_weight ); _N_items ++; } void WeatherData::setStep(int step, double day, double hour, double dni, double step_weight){ Day.at(step) = day; Hour.at(step) = hour; DNI.at(step) = dni; Step_weight.at(step) = step_weight; } void WeatherData::setStep(int step, double day, double hour, double month, double dni, double tdb, double pres, double vwind, double step_weight){ Day.at(step) = day; Hour.at(step) = hour; Month.at(step) = month; DNI.at(step) = dni; T_db.at(step) = tdb; Pres.at(step) = pres; V_wind.at(step) = vwind; Step_weight.at(step) = step_weight; } std::vector<std::vector<double>*> *WeatherData::getEntryPointers() { return &v_ptrs; } //-----------------------Toolbox namespace-------------------- //misc double Toolbox::round(double x){ return fabs(x - ceil(x)) > 0.5 ? floor(x) : ceil(x); } void Toolbox::writeMatD(string dir, string name, matrix_t<double> &mat, bool clear){ //write the data to a log file FILE *file; //ofstream file; string path; path.append(dir); path.append("\\matrix_data_log.txt"); if( clear ) { file = fopen(path.c_str(), "w"); } else{ file = fopen(path.c_str(), "a"); } int nr = (int)mat.nrows(); int nc = (int)mat.ncols(); fprintf(file, "%s\n", name.c_str()); for (int i=0; i<nr; i++){ for (int j=0; j<nc; j++){ fprintf(file, "%e\t", mat.at(i,j)); } fprintf(file, "%s", "\n"); } fprintf(file, "%s", "\n"); fclose(file); } void Toolbox::writeMatD(string dir, string name, block_t<double> &mat, bool clear){ //write the data to a log file FILE *file; //ofstream file; string path; path.append(dir); path.append("\\matrix_data_log.txt"); if( clear ) { file =fopen(path.c_str(), "w"); } else{ file =fopen(path.c_str(), "a"); } int nr = (int)mat.nrows(); int nc = (int)mat.ncols(); int nl = (int)mat.nlayers(); fprintf(file, "%s\n", name.c_str()); for (int k=0; k<nl; k++){ fprintf(file, "%i%s", k, "--\n"); for (int i=0; i<nr; i++){ for (int j=0; j<nc; j++){ fprintf(file, "%e\t", mat.at(i,j,k)); } fprintf(file, "%s", "\n"); } } fprintf(file, "%s", "\n"); fclose(file); } void Toolbox::swap(double &a, double &b){ //Swap the values in A and B double xt = a; a = b; b = xt; } void Toolbox::swap(double *a, double *b){ double xt = *a; *a = *b; *b = xt; } double Toolbox::atan3(double &x, double &y){ double v = atan2(x,y); return v < 0. ? v += 2.*PI : v; } void Toolbox::map_profiles(double *source, int nsource, double *dest, int ndest, double *weights){ /* Take a source array 'source(nsource)' and map the values to 'dest(ndest)'. This method creates an integral-conserved map of values in 'dest' that may have a different number of elements than 'source'. The size of each node within 'source' is optionally specified by the 'weights(nsource)' array. If all elements are of the same size, set weights=(double*)NULL or omit the optional argument. */ double *wsize; double wtot = 0.; if(weights != (double*)NULL){ wsize = new double[nsource]; for(int i=0; i<nsource; i++){ wtot += weights[i]; //sum up weights wsize[i] = weights[i]; } } else{ wsize = new double[nsource]; for(int i=0; i<nsource; i++) wsize[i] = 1.; wtot = (double)nsource; } double delta_D = wtot/(double)ndest; int i=0; double ix = 0.; for(int j=0; j<ndest; j++){ dest[j] = 0.; double jx = (double)(j+1)*delta_D, jx0 = (double)j*delta_D; //From previous step if(ix-jx0>0) dest[j] += (ix-jx0)*source[i-1]; //internal steps while(ix < jx ){ ix += wsize[i]; dest[j] += wsize[i] * source[i]; i++; } //subtract overage if(ix > jx ) dest[j] += -(ix-jx)*source[i-1]; //Divide by length dest[j] *= 1./delta_D; } //Memory cleanup delete [] wsize; } /* Factorial of an integer x*/ int Toolbox::factorial(int x) { //if (floor(3.2)!=x) { cout << "Factorial must be an integer!" }; int f = x; for (int i=1; i<x; i++) { int j=x-i; f=f*j; } if(f<1) f=1; //Minimum of any factorial is 1 return f; } double Toolbox::factorial_d(int x) { //returns the same as factorial, but with a doub value return double(factorial(x)); } bool Toolbox::pointInPolygon( const vector< sp_point > &poly, const sp_point &pt) { /* This subroutine takes a polynomial array containing L_poly vertices (X,Y,Z) and a single point (X,Y,Z) and determines whether the point lies within the polygon. If so, the algorithm returns TRUE (otherwise FALSE) */ //if polywind returns a number between -1 and 1, the point is in the polygon int wind = polywind(poly, pt); if (wind == -1 || wind == 1) { return true;} else {return false;} } vector<sp_point> Toolbox::projectPolygon(vector<sp_point> &poly, PointVect &plane) { /* Take a polygon with points in three dimensions (X,Y,Z) and project all points onto a plane defined by the point-vector {x,y,z,i,j,k}. The subroutine returns a new polygon with the adjusted points all lying on the plane. The points are also assigned vector values corresponding to the normal vector of the plane that they lie in.*/ //Declare variables double dist, A, B, C, D; sp_point pt; //Declare a new polygon of type vector int Lpoly = (int)poly.size(); vector< sp_point > FPoly(Lpoly); //Determine the coefficients for the equation of the plane {A,B,C,D} A=plane.i; B=plane.j; C=plane.k; Vect uplane; uplane.Set(A,B,C); vectmag(uplane); D = -A*plane.x - B*plane.y - C*plane.z; for (int i=0; i<Lpoly; i++) { //Determine the distance between the point and the plane pt = poly.at(i); dist = -(A*pt.x + B*pt.y + C*pt.z + D)/vectmag(*plane.vect()); //knowing the distance, now shift the point to the plane FPoly.at(i).x = pt.x+dist*A; FPoly.at(i).y = pt.y+dist*B; FPoly.at(i).z = pt.z+dist*C; } return FPoly; } int Toolbox::polywind( const vector<sp_point> &vt, const sp_point &pt) { /* Determine the winding number of a polygon with respect to a point. This helps calculate the inclusion/exclusion of the point inside the polygon. If the point is inside the polygon, the winding number is equal to -1 or 1. */ //Declarations int i, np, wind = 0, which_ign; double d0=0., d1=0., p0=0., p1=0., pt0=0., pt1=0.; /*The 2D polywind function can be mapped to 3D polygons by choosing a single dimension to ignore. The best ignored dimension corresponds to the largest magnitude component of the normal vector to the plane containing the polygon.*/ //Get the cross product of the first three points in the polygon to determine the planar normal vector Vect v1, v2; v1.Set((vt.at(0).x-vt.at(1).x),(vt.at(0).y - vt.at(1).y),(vt.at(0).z - vt.at(1).z)); v2.Set((vt.at(2).x-vt.at(1).x),(vt.at(2).y - vt.at(1).y),(vt.at(2).z - vt.at(1).z)); Vect pn = crossprod( v1, v2 ); which_ign = 1; if(fabs(pn.j) > fabs(pn.i)) {which_ign=1;} if(fabs(pn.k) > fabs(pn.j)) {which_ign=2;} if(fabs(pn.i) > fabs(pn.k)) {which_ign=0;} /* Return the winding number of a polygon (specified by a vector of vertex points vt) around an arbitrary point pt.*/ np = (int)vt.size(); switch (which_ign) { case 0: pt0 = pt.y; pt1 = pt.z; p0 = vt[np-1].y; p1 = vt[np-1].z; break; case 1: pt0 = pt.x; pt1 = pt.z; p0 = vt[np-1].x; p1 = vt[np-1].z; break; case 2: pt0 = pt.x; pt1 = pt.y; p0 = vt[np-1].x; p1 = vt[np-1].y; } for (i=0; i<np; i++) { switch (which_ign) { case 0: d0 = vt[i].y; d1 = vt[i].z; break; case 1: d0 = vt[i].x; d1 = vt[i].z; break; case 2: d0 = vt[i].x; d1 = vt[i].y; } if (p1 <= pt1) { if (d1 > pt1 && (p0-pt0)*(d1-pt1)-(p1-pt1)*(d0-pt0) > 0) wind++; } else { if (d1 <= pt1 && (p0-pt0)*(d1-pt1)-(p1-pt1)*(d0-pt0) < 0) wind--; } p0=d0; p1=d1; } return wind; } Vect Toolbox::crossprod(const Vect &A, const Vect &B) { /* Calculate the cross product of two vectors. The magnitude of the cross product represents the area contained in a parallelogram bounded by the multipled vectors.*/ Vect res; res.i = A.j*B.k - A.k*B.j; res.j = A.k*B.i - A.i*B.k; res.k = A.i*B.j - A.j*B.i; return res; }; double Toolbox::crossprod(const sp_point &O, const sp_point &A, const sp_point &B) { //2D cross-product of vectors OA and OB. return (A.x - O.x) * (B.y - O.y) - (A.y - O.y) * (B.x - O.x); } void Toolbox::unitvect(Vect &A) { /*Take a vector that may or may not be in unit vector form and scale the magnitude to make it a unit vector*/ double M = vectmag(A); if(M==0.){A.i=0; A.j=0; A.k=0; return;} A.i /= M; A.j /= M; A.k /= M; return; } double Toolbox::dotprod(const Vect &A, const Vect &B) { return (A.i * B.i + A.j * B.j + A.k * B.k); } double Toolbox::dotprod(const Vect &A, const sp_point &B) { return (A.i * B.x + A.j * B.y + A.k * B.z); } double Toolbox::vectmag(const Vect &A) { return sqrt(pow(A.i,2) + pow(A.j,2) + pow(A.k,2)); } double Toolbox::vectmag(const sp_point &P){ return sqrt( pow(P.x,2) + pow(P.y,2) + pow(P.z,3) ); } double Toolbox::vectmag(double i, double j, double k){ return sqrt( pow(i,2) + pow(j,2) + pow(k,2) ); } double Toolbox::vectangle(const Vect &A, const Vect&B) { //Determine the angle between two vectors return acos(dotprod(A,B)/(vectmag(A)*vectmag(B))); } void Toolbox::rotation(double theta, int axis, Vect &V){ sp_point p; p.Set(V.i, V.j, V.k); Toolbox::rotation(theta, axis, p); V.Set(p.x, p.y, p.z); } void Toolbox::rotation(double theta, int axis, sp_point &P){ /* This method takes a point, a rotation angle, and the axis of rotation and rotates the point about the origin in the specified direction. The inputs are: theta | [rad] | Angle of rotation axis | none | X=0, Y=1, Z=2 : Axis to rotate about The method returns a modified point "P" that has been rotated according to the inputs. Rotation is clockwise about each axis (left hand rule). In other words, positive rotation for each axis is defined by the apparent motion when positive end of the axis points toward the viewer. */ //the 3x3 rotation matrix double MR0i, MR0j, MR0k, MR1i, MR1j, MR1k, MR2i, MR2j, MR2k; double costheta = cos(theta); double sintheta = sin(theta); switch(axis) { /* The rotation vectors are entered in as the transverse for convenience of multiplication. The correct matrix form for each are: X axis [1, 0, 0, 0, cos(theta), -sin(theta), 0, sin(theta), cos(theta)] Y axis [cos(theta), 0, sin(theta), 0, 1, 0, -sin(theta), 0, cos(theta)] Z axis [cos(theta), -sin(theta), 0, sin(theta), cos(theta), 0, 0, 0, 1 ] */ case 0: //X axis //Fill in the x-rotation matrix for this angle theta MR0i = 1; MR0j = 0; MR0k = 0; MR1i = 0; MR1j = costheta; MR1k = sintheta; MR2i = 0; MR2j = -sintheta; MR2k = costheta; break; case 1: //Y axis //Fill in the y-rotation matrix for this angle theta MR0i = costheta; MR0j = 0; MR0k = -sintheta; MR1i = 0; MR1j = 1; MR1k = 0; MR2i = sintheta; MR2j = 0; MR2k = costheta; break; case 2: //Z axis //Fill in the z-rotation matrix for this angle theta MR0i = costheta; MR0j = sintheta; MR0k = 0; MR1i = -sintheta; MR1j = costheta; MR1k = 0; MR2i = 0; MR2j = 0; MR2k = 1; break; default: throw spexception("Internal error: invalid axis number specified in rotation() method."); } //Create a copy of the point double Pcx = P.x; double Pcy = P.y; double Pcz = P.z; //Do the rotation. The A matrix is the rotation vector and the B matrix is the point vector P.x = MR0i*Pcx + MR0j*Pcy + MR0k*Pcz; //dotprod(MR0, Pc); //do the dotprod's here to avoid function call P.y = MR1i*Pcx + MR1j*Pcy + MR1k*Pcz; //dotprod(MR1, Pc); P.z = MR2i*Pcx + MR2j*Pcy + MR2k*Pcz; //dotprod(MR2, Pc); return; } bool Toolbox::plane_intersect(sp_point &P, Vect &N, sp_point &C, Vect &L, sp_point &Int){ /* Determine the intersection point of a line and a plane. The plane is defined by: P | sp_point on the plane N | Normal unit vector to the plane The line/vector is defined by: C | (x,y,z) coordinate of the beginning of the line L | Unit vector pointing along the line The distance 'd' along the unit vector is given by the equation: d = ((P - C) dot N)/(L dot N) The method fills in the values of a point "Int" that is the intersection. In the case that the vector does not intersect with the plane, the method returns FALSE and the point Int is not modified. If an intersection is found, the method will return TRUE. */ double PC[3], LdN, PCdN, d; int i; //Create a vector between P and C for(i=0; i<3; i++){PC[i] = P[i]-C[i];} //Calculate the dot product of L and N LdN = 0.; for(i=0; i<3; i++){ LdN += L[i]*N[i]; } //Calculate the dot product of (P-C) and N PCdN = 0.; for(i=0; i<3; i++){ PCdN += PC[i]*N[i]; } if(LdN == 0.) return false; //Line is parallel to the plane d = PCdN / LdN; //Multiplier on unit vector that intersects the plane //Calculate the coordinates of intersection Int.x = C.x + d*L.i; Int.y = C.y + d*L.j; Int.z = C.z + d*L.k; return true; } bool Toolbox::line_norm_intersect(sp_point &line_p0, sp_point &line_p1, sp_point &P, sp_point &I, double &rad){ /* Note: 2D implementation (no Z component) Given two points that form a line segment (line_p0 and line_p1) and an external point NOT on the line (P), return the location of the intersection (I) between a second line that is normal to the first and passes through P. Also return the corresponding radius 'rad' ||P I||. (line_p0) (I) (line_p1) O--------------X----------------------------O |_| | | O (P) If the normal to the line segment lies outside of the segment, the method returns FALSE, otherwise its TRUE. In the first case, 'I' is equal to the segment point closest to 'P', otherwise it is the intersection point. Solve for 'I' using the derivative of the distance formula (r(x,y)) between I and P. I is the point where dr(x,y)/dx = 0. */ //Check to see if the 'x' components of p0 and p1 are the same, which is undefined slope. if(line_p0.x == line_p1.x){ //check for containment double Iyr = (P.y - line_p0.y)/(line_p1.y - line_p0.y); if(Iyr < 0.){ //out of bounds on the p0 side I.Set(line_p0.x, line_p0.y, 0.); rad = vectmag(I.x - P.x, I.y - P.y, 0.); return false; } else if(Iyr > 1.){ //out of bounds on the p1 side I.Set(line_p1.x, line_p1.y, 0.); rad = vectmag(I.x - P.x, I.y - P.y, 0.); return false; } I.Set(line_p0.x, P.y, 0.); } double drdx = (line_p1.y - line_p0.y)/(line_p1.x - line_p0.x), drdx_sq = pow(drdx,2); I.x = (P.x + P.y * drdx - line_p0.y*drdx + line_p0.x*drdx_sq)/(1. + drdx_sq); //check for containment double Ixr = (I.x - line_p0.x)/(line_p1.x - line_p0.x); if(Ixr < 0.){ //outside the bounds on the p0 side I.x = line_p0.x; I.y = line_p0.y; rad = vectmag(I.x - P.x, I.y - P.y, 0.); return false; } else if(Ixr > 1.){ //outside the bounds on the p1 side I.x = line_p1.x; I.y = line_p1.y; rad = vectmag(I.x - P.x, I.y - P.y, 0.); return false; } //in bounds I.y = line_p0.y + (I.x - line_p0.x)*drdx; rad = vectmag(I.x - P.x, I.y - P.y, 0.); return true; } void Toolbox::ellipse_bounding_box(double &A, double &B, double &phi, double sides[4], double cx, double cy){ /* This algorithm takes an ellipse in a plane at location {cx,cy} and with unrotated X axis size A, unrotated Y axis size B, and with angle of rotation 'phi' [radians] and calculates the bounding box edge locations in the coordinate system of the plane. This method fills the 'sides' array with values for: sides[0] | x-axis minimum sides[1] | x-axis maximum sides[2] | y-axis minimum sides[3] | y-axis maximum Reference: http://stackoverflow.com/questions/87734/how-do-you-calculate-the-axis-aligned-bounding-box-of-an-ellipse Governing equations are: x = cx + A*cos(t)*cos(phi) - b*sin(t)*sin(phi) y = cy + b*sin(t)*cos(phi) - a*cos(t)*sin(phi) where 't' is an eigenvalue with repeating solutions of dy/dt=0 For X values: 0 = dx/dt = -A*sin(t)*cos(phi) - B*cos(t)*sin(phi) --> tan(t) = -B*tan(phi)/A --> t = atan( -B*tan(phi)/A ) for Y values: 0 = dy/dt = B*cos(t)*cos(phi) - A*sin(t)*sin(phi) --> tan(t) = B*cot(phi)/A --> t = aan( B*cot(phi)/A ) */ //double pi = PI; //X first //double tx = atan( -B*tan(phi)/A ); double tx = atan2( -B*tan(phi), A); //plug back into the gov. equation double txx = A*cos(tx)*cos(phi) - B*sin(tx)*sin(phi); sides[0] = cx + txx/2.; sides[1] = cx - txx/2.; //enforce orderedness if(sides[1] < sides[0]) swap(&sides[0], &sides[1]); //Y next double ty = atan2( -B, tan(phi)*A ); double tyy = B*sin(ty)*cos(phi) - A*cos(ty)*sin(phi); sides[2] = cy + tyy/2.; sides[3] = cy - tyy/2.; if(sides[3] < sides[2]) swap(&sides[3], &sides[2]); } void Toolbox::convex_hull(std::vector<sp_point> &points, std::vector<sp_point> &hull) { /* Returns a list of points on the convex hull in counter-clockwise order. Note: the last point in the returned list is the same as the first one. Source: http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain */ int n = (int)points.size(), k = 0; vector<sp_point> H(2*n); //copy points vector<sp_point> pointscpy; pointscpy.reserve( points.size() ); for(size_t i=0; i<points.size(); i++) pointscpy.push_back( points.at(i) ); // Sort points lexicographically sort(pointscpy.begin(), pointscpy.end()); // Build lower hull for (int i = 0; i < n; ++i) { while (k >= 2 && crossprod(H.at(k-2), H.at(k-1), pointscpy.at(i)) <= 0) k--; H.at(k++) = pointscpy[i]; } // Build upper hull for (int i = n-2, t = k+1; i >= 0; i--) { while (k >= t && crossprod(H.at(k-2), H.at(k-1), pointscpy.at(i)) <= 0) k--; H.at(k++) = pointscpy[i]; } H.resize(k); hull = H; } double Toolbox::area_polygon(std::vector<sp_point> &points){ /* INPUT: vector<sp_point> a list of 'sp_point' objects. OUTPUT: Return the total area ASSUME: we care about the area projected into the Z plane, therefore only x,y coordinates are considered. Calculate the area contained within a generic polygon. Use the projected segments method. The polygon can be convex or non-convex and can be irregular. The vector "points" is an ordered list of points composing the polygon in CLOCKWISE order. The final point in "points" is assumed to be connected to the first point in "points". */ //add the first point to the end of the list if( points.size() == 0 ) return 0.; points.push_back(points.front()); int npt = (int)points.size(); double area = 0.; for(int i=0; i<npt-1; i++){ double w = points.at(i).x - points.at(i+1).x; double ybar = (points.at(i).y + points.at(i+1).y)*0.5; area += w * ybar; } //restore the array points.pop_back(); return area; } typedef vector<sp_point> Poly; //Local definitino of polygon, used only in polyclip class polyclip { /* A class dedicated to clipping polygons This class must remain in Toolbox.cpp to compile! */ public: Poly clip(Poly &subjectPolygon, Poly &clipPolygon) { /* http://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm */ outputList = subjectPolygon; cp1 = clipPolygon.back(); for(int i=0; i<(int)clipPolygon.size(); i++) { cp2 = clipPolygon.at(i); inputList = outputList; outputList.clear(); s = inputList.back(); for(int j=0; j<(int)inputList.size(); j++) { e = inputList.at(j); if(inside(&e) ){ if(! inside(&s) ) outputList.push_back( computeIntersection() ); outputList.push_back(e); } else if( inside(&s) ){ outputList.push_back( computeIntersection() ); } s = e; } cp1 = cp2; } return outputList; } private: sp_point cp1, cp2; Poly outputList, inputList; sp_point s, e; bool inside(sp_point *P){ return (cp2.x - cp1.x)*(P->y - cp1.y) > (cp2.y - cp1.y)*(P->x - cp1.x); }; sp_point computeIntersection() { sp_point dc = cp1; dc.Subtract(cp2); sp_point dp = s; dp.Subtract(e); double n1 = cp1.x * cp2.y - cp1.y * cp2.x; double n2 = s.x * e.y - s.y * e.x; double n3 = 1./ (dc.x * dp.y - dc.y * dp.x); sp_point ret; ret.Set((n1*dp.x - n2*dc.x) * n3, (n1*dp.y - n2*dc.y)*n3, 0.); return ret; } }; vector<sp_point> Toolbox::clipPolygon(std::vector<sp_point> &A, std::vector<sp_point> &B) { /* Compute the polygon that forms the intersection of two polygons subjectPolygon and clipPolygon. (clipPolygon clips subjectPolygon). This only considers 2D polygons -- vertices X and Y in "sp_point" structure! */ polyclip P; return P.clip(A,B); } void Toolbox::BezierQ(sp_point &start, sp_point &control, sp_point &end, double t, sp_point &result) { /* Locate a point 'result' along a quadratic Bezier curve. */ double tc = 1. - t; result.x = tc * tc * start.x + 2 * (1 - t) * t * control.x + t * t * end.x; result.y = tc * tc * start.y + 2 * (1 - t) * t * control.y + t * t * end.y; result.z = tc * tc * start.z + 2 * (1 - t) * t * control.z + t * t * end.z; } void Toolbox::BezierC(sp_point &start, sp_point &control1, sp_point &control2, sp_point &end, double t, sp_point &result) { /* Locate a point 'result' along a cubic Bezier curve. */ double tc = 1. - t; result.x = tc*tc*tc * start.x + 3. * tc *tc * t * control1.x + 3. * tc * t * t * control2.x + t * t * t * end.x; result.y = tc*tc*tc * start.y + 3. * tc *tc * t * control1.y + 3. * tc * t * t * control2.y + t * t * t * end.y; result.z = tc*tc*tc * start.z + 3. * tc *tc * t * control1.z + 3. * tc * t * t * control2.z + t * t * t * end.z; } void Toolbox::poly_from_svg(std::string &svg, std::vector< sp_point > &polygon, bool clear_poly) //construct a polygon from an SVG path { /* The following commands are available for path data: M = moveto L = lineto H = horizontal lineto V = vertical lineto C = curveto Q = quadratic Bezier curve Z = closepath >> not yet supported S = smooth curveto T = smooth quadratic Bezier curveto A = elliptical Arc << Note: All of the commands above can also be expressed with lower letters. Capital letters means absolutely positioned, lower cases means relatively positioned. */ int move=-1; //initialize std::string movedat; bool process_now = false; if( clear_poly ) polygon.clear(); polygon.reserve( svg.size()/5 ); double x0,y0; x0=y0=0.; //last position for relative calcs for(size_t i=0; i<svg.size(); i++) { int c = svg.at(i); if( c > 64 && c < 123 ) //a new command { if( move > 0 ) process_now = true; else move = c; } else { movedat += svg.at(i); } if( process_now ) { std::vector< std::string > points_s = split(movedat, " "); std::vector< std::vector<double> > points; for(size_t j=0; j<points_s.size(); j++) { std::vector< std::string > xy_s = split( points_s.at(j), "," ); points.push_back( std::vector<double>() ); for( size_t k=0; k<xy_s.size(); k++) { points.back().push_back( 0 ); to_double( xy_s.at(k), &points.back().at(k) ); } } int npt = (int)points.size(); switch (move) { case 'm': //pick up and move cursor (reset last position) x0 += points.front().at(0); y0 += points.front().at(1); polygon.push_back( sp_point(x0, -y0, 0.) ); if( npt > 1 ) //any subsequent points are assumed to be 'l' { for(int j=1; j<npt; j++) { x0 += points.at(j).at(0); y0 += points.at(j).at(1); polygon.push_back( sp_point(x0, -y0, 0.) ); } } break; case 'M': //pick up and move cursor (reset last position) x0 = points.front().at(0); y0 = points.front().at(1); polygon.push_back( sp_point(x0, -y0, 0.) ); if( npt > 1 ) //any subsequent points are assumed to be 'l' { for(int j=1; j<npt; j++) { x0 += points.at(j).at(0); y0 += points.at(j).at(1); polygon.push_back( sp_point(x0, -y0, 0.) ); } } break; case 'l': //trace all points for(int j=0; j<npt; j++) { x0 += points.at(j).at(0); y0 += points.at(j).at(1); polygon.push_back( sp_point(x0, -y0, 0.) ); } break; case 'L': //trace all points - absolute for(int j=0; j<npt; j++) { x0 = points.at(j).at(0); y0 = points.at(j).at(1); polygon.push_back( sp_point(x0, -y0, 0.) ); } break; case 'h': //horizontal line relative for(int j=0; j<npt; j++) { x0 += points.at(j).front(); polygon.push_back( sp_point(x0, -y0, 0.) ); } break; case 'H': //horizontal line absolute for(int j=0; j<npt; j++) { x0 = points.at(j).front(); polygon.push_back( sp_point(x0, -y0, 0.) ); } break; case 'v': //vertical line relative for(int j=0; j<npt; j++) { y0 += points.at(j).front(); polygon.push_back( sp_point(x0, -y0, 0.) ); } break; case 'V': //vertical line absolute for(int j=0; j<npt; j++) { y0 = points.at(j).front(); polygon.push_back( sp_point(x0, -y0, 0.) ); } break; case 'q': case 'Q': { //bezier curve double xcond=0.; double ycond=0.; //check to make sure there are an even number of points if( npt % 2 != 0 ) return; int nbz = 5; //number of internal bezier points for(int j=0; j<npt; j+=2) //jump through in pairs { sp_point start(x0, y0, 0.); if( move == 'q' ) //if relative, set the relative adder to the start point location { xcond = start.x; ycond = start.y; } sp_point control( points.at(j).at(0) + xcond, points.at(j).at(1) + ycond, 0. ); sp_point end( points.at(j+1).at(0) + xcond, points.at(j+1).at(1) + ycond, 0. ); for(int k=0; k<nbz; k++) { double t = (k+1)/(double)(nbz+1); sp_point result; Toolbox::BezierQ(start, control, end, t, result); result.y = -result.y; polygon.push_back( result ); } //update cursor position x0 = end.x; y0 = end.y; //add the end point end.y = -end.y; polygon.push_back( end ); } break; } case 'c': case 'C': { //bezier curve double xcond=0.; double ycond=0.; //check to make sure there are a divisible number of points if( npt % 3 != 0 ) return; int nbz = 7; //number of internal bezier points for(int j=0; j<npt; j+=3) //jump through in pairs { sp_point start(x0, y0, 0.); //sp_point start = polygon.back(); if( move == 'c' ) //if relative, set the relative adder to the start point location { xcond = start.x; ycond = start.y; } sp_point control1( points.at(j).at(0) + xcond, points.at(j).at(1) + ycond, 0. ); sp_point control2( points.at(j+1).at(0) + xcond, points.at(j+1).at(1) + ycond, 0. ); sp_point end( points.at(j+2).at(0) + xcond, points.at(j+2).at(1) + ycond, 0. ); for(int k=0; k<nbz; k++) { double t = (k+1)/(double)(nbz+2); sp_point result; Toolbox::BezierC(start, control1, control2, end, t, result); result.y = -result.y; polygon.push_back( result ); } //update cursor position x0 = end.x; y0 = end.y; //add the end point end.y = -end.y; polygon.push_back( end ); } break; } case 'z': case 'Z': break; default: //c, t, s, a break; } movedat.clear(); move = c; //next move process_now = false; } } return; } sp_point Toolbox::rotation_arbitrary(double theta, Vect &axis, sp_point &axloc, sp_point &pt){ /* Rotation of a point 'pt' about an arbitrary axis with direction 'axis' centered at point 'axloc'. The point is rotated through 'theta' radians. http://inside.mines.edu/~gmurray/ArbitraryAxisRotation/ Returns the rotated sp_point location */ double a = axloc.x, //Point through which the axis passes b = axloc.y, c = axloc.z, x = pt.x, //Point that we're rotating y = pt.y, z = pt.z, u = axis.i, //Direction of the axis that we're rotating about v = axis.j, w = axis.k; sp_point fin; double sinth = sin(theta), costh = cos(theta); fin.x = (a*(pow(v,2)+pow(w,2)) - u*(b*v + c*w - u*x - v*y - w*z))*(1.-costh) + x*costh + (-c*v + b*w - w*y + v*z)*sinth; fin.y = (b*(pow(u,2)+pow(w,2)) - v*(a*u + c*w - u*x - v*y - w*z))*(1.-costh) + y*costh + (c*u - a*w + w*x - u*z)*sinth; fin.z = (c*(pow(u,2)+pow(v,2)) - w*(a*u + b*v - u*x - v*y - w*z))*(1.-costh) + z*costh + (-b*u + a*v - v*x + u*y)*sinth; return fin; } double Toolbox::ZRotationTransform(Vect &normal_vect){ /* When a heliostat position is transformed using the SolTrace convention, the heliostat ends up such that the horizontal (x) axis is not parallel with the ground XZ plane. This is caused by a mismatch between conventional rotation about (1) the y axis and (2) the rotated y axis, and azimuth-elevation rotation about (1) the x axis and (2) the original z axis. This method calculates the angle of rotation about the modified z-axis in order to restore the azimuth-elevation positioning. Rotations are assumed to be: (1) CCW about Y axis (2) CW about X' axis (3) CW about Z'' axis */ //double Pi = PI; double az = atan3(normal_vect.i,normal_vect.j); double el = asin(normal_vect.k); //Calculate Euler angles double alpha = atan2(normal_vect.i, normal_vect.k); //Rotation about the Y axis double bsign = normal_vect.j > 0. ? 1. : -1.; double beta = -bsign*acos( ( pow(normal_vect.i,2) + pow(normal_vect.k,2) )/ max(sqrt(pow(normal_vect.i,2) + pow(normal_vect.k,2)), 1.e-8) ); //Rotation about the modified X axis //Calculate the modified axis vector Vect modax; modax.Set( cos(alpha), 0., -sin(alpha) ); //Rotation references - axis point sp_point axpos; axpos.Set(0.,0.,0.); //Set as origin //sp_point to rotate sp_point pbase; pbase.Set(0., -1., 0.); //lower edge of heliostat //Rotated point sp_point prot = Toolbox::rotation_arbitrary(beta, modax, axpos, pbase); //Azimuth/elevation reference vector (vector normal to where the base of the heliostat should be) Vect azelref; azelref.Set( sin(az)*sin(el), cos(az)*sin(el), -cos(el) ); //Calculate the angle between the rotated point and the azel ref vector //double gamma = acos( Toolbox::dotprod(azelref, prot) ); /* the sign of the rotation angle is determined by whether the 'k' component of the cross product vector is positive or negative. */ Vect protv; protv.Set(prot.x, prot.y, prot.z); unitvect(protv); Vect cp = crossprod(protv, azelref); double gamma = asin( vectmag( cp )); double gsign = (cp.k > 0. ? 1. : -1.) * (normal_vect.j > 0. ? 1. : -1.); return gamma * gsign; } double Toolbox::ZRotationTransform(double Az, double Zen){ /* Overload for az-zen specification Notes: The Azimuth angle should be [-180,180], zero is north, +east, -west. Az and Zen are both in Radians. */ //Calculate the normal vector to the heliostat based on elevation and azimuth double Pi = PI; double el = Pi/2.-Zen; double az = Az+Pi; //Transform to 0..360 (in radians) Vect aim; aim.Set( sin(az)*cos(el), cos(az)*cos(el), sin(el) ); return ZRotationTransform(aim); } double Toolbox::intersect_fuv(double U, double V){ /* Helper function for intersect_ellipse_rect() */ double u2 = sqrt(1.-pow(U,2)), v2 = sqrt(1.-pow(V,2)); return asin(u2 * v2 - U*V) - U*u2 - V*v2 + 2.*U*V; } double Toolbox::intersect_ellipse_rect(double rect[4], double ellipse[2]){ /* Calculate the area of intersection of a rectangle and an ellipse where the sides of the rectangle area parallel with the axes of the ellipse. {rect[0], rect[1]} = Point location of center of rectangle {rect[2], rect[3]} = Rectangle width, Rectangle height {ellipse[0], ellipse[1]} = Ellipse width and height (A.D. Groves, 1963. Area of intersection of an ellipse and a rectangle. Ballistic Research Laboratories.) */ //Unpack double //a = rect[0] - rect[2]/2., //Lower left corner X location //b = rect[1] - rect[3]/2., //Lower left corner Y location c = rect[2], //Rect width d = rect[3]; //Rect height double w = ellipse[0], //Ellipse width h = ellipse[1]; //Ellipse height //Construct 4 separate possible rectangles double A[4], B[4], C[4], D[4]; for(int i=1; i<5; i++){ A[i-1] = max(0., pow(-1, (pow((double)i,2)-i)/2)*rect[0] - c/2.); B[i-1] = max(0., pow(-1, (pow((double)i,2)+i-2)/2)*rect[1] - d/2.); C[i-1] = max(0., pow(-1, (pow((double)i,2)-i)/2)*rect[0]+c/d-A[i-1]); D[i-1] = max(0., pow(-1, (pow((double)i,2)+i-2)/2)*rect[1]+d/2.-B[i-1]); } double atot=0.; for(int i=0; i<4; i++){ if(C[i] == 0. || D[i] == 0.) continue; //No area if width or height are 0 //Calculate vertex radii double V[4]; V[0] = pow(A[i]/w,2) + pow(B[i]/h,2); V[1] = pow(A[i]/w,2) + pow((B[i]+D[i])/h,2); V[2] = pow((A[i]+C[i])/w,2) + pow((B[i]+D[i])/h,2); V[3] = pow((A[i]+C[i])/w,2) + pow(B[i]/h,2); //Seven cases if(pow(A[i]/w,2) + pow(B[i]/h,2) >= 1.){ continue; //no area overlap } else if(V[0] < 1. && V[1] >= 1 && V[3] >= 1.){ //Lower left vertex is the only one in the ellipse atot += w*h/2.*intersect_fuv(A[i]/w, B[i]/h); } else if(V[3] < 1. && V[1] >= 1.){ //Lower edge inside ellipse, upper edge outside atot += w*h/2. * (intersect_fuv(A[i]/w, B[i]/h) - intersect_fuv((A[i]+C[i])/w, B[i]/h)); } else if(V[1] < 1. && V[3] >= 1.){ //Left edge inside, right edge outside atot += w*h/2. * (intersect_fuv(A[i]/w, B[i]/h) - intersect_fuv(A[i]/w, (B[i]+D[i])/h)); } else if(V[1] < 1. && V[3] < 1. && V[2] > 1.){ //All vertices inside ellipse except upper right corner atot += w*h/2.*(intersect_fuv(A[i]/w, B[i]/h) - intersect_fuv((A[i]+C[i])/w, B[i]/h) - intersect_fuv(A[i]/w, (B[i]+D[i])/h)); } else if(V[2] < 1.){ //All vertices inside the ellipse atot += w*h; } else{ continue; //Error } } return atot; } string Toolbox::getDelimiter(std::string &text){ if (text.empty()) return ","; //Find the type of delimiter vector<string> delims; delims.push_back(","); delims.push_back(" "); delims.push_back("\t"); delims.push_back(";"); string delim = "\t"; //initialize int ns=0; for(int i=0; i<4; i++){ vector<string> data = Toolbox::split(text, delims[i]); if((int)data.size()>ns){ delim = delims[i]; ns = (int)data.size(); } //pick the delimiter that returns the most entries } return delim; } vector< string > Toolbox::split( const string &str, const string &delim, bool ret_empty, bool ret_delim ) { //Take a string with a delimiter and return a vector of separated values vector< string > list; char cur_delim[2] = {0,0}; string::size_type m_pos = 0; string token; int dsize = (int)delim.size(); while (m_pos < str.length()) { //string::size_type pos = str.find_first_of(delim, m_pos); string::size_type pos = str.find(delim, m_pos); if (pos == string::npos) { cur_delim[0] = 0; token.assign(str, m_pos, string::npos); m_pos = str.length(); } else { cur_delim[0] = str[pos]; string::size_type len = pos - m_pos; token.assign(str, m_pos, len); //m_pos = pos + 1; m_pos = pos + dsize; } if (token.empty() && !ret_empty) continue; list.push_back( token ); if ( ret_delim && cur_delim[0] != 0 && m_pos < str.length() ) list.push_back( string( cur_delim ) ); } return list; }
27.523759
178
0.585118
cce4c58fd7f2fe5c465f493d28169a189cb5e6b9
2,019
cpp
C++
cocos2dx_playground/Classes/cpg_input_BasicKeyCollector.cpp
R2Road/cocos2dx_playground
6e6f349b5c9fc702558fe8720ba9253a8ba00164
[ "Apache-2.0" ]
9
2020-06-11T17:09:44.000Z
2021-12-25T00:34:33.000Z
cocos2dx_playground/Classes/cpg_input_BasicKeyCollector.cpp
R2Road/cocos2dx_playground
6e6f349b5c9fc702558fe8720ba9253a8ba00164
[ "Apache-2.0" ]
9
2019-12-21T15:01:01.000Z
2020-12-05T15:42:43.000Z
cocos2dx_playground/Classes/cpg_input_BasicKeyCollector.cpp
R2Road/cocos2dx_playground
6e6f349b5c9fc702558fe8720ba9253a8ba00164
[ "Apache-2.0" ]
1
2020-09-07T01:32:16.000Z
2020-09-07T01:32:16.000Z
#include "cpg_input_BasicKeyCollector.h" #include "cpg_input_KeyMap.h" #include "step_rain_of_chaos_input_KeyCodeCollector.h" USING_NS_CC; namespace cpg_input { BasicKeyCollector::BasicKeyCollector( const KeyMapSp& key_map_container ) : iKeyCollector( key_map_container ) , mKeyHistory() , mCurrent_KeyStatus_Container() , mLast_KeyStatus_Container() { mLast_KeyStatus_Container = mKeyHistory.begin(); mCurrent_KeyStatus_Container = mLast_KeyStatus_Container + 1; } KeyCollectorSp BasicKeyCollector::create( const KeyMapSp& key_map_container ) { KeyCollectorSp ret( new ( std::nothrow ) BasicKeyCollector( key_map_container ) ); return ret; } void BasicKeyCollector::collect( const step_rain_of_chaos::input::KeyCodeCollector& key_code_collector ) { for( const auto k : mKeyMapContainer->mContainer ) ( *mCurrent_KeyStatus_Container )[k.idx] = key_code_collector.isActiveKey( k.keycode ); } void BasicKeyCollector::update_forHistory() { if( mLast_KeyStatus_Container->to_ulong() != mCurrent_KeyStatus_Container->to_ulong() ) { mLast_KeyStatus_Container = mCurrent_KeyStatus_Container; ++mCurrent_KeyStatus_Container; if( mKeyHistory.end() == mCurrent_KeyStatus_Container ) mCurrent_KeyStatus_Container = mKeyHistory.begin(); *mCurrent_KeyStatus_Container = *mLast_KeyStatus_Container; } } bool BasicKeyCollector::getKeyStatus( const cocos2d::EventKeyboard::KeyCode keycode ) const { for( auto& k : mKeyMapContainer->mContainer ) if( keycode == k.keycode ) return ( *mCurrent_KeyStatus_Container )[k.idx]; return false; } bool BasicKeyCollector::getKeyStatus( const int target_key_index ) const { if( 0 > target_key_index || static_cast<std::size_t>( target_key_index ) >= ( *mCurrent_KeyStatus_Container ).size() ) return false; return ( *mCurrent_KeyStatus_Container )[target_key_index]; } bool BasicKeyCollector::hasChanged() const { return mLast_KeyStatus_Container->to_ulong() != mCurrent_KeyStatus_Container->to_ulong(); } }
33.098361
120
0.771174
cce5501e3b418a4945627888a305392c92ee0906
1,763
inl
C++
libblk/info.inl
transpixel/tpqz
2d8400b1be03292d0c5ab74710b87e798ae6c52c
[ "MIT" ]
1
2017-06-01T00:21:16.000Z
2017-06-01T00:21:16.000Z
libblk/info.inl
transpixel/tpqz
2d8400b1be03292d0c5ab74710b87e798ae6c52c
[ "MIT" ]
3
2017-06-01T00:26:16.000Z
2020-05-09T21:06:27.000Z
libblk/info.inl
transpixel/tpqz
2d8400b1be03292d0c5ab74710b87e798ae6c52c
[ "MIT" ]
null
null
null
// // // MIT License // // Copyright (c) 2017 Stellacore Corporation. // // 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. // // /*! \file \brief Definitions for blk::info */ namespace blk { template <typename TypeKey> std::string infoString ( std::map<TypeKey, ga::Rigid> const & oriMap , std::string const & title ) { std::ostringstream oss; if (! title.empty()) { oss << title << std::endl; } oss << "NumberNodes: " << oriMap.size(); for (typename std::map<TypeKey, ga::Rigid>::const_iterator iter(oriMap.begin()) ; oriMap.end() != iter ; ++iter) { oss << std::endl; oss << dat::infoString(iter->first) << " " << ":" << " " << iter->second.infoStringShort() ; } return oss.str(); } } // blk
25.926471
72
0.695973
cce6a75dd76da1b27efb082873e079f1c618091f
6,868
hpp
C++
src/Renderer.hpp
CobaltXII/Tempest
5963e21b98cd414b1b525b11a193512ec3e35f14
[ "MIT" ]
4
2020-01-03T02:52:53.000Z
2021-09-16T23:03:06.000Z
src/Renderer.hpp
CobaltXII/Tempest
5963e21b98cd414b1b525b11a193512ec3e35f14
[ "MIT" ]
null
null
null
src/Renderer.hpp
CobaltXII/Tempest
5963e21b98cd414b1b525b11a193512ec3e35f14
[ "MIT" ]
null
null
null
// A renderer. struct Renderer { const float FOV = 60.0f; const float NEAR_PLANE = 0.5f; const float FAR_PLANE = 5000.0f; Display display; glm::mat4 projection; int width; int height; Renderer() { return; } Renderer(std::string title, int width, int height) { display = Display(title, width, height); SDL_GL_GetDrawableSize(display.window, &this->width, &this->height); projection = glm::perspectiveFov( glm::radians(FOV), float(display.width), float(display.height), NEAR_PLANE, FAR_PLANE ); } // Get the mouse ray. glm::vec3 getMouseRay(Camera camera, int mouseX, int mouseY) { float u = float(mouseX) * 2.0f / float(display.width) - 1.0f; float v = 1.0f - float(mouseY) * 2.0f / float(display.height); glm::vec4 b = glm::inverse(projection) * glm::vec4(u, v, -1.0f, 1.0f); return normalize(glm::inverse(camera.getView()) * glm::vec4(b.x, b.y, -1.0f, 0.0f)); } // Get the time in seconds. float getTime() { return float(SDL_GetTicks()) / 1000.0f; } // Bind the default framebuffer. void bindDefaultFramebuffer() { glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0, 0, width, height); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } // Unbind the default framebuffer. void unbindDefaultFramebuffer() { return; } // Prepare the frame. void prepare() { glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); } // Render a textured model. template<typename T> void renderTexturedModel(TexturedModel& model, T& shader) { glBindVertexArray(model.model.vaoID); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); shader.setUniformSampler2D(shader.uTexture, GL_TEXTURE0, model.texture.textureID); glDrawArrays(GL_TRIANGLES, 0, model.model.vertexCount); glDisableVertexAttribArray(2); glDisableVertexAttribArray(1); glDisableVertexAttribArray(0); glBindVertexArray(0); } // Render a terrain object. template<typename T> void renderTerrainObject(TerrainObject& model, T& shader) { glBindVertexArray(model.model.vaoID); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); shader.setUniformSampler2D(shader.uTexture1, GL_TEXTURE0, model.texture1.textureID); shader.setUniformSampler2D(shader.uTexture2, GL_TEXTURE1, model.texture2.textureID); shader.setUniformSampler2D(shader.uTexture3, GL_TEXTURE2, model.texture3.textureID); shader.setUniformSampler2D(shader.uHeightmap, GL_TEXTURE3, model.heightmap.textureID); glDrawArrays(GL_TRIANGLES, 0, model.model.vertexCount); glDisableVertexAttribArray(1); glDisableVertexAttribArray(0); glBindVertexArray(0); } // Render an entity. template<typename T> void renderEntity(Entity& entity, T& shader) { glBindVertexArray(entity.model.model.vaoID); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); shader.setUniformSampler2D(shader.uTexture, GL_TEXTURE0, entity.model.texture.textureID); glm::mat4 transformation = createTransformation( entity.position, entity.rotation, entity.scale ); shader.setModel(transformation); glDrawArrays(GL_TRIANGLES, 0, entity.model.model.vertexCount); glDisableVertexAttribArray(2); glDisableVertexAttribArray(1); glDisableVertexAttribArray(0); glBindVertexArray(0); } // Render entities. template<typename T> void renderEntities(std::vector<Entity> entities, T& shader) { if (entities.empty()) { return; } glBindVertexArray(entities[0].model.model.vaoID); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); shader.setUniformSampler2D(shader.uTexture, GL_TEXTURE0, entities[0].model.texture.textureID); for (auto& entity: entities) { glm::mat4 transformation = createTransformation( entity.position, entity.rotation, entity.scale ); shader.setModel(transformation); glDrawArrays(GL_TRIANGLES, 0, entity.model.model.vertexCount); } glDisableVertexAttribArray(2); glDisableVertexAttribArray(1); glDisableVertexAttribArray(0); glBindVertexArray(0); } // Render a cubemap. template<typename T> void renderCubemap(Cubemap& cubemap, T& shader) { glDisable(GL_DEPTH_TEST); glBindVertexArray(cubemap.modelID); glEnableVertexAttribArray(0); shader.setUniformSamplerCube(cubemap.cubemapID); glDrawArrays(GL_TRIANGLES, 0, 36); glDisableVertexAttribArray(0); glBindVertexArray(0); glEnable(GL_DEPTH_TEST); } // Render a quad. template<typename T> void renderQuad(Model& model, GLuint textureID, T& shader) { glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glBindVertexArray(model.vaoID); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); shader.setUniformSampler2D(shader.uTexture, GL_TEXTURE0, textureID); glDrawArrays(GL_TRIANGLES, 0, model.vertexCount); glDisableVertexAttribArray(1); glDisableVertexAttribArray(0); glBindVertexArray(0); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); } // Render an untextured quad. void renderUntexturedQuad(Model& model) { glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glBindVertexArray(model.vaoID); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glDrawArrays(GL_TRIANGLES, 0, model.vertexCount); glDisableVertexAttribArray(1); glDisableVertexAttribArray(0); glBindVertexArray(0); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); } // Render water. template<typename T> void renderWaterObject(WaterObject& model, T& shader) { glBindVertexArray(model.model.vaoID); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); shader.setUniformSampler2D(shader.uReflectionTexture, GL_TEXTURE0, model.reflectionTextureID); shader.setUniformSampler2D(shader.uRefractionTexture, GL_TEXTURE1, model.refractionTextureID); shader.setUniformSampler2D(shader.uDepthTexture, GL_TEXTURE2, model.refractionDepthTextureID); shader.setUniformSampler2D(shader.uWaterDuDv, GL_TEXTURE3, model.waterDuDv.textureID); shader.setUniformSampler2D(shader.uWaterNormal, GL_TEXTURE4, model.waterNormal.textureID); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDrawArrays(GL_TRIANGLES, 0, model.model.vertexCount); glDisable(GL_BLEND); glDisableVertexAttribArray(2); glDisableVertexAttribArray(1); glDisableVertexAttribArray(0); glBindVertexArray(0); } // Prepare ImGui. void prepareImGui() { ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplSDL2_NewFrame(display.window); ImGui::NewFrame(); } // Render ImGui. void renderImGui() { ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); } // Update the frame. void update(int fps) { display.update(fps); } // Destroy the renderer. void destroy() { display.destroy(); } };
27.805668
96
0.755679
cceaba2286593dc1fa55e6559cc1ece25b0bc55a
18,490
cpp
C++
src/QMCWaveFunctions/tests/test_einset_spinor.cpp
kayahans/qmcpack
c25d77702e36363ff7368ded783bf31c1b1c5f17
[ "NCSA" ]
null
null
null
src/QMCWaveFunctions/tests/test_einset_spinor.cpp
kayahans/qmcpack
c25d77702e36363ff7368ded783bf31c1b1c5f17
[ "NCSA" ]
null
null
null
src/QMCWaveFunctions/tests/test_einset_spinor.cpp
kayahans/qmcpack
c25d77702e36363ff7368ded783bf31c1b1c5f17
[ "NCSA" ]
null
null
null
////////////////////////////////////////////////////////////////////////////////////// // This file is distributed under the University of Illinois/NCSA Open Source License. // See LICENSE file in top directory for details. // // Copyright (c) 2020 Jeongnim Kim and QMCPACK developers. // // File developed by: Raymond Clay, rclay@sandia.gov, Sandia National Laboratories // // File created by: Raymond Clay, rclay@sandia.gov, Sandia National Laboratories ////////////////////////////////////////////////////////////////////////////////////// #include "catch.hpp" #include "OhmmsData/Libxml2Doc.h" #include "OhmmsPETE/OhmmsMatrix.h" #include "Particle/ParticleSet.h" #include "Particle/ParticleSetPool.h" #include "QMCWaveFunctions/WaveFunctionComponent.h" #include "QMCWaveFunctions/EinsplineSetBuilder.h" #include "QMCWaveFunctions/EinsplineSpinorSetBuilder.h" #include <stdio.h> #include <string> #include <limits> using std::string; namespace qmcplusplus { //Now we test the spinor set with Einspline orbitals from HDF. #ifdef QMC_COMPLEX TEST_CASE("Einspline SpinorSet from HDF", "[wavefunction]") { app_log() << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"; app_log() << "!!!!! Einspline SpinorSet from HDF !!!!!\n"; app_log() << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"; using ValueType = SPOSet::ValueType; using RealType = SPOSet::RealType; Communicate* c; c = OHMMS::Controller; ParticleSet ions_; ParticleSet elec_; ions_.setName("ion"); ions_.create(2); ions_.R[0][0] = 0.00000000; ions_.R[0][1] = 0.00000000; ions_.R[0][2] = 1.08659253; ions_.R[1][0] = 0.00000000; ions_.R[1][1] = 0.00000000; ions_.R[1][2] = -1.08659253; elec_.setName("elec"); elec_.create(3); elec_.R[0][0] = 0.1; elec_.R[0][1] = -0.3; elec_.R[0][2] = 1.0; elec_.R[1][0] = -0.1; elec_.R[1][1] = 0.3; elec_.R[1][2] = 1.0; elec_.R[2][0] = 0.1; elec_.R[2][1] = 0.2; elec_.R[2][2] = 0.3; elec_.spins[0] = 0.0; elec_.spins[1] = 0.2; elec_.spins[2] = 0.4; // O2 test example from pwscf non-collinear calculation. elec_.Lattice.R(0, 0) = 5.10509515; elec_.Lattice.R(0, 1) = -3.23993545; elec_.Lattice.R(0, 2) = 0.00000000; elec_.Lattice.R(1, 0) = 5.10509515; elec_.Lattice.R(1, 1) = 3.23993545; elec_.Lattice.R(1, 2) = 0.00000000; elec_.Lattice.R(2, 0) = -6.49690625; elec_.Lattice.R(2, 1) = 0.00000000; elec_.Lattice.R(2, 2) = 7.08268015; SpeciesSet& tspecies = elec_.getSpeciesSet(); int upIdx = tspecies.addSpecies("u"); int chargeIdx = tspecies.addAttribute("charge"); tspecies(chargeIdx, upIdx) = -1; ParticleSetPool ptcl = ParticleSetPool(c); ptcl.addParticleSet(&elec_); ptcl.addParticleSet(&ions_); const char* particles = "<tmp> \ <sposet_builder name=\"A\" type=\"spinorbspline\" href=\"o2_45deg_spins.pwscf.h5\" tilematrix=\"1 0 0 0 1 0 0 0 1\" twistnum=\"0\" source=\"ion\" size=\"3\" precision=\"float\"> \ <sposet name=\"myspo\" size=\"3\"> \ <occupation mode=\"ground\"/> \ </sposet> \ </sposet_builder> \ </tmp> \ "; Libxml2Document doc; bool okay = doc.parseFromString(particles); REQUIRE(okay); xmlNodePtr root = doc.getRoot(); xmlNodePtr ein1 = xmlFirstElementChild(root); EinsplineSpinorSetBuilder einSet(elec_, ptcl.getPool(), c, ein1); std::unique_ptr<SPOSet> spo(einSet.createSPOSetFromXML(ein1)); REQUIRE(spo); SPOSet::ValueMatrix_t psiM(elec_.R.size(), spo->getOrbitalSetSize()); SPOSet::GradMatrix_t dpsiM(elec_.R.size(), spo->getOrbitalSetSize()); SPOSet::ValueMatrix_t dspsiM(elec_.R.size(), spo->getOrbitalSetSize()); //spin gradient SPOSet::ValueMatrix_t d2psiM(elec_.R.size(), spo->getOrbitalSetSize()); //These are the reference values computed from a spin-polarized calculation, //with the assumption that the coefficients for phi^\uparrow SPOSet::ValueMatrix_t psiM_up(elec_.R.size(), spo->getOrbitalSetSize()); SPOSet::ValueMatrix_t psiM_down(elec_.R.size(), spo->getOrbitalSetSize()); SPOSet::ValueMatrix_t psiM_ref(elec_.R.size(), spo->getOrbitalSetSize()); SPOSet::ValueMatrix_t dspsiM_ref(elec_.R.size(), spo->getOrbitalSetSize()); SPOSet::GradMatrix_t dpsiM_up(elec_.R.size(), spo->getOrbitalSetSize()); SPOSet::GradMatrix_t dpsiM_down(elec_.R.size(), spo->getOrbitalSetSize()); SPOSet::GradMatrix_t dpsiM_ref(elec_.R.size(), spo->getOrbitalSetSize()); SPOSet::ValueMatrix_t d2psiM_up(elec_.R.size(), spo->getOrbitalSetSize()); SPOSet::ValueMatrix_t d2psiM_down(elec_.R.size(), spo->getOrbitalSetSize()); SPOSet::ValueMatrix_t d2psiM_ref(elec_.R.size(), spo->getOrbitalSetSize()); //These reference values were generated as follows: // 1.) Non-Collinear O2 calculation in PBC's performed using Quantum Espresso. // 2.) Spinor wavefunction converted to HDF5 using convertpw4qmc tool. Mainly, this places the up channel in the spin_0 slot, and spin down in spin_1. // 3.) The HDF5 metadata was hacked by hand to correspond to a fictional but consistent spin-polarized set of orbitals. // 4.) A spin polarized QMCPACK run was done using the electron and ion configuration specified in this block. Orbital values, gradients, and laplacians were calculated // for both "spin up" and "spin down" orbitals. This is where the psiM_up(down), d2psiM_up(down) values come from. // 5.) By hand, the reference values, gradients, and laplacians are calculated by using the formula for a spinor e^is phi_up + e^{-is} phi_down. // 6.) These are compared against the integrated initialization/parsing/evaluation of the Einspline Spinor object. //Reference values for spin up component. psiM_up[0][0] = ValueType(2.8696985245e+00, -2.8696982861e+00); psiM_up[0][1] = ValueType(1.1698637009e+00, -1.1698638201e+00); psiM_up[0][2] = ValueType(-2.6149117947e+00, 2.6149117947e+00); psiM_up[1][0] = ValueType(2.8670933247e+00, -2.8670933247e+00); psiM_up[1][1] = ValueType(1.1687355042e+00, -1.1687356234e+00); psiM_up[1][2] = ValueType(-2.6131081581e+00, 2.6131081581e+00); psiM_up[2][0] = ValueType(4.4833350182e+00, -4.4833350182e+00); psiM_up[2][1] = ValueType(1.8927993774e+00, -1.8927993774e+00); psiM_up[2][2] = ValueType(-8.3977413177e-01, 8.3977431059e-01); //Reference values for spin down component. psiM_down[0][0] = ValueType(1.1886650324e+00, -1.1886655092e+00); psiM_down[0][1] = ValueType(-2.8243079185e+00, 2.8243076801e+00); psiM_down[0][2] = ValueType(-1.0831292868e+00, 1.0831292868e+00); psiM_down[1][0] = ValueType(1.1875861883e+00, -1.1875866652e+00); psiM_down[1][1] = ValueType(-2.8215842247e+00, 2.8215837479e+00); psiM_down[1][2] = ValueType(-1.0823822021e+00, 1.0823823214e+00); psiM_down[2][0] = ValueType(1.8570541143e+00, -1.8570543528e+00); psiM_down[2][1] = ValueType(-4.5696320534e+00, 4.5696320534e+00); psiM_down[2][2] = ValueType(-3.4784498811e-01, 3.4784474969e-01); //And the laplacians... d2psiM_up[0][0] = ValueType(-6.1587309837e+00, 6.1587429047e+00); d2psiM_up[0][1] = ValueType(-2.4736759663e+00, 2.4736781120e+00); d2psiM_up[0][2] = ValueType(2.1381640434e-01, -2.1381306648e-01); d2psiM_up[1][0] = ValueType(-5.0561609268e+00, 5.0561575890e+00); d2psiM_up[1][1] = ValueType(-2.0328726768e+00, 2.0328762531e+00); d2psiM_up[1][2] = ValueType(-7.4090242386e-01, 7.4090546370e-01); d2psiM_up[2][0] = ValueType(-1.8970542908e+01, 1.8970539093e+01); d2psiM_up[2][1] = ValueType(-8.2134075165e+00, 8.2134037018e+00); d2psiM_up[2][2] = ValueType(1.0161912441e+00, -1.0161914825e+00); d2psiM_down[0][0] = ValueType(-2.5510206223e+00, 2.5510258675e+00); d2psiM_down[0][1] = ValueType(5.9720201492e+00, -5.9720129967e+00); d2psiM_down[0][2] = ValueType(8.8568925858e-02, -8.8571548462e-02); d2psiM_down[1][0] = ValueType(-2.0943276882e+00, 2.0943336487e+00); d2psiM_down[1][1] = ValueType(4.9078116417e+00, -4.9078197479e+00); d2psiM_down[1][2] = ValueType(-3.0689623952e-01, 3.0689093471e-01); d2psiM_down[2][0] = ValueType(-7.8578405380e+00, 7.8578381538e+00); d2psiM_down[2][1] = ValueType(1.9828968048e+01, -1.9828992844e+01); d2psiM_down[2][2] = ValueType(4.2092007399e-01, -4.2091816664e-01); //And now a looooot of gradient info. ////////SPIN UP////////// dpsiM_up[0][0][0] = ValueType(-1.7161563039e-01, 1.7161482573e-01); dpsiM_up[0][0][1] = ValueType(5.6693041325e-01, -5.6692999601e-01); dpsiM_up[0][0][2] = ValueType(-4.5538558960e+00, 4.5538554192e+00); dpsiM_up[0][1][0] = ValueType(-7.4953302741e-02, 7.4952393770e-02); dpsiM_up[0][1][1] = ValueType(2.4608184397e-01, -2.4608163536e-01); dpsiM_up[0][1][2] = ValueType(-1.9720511436e+00, 1.9720509052e+00); dpsiM_up[0][2][0] = ValueType(-4.2384520173e-02, 4.2384237051e-02); dpsiM_up[0][2][1] = ValueType(1.1735939980e-01, -1.1735984683e-01); dpsiM_up[0][2][2] = ValueType(-3.1189033985e+00, 3.1189031601e+00); dpsiM_up[1][0][0] = ValueType(1.9333077967e-01, -1.9333113730e-01); dpsiM_up[1][0][1] = ValueType(-5.7470333576e-01, 5.7470202446e-01); dpsiM_up[1][0][2] = ValueType(-4.5568108559e+00, 4.5568113327e+00); dpsiM_up[1][1][0] = ValueType(8.4540992975e-02, -8.4540143609e-02); dpsiM_up[1][1][1] = ValueType(-2.4946013093e-01, 2.4946044385e-01); dpsiM_up[1][1][2] = ValueType(-1.9727530479e+00, 1.9727528095e+00); dpsiM_up[1][2][0] = ValueType(3.1103719026e-02, -3.1103719026e-02); dpsiM_up[1][2][1] = ValueType(-1.2540178001e-01, 1.2540178001e-01); dpsiM_up[1][2][2] = ValueType(-3.1043677330e+00, 3.1043677330e+00); dpsiM_up[2][0][0] = ValueType(-8.8733488321e-01, 8.8733488321e-01); dpsiM_up[2][0][1] = ValueType(-1.7726477385e+00, 1.7726477385e+00); dpsiM_up[2][0][2] = ValueType(7.3728728294e-01, -7.3728692532e-01); dpsiM_up[2][1][0] = ValueType(-3.8018247485e-01, 3.8018330932e-01); dpsiM_up[2][1][1] = ValueType(-7.5880718231e-01, 7.5880759954e-01); dpsiM_up[2][1][2] = ValueType(2.7537062764e-01, -2.7537041903e-01); dpsiM_up[2][2][0] = ValueType(-9.5389984548e-02, 9.5390148461e-02); dpsiM_up[2][2][1] = ValueType(-1.8467208743e-01, 1.8467210233e-01); dpsiM_up[2][2][2] = ValueType(-2.4704084396e+00, 2.4704084396e+00); ////////SPIN DOWN////////// dpsiM_down[0][0][0] = ValueType(-7.1084961295e-02, 7.1085616946e-02); dpsiM_down[0][0][1] = ValueType(2.3483029008e-01, -2.3482969403e-01); dpsiM_down[0][0][2] = ValueType(-1.8862648010e+00, 1.8862643242e+00); dpsiM_down[0][1][0] = ValueType(1.8095153570e-01, -1.8095159531e-01); dpsiM_down[0][1][1] = ValueType(-5.9409534931e-01, 5.9409546852e-01); dpsiM_down[0][1][2] = ValueType(4.7609643936e+00, -4.7609624863e+00); dpsiM_down[0][2][0] = ValueType(-1.7556600273e-02, 1.7556769773e-02); dpsiM_down[0][2][1] = ValueType(4.8611730337e-02, -4.8612065613e-02); dpsiM_down[0][2][2] = ValueType(-1.2918885946e+00, 1.2918891907e+00); dpsiM_down[1][0][0] = ValueType(8.0079451203e-02, -8.0079004169e-02); dpsiM_down[1][0][1] = ValueType(-2.3804906011e-01, 2.3804855347e-01); dpsiM_down[1][0][2] = ValueType(-1.8874882460e+00, 1.8874886036e+00); dpsiM_down[1][1][0] = ValueType(-2.0409825444e-01, 2.0409949124e-01); dpsiM_down[1][1][1] = ValueType(6.0225284100e-01, -6.0225236416e-01); dpsiM_down[1][1][2] = ValueType(4.7626581192e+00, -4.7626576424e+00); dpsiM_down[1][2][0] = ValueType(1.2884057127e-02, -1.2884397991e-02); dpsiM_down[1][2][1] = ValueType(-5.1943197846e-02, 5.1943652332e-02); dpsiM_down[1][2][2] = ValueType(-1.2858681679e+00, 1.2858685255e+00); dpsiM_down[2][0][0] = ValueType(-3.6754500866e-01, 3.6754477024e-01); dpsiM_down[2][0][1] = ValueType(-7.3425340652e-01, 7.3425388336e-01); dpsiM_down[2][0][2] = ValueType(3.0539327860e-01, -3.0539402366e-01); dpsiM_down[2][1][0] = ValueType(9.1784656048e-01, -9.1784602404e-01); dpsiM_down[2][1][1] = ValueType(1.8319253922e+00, -1.8319247961e+00); dpsiM_down[2][1][2] = ValueType(-6.6480386257e-01, 6.6480308771e-01); dpsiM_down[2][2][0] = ValueType(-3.9511863142e-02, 3.9511814713e-02); dpsiM_down[2][2][1] = ValueType(-7.6493337750e-02, 7.6493576169e-02); dpsiM_down[2][2][2] = ValueType(-1.0232743025e+00, 1.0232743025e+00); for (unsigned int iat = 0; iat < 3; iat++) { RealType s = elec_.spins[iat]; RealType coss(0.0), sins(0.0); coss = std::cos(s); sins = std::sin(s); ValueType eis(coss, sins); ValueType emis(coss, -sins); ValueType eye(0, 1.0); //Using the reference values for the up and down channels invdividually, we build the total reference spinor value //consistent with the current spin value of particle iat. psiM_ref[iat][0] = eis * psiM_up[iat][0] + emis * psiM_down[iat][0]; psiM_ref[iat][1] = eis * psiM_up[iat][1] + emis * psiM_down[iat][1]; psiM_ref[iat][2] = eis * psiM_up[iat][2] + emis * psiM_down[iat][2]; dspsiM_ref[iat][0] = eye * (eis * psiM_up[iat][0] - emis * psiM_down[iat][0]); dspsiM_ref[iat][1] = eye * (eis * psiM_up[iat][1] - emis * psiM_down[iat][1]); dspsiM_ref[iat][2] = eye * (eis * psiM_up[iat][2] - emis * psiM_down[iat][2]); dpsiM_ref[iat][0] = eis * dpsiM_up[iat][0] + emis * dpsiM_down[iat][0]; dpsiM_ref[iat][1] = eis * dpsiM_up[iat][1] + emis * dpsiM_down[iat][1]; dpsiM_ref[iat][2] = eis * dpsiM_up[iat][2] + emis * dpsiM_down[iat][2]; d2psiM_ref[iat][0] = eis * d2psiM_up[iat][0] + emis * d2psiM_down[iat][0]; d2psiM_ref[iat][1] = eis * d2psiM_up[iat][1] + emis * d2psiM_down[iat][1]; d2psiM_ref[iat][2] = eis * d2psiM_up[iat][2] + emis * d2psiM_down[iat][2]; } //OK. Going to test evaluate_notranspose with spin. spo->evaluate_notranspose(elec_, 0, elec_.R.size(), psiM, dpsiM, d2psiM); for (unsigned int iat = 0; iat < 3; iat++) { REQUIRE(psiM[iat][0] == ComplexApprox(psiM_ref[iat][0])); REQUIRE(psiM[iat][1] == ComplexApprox(psiM_ref[iat][1])); REQUIRE(psiM[iat][2] == ComplexApprox(psiM_ref[iat][2])); REQUIRE(dpsiM[iat][0][0] == ComplexApprox(dpsiM_ref[iat][0][0])); REQUIRE(dpsiM[iat][0][1] == ComplexApprox(dpsiM_ref[iat][0][1])); REQUIRE(dpsiM[iat][0][2] == ComplexApprox(dpsiM_ref[iat][0][2])); REQUIRE(dpsiM[iat][1][0] == ComplexApprox(dpsiM_ref[iat][1][0])); REQUIRE(dpsiM[iat][1][1] == ComplexApprox(dpsiM_ref[iat][1][1])); REQUIRE(dpsiM[iat][1][2] == ComplexApprox(dpsiM_ref[iat][1][2])); REQUIRE(dpsiM[iat][2][0] == ComplexApprox(dpsiM_ref[iat][2][0])); REQUIRE(dpsiM[iat][2][1] == ComplexApprox(dpsiM_ref[iat][2][1])); REQUIRE(dpsiM[iat][2][2] == ComplexApprox(dpsiM_ref[iat][2][2])); REQUIRE(d2psiM[iat][0] == ComplexApprox(d2psiM_ref[iat][0])); REQUIRE(d2psiM[iat][1] == ComplexApprox(d2psiM_ref[iat][1])); REQUIRE(d2psiM[iat][2] == ComplexApprox(d2psiM_ref[iat][2])); } //Now we're going to test evaluateValue and evaluateVGL: int OrbitalSetSize = spo->getOrbitalSetSize(); //temporary arrays for holding the values of the up and down channels respectively. SPOSet::ValueVector_t psi_work; //temporary arrays for holding the gradients of the up and down channels respectively. SPOSet::GradVector_t dpsi_work; //temporary arrays for holding the laplacians of the up and down channels respectively. SPOSet::ValueVector_t d2psi_work; psi_work.resize(OrbitalSetSize); dpsi_work.resize(OrbitalSetSize); d2psi_work.resize(OrbitalSetSize); //We worked hard to generate nice reference data above. Let's generate a test for evaluateV //and evaluateVGL by perturbing the electronic configuration by dR, and then make //single particle moves that bring it back to our original R reference values. //Our perturbation vector. ParticleSet::ParticlePos_t dR; dR.resize(3); //Values chosen based on divine inspiration. Not important. dR[0][0] = 0.1; dR[0][1] = 0.2; dR[0][2] = 0.1; dR[1][0] = -0.1; dR[1][1] = -0.05; dR[1][2] = 0.05; dR[2][0] = -0.1; dR[2][1] = 0.0; dR[2][2] = 0.0; //The new R of our perturbed particle set. ParticleSet::ParticlePos_t Rnew; Rnew.resize(3); Rnew = elec_.R + dR; elec_.R = Rnew; elec_.update(); //Now we test evaluateValue() for (unsigned int iat = 0; iat < 3; iat++) { psi_work = 0.0; elec_.makeMove(iat, -dR[iat], false); spo->evaluateValue(elec_, iat, psi_work); REQUIRE(psi_work[0] == ComplexApprox(psiM_ref[iat][0])); REQUIRE(psi_work[1] == ComplexApprox(psiM_ref[iat][1])); REQUIRE(psi_work[2] == ComplexApprox(psiM_ref[iat][2])); elec_.rejectMove(iat); } //Now we test evaluateVGL() for (unsigned int iat = 0; iat < 3; iat++) { psi_work = 0.0; dpsi_work = 0.0; d2psi_work = 0.0; elec_.makeMove(iat, -dR[iat], false); spo->evaluateVGL(elec_, iat, psi_work, dpsi_work, d2psi_work); REQUIRE(psi_work[0] == ComplexApprox(psiM_ref[iat][0])); REQUIRE(psi_work[1] == ComplexApprox(psiM_ref[iat][1])); REQUIRE(psi_work[2] == ComplexApprox(psiM_ref[iat][2])); REQUIRE(dpsi_work[0][0] == ComplexApprox(dpsiM_ref[iat][0][0])); REQUIRE(dpsi_work[0][1] == ComplexApprox(dpsiM_ref[iat][0][1])); REQUIRE(dpsi_work[0][2] == ComplexApprox(dpsiM_ref[iat][0][2])); REQUIRE(dpsi_work[1][0] == ComplexApprox(dpsiM_ref[iat][1][0])); REQUIRE(dpsi_work[1][1] == ComplexApprox(dpsiM_ref[iat][1][1])); REQUIRE(dpsi_work[1][2] == ComplexApprox(dpsiM_ref[iat][1][2])); REQUIRE(dpsi_work[2][0] == ComplexApprox(dpsiM_ref[iat][2][0])); REQUIRE(dpsi_work[2][1] == ComplexApprox(dpsiM_ref[iat][2][1])); REQUIRE(dpsi_work[2][2] == ComplexApprox(dpsiM_ref[iat][2][2])); REQUIRE(d2psi_work[0] == ComplexApprox(d2psiM_ref[iat][0])); REQUIRE(d2psi_work[1] == ComplexApprox(d2psiM_ref[iat][1])); REQUIRE(d2psi_work[2] == ComplexApprox(d2psiM_ref[iat][2])); elec_.rejectMove(iat); } //Now we test evaluateSpin: SPOSet::ValueVector_t dspsi_work; dspsi_work.resize(OrbitalSetSize); for (unsigned int iat = 0; iat < 3; iat++) { psi_work = 0.0; dspsi_work = 0.0; elec_.makeMove(iat, -dR[iat], false); spo->evaluate_spin(elec_, iat, psi_work, dspsi_work); REQUIRE(psi_work[0] == ComplexApprox(psiM_ref[iat][0])); REQUIRE(psi_work[1] == ComplexApprox(psiM_ref[iat][1])); REQUIRE(psi_work[2] == ComplexApprox(psiM_ref[iat][2])); REQUIRE(dspsi_work[0] == ComplexApprox(dspsiM_ref[iat][0])); REQUIRE(dspsi_work[1] == ComplexApprox(dspsiM_ref[iat][1])); REQUIRE(dspsi_work[2] == ComplexApprox(dspsiM_ref[iat][2])); elec_.rejectMove(iat); } } #endif //QMC_COMPLEX } // namespace qmcplusplus
43.505882
182
0.669605
ccedd60d98c2a361b0bdc6a2daf26844379be7bf
1,550
cpp
C++
gui/previewer/Previewer.cpp
ERPShuen/ICQ1
f319a72ad60aae4809eef0e4eb362f4d69292296
[ "Apache-2.0" ]
1
2019-12-02T08:37:10.000Z
2019-12-02T08:37:10.000Z
gui/previewer/Previewer.cpp
ERPShuen/ICQ1
f319a72ad60aae4809eef0e4eb362f4d69292296
[ "Apache-2.0" ]
null
null
null
gui/previewer/Previewer.cpp
ERPShuen/ICQ1
f319a72ad60aae4809eef0e4eb362f4d69292296
[ "Apache-2.0" ]
null
null
null
#include "stdafx.h" #include "Previewer.h" #include "../main_window/MainWindow.h" #include "../utils/InterConnector.h" #include "../../corelib/enumerations.h" #include "../../gui.shared/implayer.h" #include "../utils/utils.h" namespace { std::unique_ptr<QWidget> PreviewWidget_; std::unique_ptr<QWidget> g_multimediaViewer; } const char* mplayer_exe = "mplayer.exe"; namespace Previewer { void ShowMedia(const core::file_sharing_content_type /*_contentType*/, const QString& _path) { if (platform::is_windows()) { // const auto exePath = QCoreApplication::applicationFilePath(); // // const auto forder = QFileInfo(exePath).path(); // // const int scale = Utils::scale_value(100); // // const int screenNumber = Utils::InterConnector::instance().getMainWindow()->getScreen(); // // const QString command = "\"" + forder + "/" + QString(mplayer_exe) + "\"" + QString(" /media \"") + _path + "\"" + " /scale " + QString::number(scale) + " /screen_number " + QString::number(screenNumber); // // QProcess::startDetached(command); } else { QUrl url = QUrl::fromLocalFile(_path); if (!url.isLocalFile() || !platform::is_apple()) url = QUrl(QDir::fromNativeSeparators(_path)); QDesktopServices::openUrl(url); } } void CloseMedia() { g_multimediaViewer.reset(); } } namespace { }
27.678571
220
0.574839
ccee09a4cf7e1da94d802e73212aa239db62006d
151
cpp
C++
components/eam/src/physics/crm/samxx/diffuse_mom.cpp
Fa-Li/E3SM
a91995093ec6fc0dd6e50114f3c70b5fb64de0f0
[ "zlib-acknowledgement", "FTL", "RSA-MD" ]
235
2018-04-23T16:30:06.000Z
2022-03-21T17:53:12.000Z
components/eam/src/physics/crm/samxx/diffuse_mom.cpp
Fa-Li/E3SM
a91995093ec6fc0dd6e50114f3c70b5fb64de0f0
[ "zlib-acknowledgement", "FTL", "RSA-MD" ]
2,372
2018-04-20T18:12:34.000Z
2022-03-31T23:43:17.000Z
components/eam/src/physics/crm/samxx/diffuse_mom.cpp
Fa-Li/E3SM
a91995093ec6fc0dd6e50114f3c70b5fb64de0f0
[ "zlib-acknowledgement", "FTL", "RSA-MD" ]
254
2018-04-20T20:43:32.000Z
2022-03-30T20:13:38.000Z
#include "diffuse_mom.h" void diffuse_mom() { if (RUN3D) { diffuse_mom3D(sgs_field_diag); } else { diffuse_mom2D(sgs_field_diag); } }
12.583333
34
0.655629
ccf059187eb3c8bccf715f1eae37d74469aa3c52
1,684
hpp
C++
include/memory/hadesmem/detail/force_initialize.hpp
CvX/hadesmem
d2c5164cc753dac37879ac8079f2ae23f2b8edb5
[ "MIT" ]
24
2018-08-18T18:05:37.000Z
2021-09-28T00:26:35.000Z
include/memory/hadesmem/detail/force_initialize.hpp
CvX/hadesmem
d2c5164cc753dac37879ac8079f2ae23f2b8edb5
[ "MIT" ]
null
null
null
include/memory/hadesmem/detail/force_initialize.hpp
CvX/hadesmem
d2c5164cc753dac37879ac8079f2ae23f2b8edb5
[ "MIT" ]
9
2018-04-16T09:53:09.000Z
2021-02-26T05:04:49.000Z
// Copyright (C) 2010-2014 Joshua Boyce. // See the file COPYING for copying permission. #pragma once #include <array> #include <windows.h> #include <hadesmem/config.hpp> #include <hadesmem/detail/remote_thread.hpp> #include <hadesmem/detail/trace.hpp> #include <hadesmem/process.hpp> #include <hadesmem/write.hpp> namespace hadesmem { namespace detail { // This is used to generate a 'nullsub' function, which is called // in the context of the remote process in order to 'force' a // call to ntdll.dll!LdrInitializeThunk. This is necessary // because module enumeration will fail if LdrInitializeThunk has // not been called, and Injector::InjectDll (and the APIs it // uses) depends on the module enumeration APIs. inline void ForceLdrInitializeThunk(DWORD proc_id) { Process const process{proc_id}; #if defined(HADESMEM_DETAIL_ARCH_X64) // RET std::array<BYTE, 1> const return_instr = {{0xC3}}; #elif defined(HADESMEM_DETAIL_ARCH_X86) // RET 4 std::array<BYTE, 3> const return_instr = {{0xC2, 0x04, 0x00}}; #else #error "[HadesMem] Unsupported architecture." #endif HADESMEM_DETAIL_TRACE_A("Allocating memory for remote stub."); Allocator const stub_remote{process, sizeof(return_instr)}; HADESMEM_DETAIL_TRACE_A("Writing remote stub."); Write(process, stub_remote.GetBase(), return_instr); auto const stub_remote_pfn = reinterpret_cast<LPTHREAD_START_ROUTINE>( reinterpret_cast<DWORD_PTR>(stub_remote.GetBase())); HADESMEM_DETAIL_TRACE_A("Starting remote thread."); CreateRemoteThreadAndWait(process, stub_remote_pfn); HADESMEM_DETAIL_TRACE_A("Remote thread complete."); } } }
28.542373
73
0.736342
ccf1d89f4b4f212721515d1d3cc2aabfa14856a5
1,807
cpp
C++
1 term/2/3/A/A.cpp
alexkats/Discrete-Math
dd4edd9ff9322e319d162d56567b9d81a6636373
[ "Unlicense" ]
null
null
null
1 term/2/3/A/A.cpp
alexkats/Discrete-Math
dd4edd9ff9322e319d162d56567b9d81a6636373
[ "Unlicense" ]
null
null
null
1 term/2/3/A/A.cpp
alexkats/Discrete-Math
dd4edd9ff9322e319d162d56567b9d81a6636373
[ "Unlicense" ]
null
null
null
#include <iostream> #include <fstream> #include <string> #include <cstring> #include <cmath> #include <cstdio> #include <cstdlib> #include <vector> #include <algorithm> #include <set> #include <map> #include <cassert> #include <ctime> #include <stack> #include <queue> #include <deque> #include <utility> #include <iterator> #define NAME "nextvector" #define INF 1000000000 #define EPS 0.000000001 #define sqr(a) a*a #define mp make_pair #define pb push_back #define rep0(i, n) for (int i = 0; i < n; i++) #define rep(i, l, r) for (int i = l; i < r; i++) #define repd0(i, n) for (int i = (n - 1); i > -1; i--) #define repd(i, l, r) for (int i = (r - 1); i > (l - 1); i--) typedef unsigned long long ull; typedef long long ll; typedef long double ld; using namespace std; string s; string solve1 (string s) { int n = s.length (); rep0(i, n) if (s [i] == '0') s [i] = '1'; else { s [i] = '0'; break; } rep0(i, n / 2) swap (s [i], s [n - i - 1]); return s; } string solve2 (string s) { int n = s.length (); rep0(i, n) if (s [i] == '1') s [i] = '0'; else { s [i] = '1'; break; } rep0(i, n / 2) swap (s [i], s [n - i - 1]); return s; } int main () { freopen (NAME".in", "r", stdin); freopen (NAME".out", "w", stdout); cin >> s; int n = s.length (); rep0(i, n / 2) swap (s [i], s [n - i - 1]); bool z0 = false; bool z1 = false; string ans1 = ""; string ans2 = ""; rep0(i, n) { if (s [i] != '0') z0 = true; if (s [i] != '1') z1 = true; } if (!z0) ans1 = "-"; else ans1 = solve1 (s); if (!z1) ans2 = "-"; else ans2 = solve2 (s); cout << ans1 << endl; cout << ans2 << endl; return 0; }
15.444444
62
0.50249
ccf5f771d0469f00cb4cc1d90ea48201f516bf7e
1,277
cpp
C++
src/ScorePeg.cpp
DarkMaguz/mastermind-gtkmm
4abfd70c81e4fb7688898cb4d55610216d75eeb8
[ "MIT" ]
null
null
null
src/ScorePeg.cpp
DarkMaguz/mastermind-gtkmm
4abfd70c81e4fb7688898cb4d55610216d75eeb8
[ "MIT" ]
null
null
null
src/ScorePeg.cpp
DarkMaguz/mastermind-gtkmm
4abfd70c81e4fb7688898cb4d55610216d75eeb8
[ "MIT" ]
null
null
null
/* * ScorePeg.cpp * * Created on: Nov 18, 2021 * Author: magnus */ #include "ScorePeg.h" ScorePeg::ScorePeg() : m_score(MasterMind::NONE) { set_size_request(20, 20); //show_all_children(); } ScorePeg::~ScorePeg() { } void ScorePeg::setScore(const MasterMind::score& score) { m_score = score; // Request redrawing of widget. queue_draw(); } bool ScorePeg::on_draw(const Cairo::RefPtr<Cairo::Context>& cr) { rgbColor color; if (m_score == MasterMind::HIT) color = {0., 0., 0.}; else if (m_score == MasterMind::MISS) color = {1., 1., 1.}; else { reset_style(); return false; } // This is where we draw on the window Gtk::Allocation allocation = get_allocation(); const int width = allocation.get_width(); const int height = allocation.get_height(); const int lesser = MIN(width, height); // coordinates for the center of the window int xc, yc; xc = width / 2; yc = height / 2; // outline thickness changes with window size cr->set_line_width(lesser * 0.02); // now draw a circle cr->save(); cr->arc(xc, yc, lesser / 4.0, 0.0, 2.0 * M_PI); // full circle cr->set_source_rgb(color.red, color.green, color.blue); cr->fill_preserve(); cr->restore(); // back to opaque black cr->stroke(); return false; }
19.348485
64
0.648395
ccf7ec1dcc93d8a545e8911fc4acaa7925ef9731
888
cpp
C++
src/13merge.cpp
baseoursteps/faang
8508b3bd66a607fa4ff5a71efd9e2a25a2a263d5
[ "MIT" ]
1
2021-07-13T19:47:57.000Z
2021-07-13T19:47:57.000Z
src/13merge.cpp
baseoursteps/faang
8508b3bd66a607fa4ff5a71efd9e2a25a2a263d5
[ "MIT" ]
1
2021-05-07T15:02:27.000Z
2021-05-09T08:44:05.000Z
src/13merge.cpp
baseoursteps/faang
8508b3bd66a607fa4ff5a71efd9e2a25a2a263d5
[ "MIT" ]
1
2021-05-07T13:18:01.000Z
2021-05-07T13:18:01.000Z
#include <algorithm> #include <iostream> #include <vector> struct interval { int start { -1 }, end { -1 }; interval(int a, int b) : start(a), end(b) {} bool operator<(const interval &o) const { return start < o.start; } }; int main() { using namespace std; vector<interval> vals { { 11, 15 }, { 1, 3 }, { 0, 2 }, { 3, 5 }, { 6, 8 }, { 9, 10 }, { 16, 20 } }; for (auto &&i : vals) cout << i.start << "->" << i.end << "\n"; sort(vals.begin(), vals.end()); for (int i = 0; i < vals.size() - 1;) { if (vals[i].end >= vals[i + 1].start) { vals[i].end = vals[i + 1].end; vals.erase(vals.begin() + i + 1); } else ++i; } cout << "\nMerged:\n"; for (auto &&i : vals) cout << i.start << "->" << i.end << "\n"; return 0; }
20.651163
71
0.427928
ccf943e42d13ae924ebf1fc082f4bd04a5a594c6
2,532
cxx
C++
src/Filtering/BinaryMathematicalMorphology/ThinImage/Code.cxx
kian-weimer/ITKSphinxExamples
ff614cbba28831d1bf2a0cfaa5a2f1949a627c1b
[ "Apache-2.0" ]
34
2015-01-26T19:38:36.000Z
2021-02-04T02:15:41.000Z
src/Filtering/BinaryMathematicalMorphology/ThinImage/Code.cxx
kian-weimer/ITKSphinxExamples
ff614cbba28831d1bf2a0cfaa5a2f1949a627c1b
[ "Apache-2.0" ]
142
2016-01-22T15:59:25.000Z
2021-03-17T15:11:19.000Z
src/Filtering/BinaryMathematicalMorphology/ThinImage/Code.cxx
kian-weimer/ITKSphinxExamples
ff614cbba28831d1bf2a0cfaa5a2f1949a627c1b
[ "Apache-2.0" ]
32
2015-01-26T19:38:41.000Z
2021-03-17T15:28:14.000Z
/*========================================================================= * * Copyright NumFOCUS * * 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.txt * * 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 "itkBinaryThinningImageFilter.h" #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkRescaleIntensityImageFilter.h" using ImageType = itk::Image<unsigned char, 2>; static void CreateImage(ImageType::Pointer image); int main(int argc, char * argv[]) { ImageType::Pointer image = ImageType::New(); if (argc == 2) { image = itk::ReadImage<ImageType>(argv[1]); } else { CreateImage(image); itk::WriteImage(image, "Input.png"); } using BinaryThinningImageFilterType = itk::BinaryThinningImageFilter<ImageType, ImageType>; BinaryThinningImageFilterType::Pointer binaryThinningImageFilter = BinaryThinningImageFilterType::New(); binaryThinningImageFilter->SetInput(image); binaryThinningImageFilter->Update(); // Rescale the image so that it can be seen (the output is 0 and 1, we want 0 and 255) using RescaleType = itk::RescaleIntensityImageFilter<ImageType, ImageType>; RescaleType::Pointer rescaler = RescaleType::New(); rescaler->SetInput(binaryThinningImageFilter->GetOutput()); rescaler->SetOutputMinimum(0); rescaler->SetOutputMaximum(255); rescaler->Update(); itk::WriteImage(rescaler->GetOutput(), "Output.png"); return EXIT_SUCCESS; } void CreateImage(ImageType::Pointer image) { // Create an image ImageType::IndexType start; start.Fill(0); ImageType::SizeType size; size.Fill(100); ImageType::RegionType region(start, size); image->SetRegions(region); image->Allocate(); image->FillBuffer(0); // Draw a 5 pixel wide line for (unsigned int i = 20; i < 80; ++i) { for (unsigned int j = 50; j < 55; ++j) { itk::Index<2> index; index[0] = i; index[1] = j; image->SetPixel(index, 255); } } }
28.449438
106
0.664297
ccfccaad9056b35e59a4c88eb1ec554d50380d1a
414
cpp
C++
tests/test_simple_exc.cpp
limhyungseok/stacktrace
e4fbe540ff8e810de00ab341ff50123a63bcde79
[ "MIT" ]
7
2017-10-25T10:41:43.000Z
2020-12-27T03:22:46.000Z
tests/test_simple_exc.cpp
limhyungseok/stacktrace
e4fbe540ff8e810de00ab341ff50123a63bcde79
[ "MIT" ]
null
null
null
tests/test_simple_exc.cpp
limhyungseok/stacktrace
e4fbe540ff8e810de00ab341ff50123a63bcde79
[ "MIT" ]
3
2015-04-29T03:08:03.000Z
2021-06-24T06:23:12.000Z
#include <stacktrace.h> #include <stdexcept> #include <cstdio> void bar () { throw std::exception(); } void foo() { bar(); } int main() { try { foo(); } catch (...) { struct stacktrace *trace = stacktrace_get_exc(); if (trace != NULL) { stacktrace_print(trace); } else { printf("No exception backtrace\n"); } } return 0; }
15.923077
56
0.502415
ccfd8be8e8655529c7f77980743cf67f842fc07f
1,759
cpp
C++
Graph Theory/Union-Find (Disjoint-Sets) and MST/prim.cpp
hoanghai1803/DataStructures_Algorithms
b5e8ccb3deba7566b915b21c6b7e9435cfe55301
[ "MIT" ]
1
2021-03-06T00:36:08.000Z
2021-03-06T00:36:08.000Z
Graph Theory/Union-Find (Disjoint-Sets) and MST/prim.cpp
hoanghai1803/DataStructures_Algorithms
b5e8ccb3deba7566b915b21c6b7e9435cfe55301
[ "MIT" ]
null
null
null
Graph Theory/Union-Find (Disjoint-Sets) and MST/prim.cpp
hoanghai1803/DataStructures_Algorithms
b5e8ccb3deba7566b915b21c6b7e9435cfe55301
[ "MIT" ]
null
null
null
/* ========== PRIM'S ALGORITHM IMPLEMENTATION ========== */ // This implementation of Prim's algorithm calculates the minimum // weight spanning tree of the weighted undirected graph with non-negative // edge weights. We assume that the graph is connected. // Time complexity: // Using adjacency matrix: O(V^2) // Using adjacency list (+ binary heap): O(max(V, E) * log_2(V)) - Implemented bellow #include <iostream> #include <vector> #include <queue> #include <climits> #define INF INT_MAX #define N 100005 typedef std::pair<int, int> Edge; int n, m; // The number of vertices and edges std::vector<Edge> adj[N]; // Adjacency List int cost[N]; // cost[u] - cost of vertex u void Prim() { // Initialize minCost = 0 (minimum cost of spanning tree). int minCost = 0; int u, v, costU; // Initialize cost of all vertices = +oo, except cost[1] = 0. for (int u = 2; u <= n; u++) cost[u] = +INF; cost[1] = 0; std::priority_queue<Edge, std::vector<Edge>, std::greater<Edge> > Heap; // Min Heap Heap.push(Edge(cost[1], 1)); // Push vertex 1 and its cost into Min Heap while (Heap.size()) { u = Heap.top().second, costU = Heap.top().first; Heap.pop(); if (costU != cost[u]) continue; minCost += cost[u]; cost[u] = 0; for (Edge e: adj[u]) { if (cost[v = e.first] > e.second) { cost[v] = e.second; Heap.push(Edge(cost[v], v)); } } } std::cout << minCost << "\n"; } // Driver code int main() { std::cin >> n >> m; while (m--) { int u, v, w; std::cin >> u >> v >> w; adj[u].push_back(Edge(v, w)); adj[v].push_back(Edge(u, w)); } Prim(); }
25.492754
87
0.554292
ccff98407b71a41ddc6d1cfe4c03e22bb036ff48
738
cpp
C++
Curso/PILHA.cpp
Pedro-H-Castoldi/c-
a01cec85559efec8c84bef142119d83dad12bb1e
[ "Apache-2.0" ]
null
null
null
Curso/PILHA.cpp
Pedro-H-Castoldi/c-
a01cec85559efec8c84bef142119d83dad12bb1e
[ "Apache-2.0" ]
null
null
null
Curso/PILHA.cpp
Pedro-H-Castoldi/c-
a01cec85559efec8c84bef142119d83dad12bb1e
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <stack> using namespace std; int main(){ stack <string> cartas; cartas.push("Carta 1"); cartas.push("Carta 2"); cartas.push("Carta 3"); cartas.push("carta 4"); /*while (!cartas.empty()){ // Maneira de excluir elementos da Pilha cartas.pop(); }*/ if(cartas.empty()){ cout << "Pilha vazia\n\n"; return 0; } else{ cout << "Pilha com cartas\n\n"; } /* cout << "Quantidade de cartas: " << cartas.size() << "\n"; cartas.pop(); cout << "Quantidade de cartas: " << cartas.size() << "\n"; cout << "Carta do topo: "<< cartas.top();*/ for (int i=0; i<4; i++){ cout << "Carta do topo: " << cartas.top() << "\n\n"; // Mostrar os valores da Pilha. cartas.pop(); } return 0; }
18.923077
86
0.574526
6905dfe09a3904ce69ca6b5d0687257e919975aa
1,427
cpp
C++
PIXEL2D/Utilities/StringExtensions.cpp
Maxchii/PIXEL2D
ac1ce604e4f1b8448f14a4f92c69a2ff6d127f56
[ "Apache-2.0" ]
1
2015-05-18T15:20:19.000Z
2015-05-18T15:20:19.000Z
PIXEL2D/Utilities/StringExtensions.cpp
Ossadtchii/PIXEL2D
ac1ce604e4f1b8448f14a4f92c69a2ff6d127f56
[ "Apache-2.0" ]
5
2015-05-18T15:21:28.000Z
2015-06-28T12:43:52.000Z
PIXEL2D/Utilities/StringExtensions.cpp
Maxchii/PIXEL2D
ac1ce604e4f1b8448f14a4f92c69a2ff6d127f56
[ "Apache-2.0" ]
null
null
null
#include "StringExtensions.h" #include <sstream> namespace PIXL { namespace utilities { void GetWords(std::string s, std::vector<std::string>& words) { UInt32 end = 0; while (s.size() > 0) { for (unsigned int i = 0; i < s.size(); i++) { if (s[i] == ' ') { end = i; string word = s.substr(0, end); s.erase(s.begin(), s.begin() + end + 1); words.push_back(word); break; } else if (i == s.size() - 1) { end = i; string word = s.substr(0, end + 1); s.clear(); words.push_back(word); break; } } } } std::vector<std::string> SplitString(const std::string &s, char delimeter) { std::vector<std::string> elems; std::stringstream ss(s); std::string item; while (std::getline(ss, item, delimeter)) { elems.push_back(item); } return elems; } std::string F2S(Float32 val) { std::stringstream stream; stream << val; std::string sValue = stream.str(); val = S2F(sValue); if (val == (int)val) { sValue.append(".0"); } return sValue; } std::string I2S(SInt32 val) { std::stringstream stream; stream << val; return stream.str(); } Float32 S2F(const std::string& s) { std::stringstream stream(s); float value = 0.0f; stream >> value; return value; } SInt32 S2I(const std::string& s) { std::stringstream stream(s); SInt32 value = 0; stream >> value; return value; } } }
17.192771
75
0.576034
690c1ea3a04477e1258114150bfd6cd416334903
4,644
cpp
C++
xcore/smart_analyzer.cpp
zongwave/libxcam
2c0cc6839ddd3ef2b6ad22d2580f7878314daf14
[ "Apache-2.0" ]
400
2018-01-26T05:33:23.000Z
2022-03-31T06:36:47.000Z
xcore/smart_analyzer.cpp
zihengchang/libxcam
53e2b415f9f20ab315de149afdfee97574aeaad0
[ "Apache-2.0" ]
77
2018-01-25T06:16:15.000Z
2022-02-23T02:50:49.000Z
xcore/smart_analyzer.cpp
zihengchang/libxcam
53e2b415f9f20ab315de149afdfee97574aeaad0
[ "Apache-2.0" ]
161
2018-03-05T01:03:42.000Z
2022-03-29T17:14:20.000Z
/* * smart_analyzer.cpp - smart analyzer * * Copyright (c) 2015 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. * * Author: Zong Wei <wei.zong@intel.com> */ #include "smart_analyzer_loader.h" #include "smart_analyzer.h" #include "smart_analysis_handler.h" #include "xcam_obj_debug.h" namespace XCam { SmartAnalyzer::SmartAnalyzer (const char *name) : XAnalyzer (name) { XCAM_OBJ_PROFILING_INIT; } SmartAnalyzer::~SmartAnalyzer () { } XCamReturn SmartAnalyzer::add_handler (SmartPtr<SmartAnalysisHandler> handler) { XCamReturn ret = XCAM_RETURN_NO_ERROR; if (!handler.ptr ()) { return XCAM_RETURN_ERROR_PARAM; } _handlers.push_back (handler); handler->set_analyzer (this); return ret; } XCamReturn SmartAnalyzer::create_handlers () { XCamReturn ret = XCAM_RETURN_NO_ERROR; if (_handlers.empty ()) { ret = XCAM_RETURN_ERROR_PARAM; } return ret; } XCamReturn SmartAnalyzer::release_handlers () { XCamReturn ret = XCAM_RETURN_NO_ERROR; return ret; } XCamReturn SmartAnalyzer::internal_init (uint32_t width, uint32_t height, double framerate) { XCAM_UNUSED (width); XCAM_UNUSED (height); XCAM_UNUSED (framerate); SmartHandlerList::iterator i_handler = _handlers.begin (); for (; i_handler != _handlers.end (); ++i_handler) { SmartPtr<SmartAnalysisHandler> handler = *i_handler; XCamReturn ret = handler->create_context (handler); if (ret != XCAM_RETURN_NO_ERROR) { XCAM_LOG_WARNING ("smart analyzer initialize handler(%s) context failed", XCAM_STR(handler->get_name())); } } return XCAM_RETURN_NO_ERROR; } XCamReturn SmartAnalyzer::internal_deinit () { SmartHandlerList::iterator i_handler = _handlers.begin (); for (; i_handler != _handlers.end (); ++i_handler) { SmartPtr<SmartAnalysisHandler> handler = *i_handler; if (handler->is_valid ()) handler->destroy_context (); } return XCAM_RETURN_NO_ERROR; } XCamReturn SmartAnalyzer::configure () { XCamReturn ret = XCAM_RETURN_NO_ERROR; return ret; } XCamReturn SmartAnalyzer::update_params (XCamSmartAnalysisParam &params) { XCamReturn ret = XCAM_RETURN_NO_ERROR; SmartHandlerList::iterator i_handler = _handlers.begin (); for (; i_handler != _handlers.end (); ++i_handler) { SmartPtr<SmartAnalysisHandler> handler = *i_handler; if (!handler->is_valid ()) continue; ret = handler->update_params (params); if (ret != XCAM_RETURN_NO_ERROR) { XCAM_LOG_WARNING ("smart analyzer update handler(%s) context failed", XCAM_STR(handler->get_name())); handler->destroy_context (); } } return XCAM_RETURN_NO_ERROR; } XCamReturn SmartAnalyzer::analyze (const SmartPtr<VideoBuffer> &buffer) { XCAM_OBJ_PROFILING_START; XCamReturn ret = XCAM_RETURN_NO_ERROR; X3aResultList results; if (!buffer.ptr ()) { XCAM_LOG_DEBUG ("SmartAnalyzer::analyze got NULL buffer!"); return XCAM_RETURN_ERROR_PARAM; } SmartHandlerList::iterator i_handler = _handlers.begin (); for (; i_handler != _handlers.end (); ++i_handler) { SmartPtr<SmartAnalysisHandler> handler = *i_handler; if (!handler->is_valid ()) continue; ret = handler->analyze (buffer, results); if (ret != XCAM_RETURN_NO_ERROR && ret != XCAM_RETURN_BYPASS) { XCAM_LOG_WARNING ("smart analyzer analyze handler(%s) context failed", XCAM_STR(handler->get_name())); handler->destroy_context (); } } if (!results.empty ()) { set_results_timestamp (results, buffer->get_timestamp ()); notify_calculation_done (results); } XCAM_OBJ_PROFILING_END ("smart analysis", XCAM_OBJ_DUR_FRAME_NUM); return XCAM_RETURN_NO_ERROR; } void SmartAnalyzer::post_smart_results (X3aResultList &results, int64_t timestamp) { if (!results.empty ()) { set_results_timestamp (results, timestamp); notify_calculation_done (results); } } }
25.944134
117
0.680233
690eddb5ac828cb5061e5482d514dd2ee0d81b27
1,531
cpp
C++
acwing/winter/1113. 红与黑.cpp
xmmmmmovo/MyAlgorithmSolutions
f5198d438f36f41cc4f72d53bb71d474365fa80d
[ "MIT" ]
1
2020-03-26T13:40:52.000Z
2020-03-26T13:40:52.000Z
acwing/winter/1113. 红与黑.cpp
xmmmmmovo/MyAlgorithmSolutions
f5198d438f36f41cc4f72d53bb71d474365fa80d
[ "MIT" ]
null
null
null
acwing/winter/1113. 红与黑.cpp
xmmmmmovo/MyAlgorithmSolutions
f5198d438f36f41cc4f72d53bb71d474365fa80d
[ "MIT" ]
null
null
null
/** * author: xmmmmmovo * generation time: 2021/01/12 * filename: red_and_black.cpp * language & build version : C 11 & C++ 17 */ #include <algorithm> #include <iostream> #include <queue> #define x first #define y second using namespace std; typedef pair<int, int> PII; char g[25][25]; int n, m; int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1}; // 宽度优先搜索 int dfs(int i, int j) { int res = 1; g[i][j] = '#'; for (int k = 0; k < 4; k++) { int x = i + dx[k], y = j + dy[k]; if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] == '.') res += dfs(x, y); } return res; } // 广度优先搜索 int bfs(int i, int j) { queue<PII> q; q.push({i, j}); g[i][j] = '#'; int res = 0; while (q.size()) { auto tmp = q.front(); q.pop(); res++; for (int i = 0; i < 4; i++) { int x = tmp.x + dx[i], y = tmp.y + dy[i]; if (x < 0 || x >= n || y < 0 || y >= m || g[x][y] != '.') continue; g[x][y] = '#'; q.push({x, y}); } } return res; } int main() { out: while (scanf("%d %d", &m, &n), n || m) { for (int i = 0; i < n; i++) { scanf("%s", &g[i]); } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (g[i][j] == '@') { // printf("%d\n", bfs(i, j)); printf("%d\n", dfs(i, j)); goto out; } } } } return 0; }
20.413333
79
0.367734
691328ec21e9bae7dd92209d732428dfda11a04d
2,656
hpp
C++
sdk/attestation/azure-security-attestation/src/private/crypto/openssl/openssl_helpers.hpp
JinmingHu-MSFT/azure-sdk-for-cpp
933486385a54a5a09a7444dbd823425f145ad75a
[ "MIT" ]
1
2022-01-19T22:54:41.000Z
2022-01-19T22:54:41.000Z
sdk/attestation/azure-security-attestation/src/private/crypto/openssl/openssl_helpers.hpp
LarryOsterman/azure-sdk-for-cpp
d96216f50909a2bd39b555c9088f685bf0f7d6e6
[ "MIT" ]
null
null
null
sdk/attestation/azure-security-attestation/src/private/crypto/openssl/openssl_helpers.hpp
LarryOsterman/azure-sdk-for-cpp
d96216f50909a2bd39b555c9088f685bf0f7d6e6
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // SPDX-License-Identifier: MIT #pragma once #include <memory> #include <openssl/bio.h> #include <openssl/evp.h> #include <stdexcept> #include <type_traits> #include <utility> namespace Azure { namespace Security { namespace Attestation { namespace _detail { // Helpers to provide RAII wrappers for OpenSSL types. template <typename T, void (&Deleter)(T*)> struct openssl_deleter { void operator()(T* obj) { Deleter(obj); } }; template <typename T, void (&FreeFunc)(T*)> using basic_openssl_unique_ptr = std::unique_ptr<T, openssl_deleter<T, FreeFunc>>; // *** Given just T, map it to the corresponding FreeFunc: template <typename T> struct type_map_helper; template <> struct type_map_helper<EVP_PKEY> { using type = basic_openssl_unique_ptr<EVP_PKEY, EVP_PKEY_free>; }; template <> struct type_map_helper<BIO> { using type = basic_openssl_unique_ptr<BIO, BIO_free_all>; }; // *** Now users can say openssl_unique_ptr<T> if they want: template <typename T> using openssl_unique_ptr = typename type_map_helper<T>::type; // *** Or the current solution's convenience aliases: using openssl_evp_pkey = openssl_unique_ptr<EVP_PKEY>; using openssl_bio = openssl_unique_ptr<BIO>; #ifdef __cpp_nontype_template_parameter_auto // *** Wrapper function that calls a given OpensslApi, and returns the corresponding // openssl_unique_ptr<T>: template <auto OpensslApi, typename... Args> auto make_openssl_unique(Args&&... args) { auto raw = OpensslApi( forward<Args>(args)...); // forwarding is probably unnecessary, could use const Args&... // check raw using T = remove_pointer_t<decltype(raw)>; // no need to request T when we can see // what OpensslApi returned return openssl_unique_ptr<T>{raw}; } #else // ^^^ C++17 ^^^ / vvv C++14 vvv template <typename Api, typename... Args> auto make_openssl_unique(Api& OpensslApi, Args&&... args) { auto raw = OpensslApi(std::forward<Args>( args)...); // forwarding is probably unnecessary, could use const Args&... // check raw using T = std::remove_pointer_t<decltype(raw)>; // no need to request T when we can see // what OpensslApi returned return openssl_unique_ptr<T>{raw}; } #endif // ^^^ C++14 ^^^ extern std::string GetOpenSSLError(std::string const& what); struct OpenSSLException : public std::runtime_error { OpenSSLException(std::string const& what); }; }}}} // namespace Azure::Security::Attestation::_detail
35.891892
96
0.67997
6913324610ba42002ca621321552d927c8186c93
1,341
cpp
C++
src/CLR/Core/StringTable.cpp
TIPConsulting/nf-interpreter
d5407872f4705d6177e1ee5a2e966bd02fd476e4
[ "MIT" ]
null
null
null
src/CLR/Core/StringTable.cpp
TIPConsulting/nf-interpreter
d5407872f4705d6177e1ee5a2e966bd02fd476e4
[ "MIT" ]
1
2021-02-22T07:54:30.000Z
2021-02-22T07:54:30.000Z
src/CLR/Core/StringTable.cpp
TIPConsulting/nf-interpreter
d5407872f4705d6177e1ee5a2e966bd02fd476e4
[ "MIT" ]
null
null
null
// // Copyright (c) .NET Foundation and Contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // #include "stdafx.h" #include "Core.h" //////////////////////////////////////////////////////////////////////////////////////////////////// #include "StringTableData.cpp" //////////////////////////////////////////////////////////////////////////////////////////////////// void CLR_RT_Assembly::InitString() { NATIVE_PROFILE_CLR_CORE(); } const char* CLR_RT_Assembly::GetString( CLR_STRING i ) { NATIVE_PROFILE_CLR_CORE(); static const CLR_STRING iMax = 0xFFFF - c_CLR_StringTable_Size; if(i >= iMax) { return &c_CLR_StringTable_Data[ c_CLR_StringTable_Lookup[ (CLR_STRING)0xFFFF - i ] ]; } return &(((const char*)GetTable( TBL_Strings ))[ i ]); } #if defined(_WIN32) void CLR_RT_Assembly::InitString( std::map<std::string,CLR_OFFSET>& map ) { NATIVE_PROFILE_CLR_CORE(); const CLR_STRING* array = c_CLR_StringTable_Lookup; size_t len = c_CLR_StringTable_Size; CLR_STRING idx = 0xFFFF; map.clear(); while(len-- > 0) { map[ &c_CLR_StringTable_Data[ *array++ ] ] = idx--; } } #endif
24.833333
101
0.541387
6917d70520912ba9c78126e9e2359c219333c51c
1,184
hh
C++
src/faodel-services/MPISyncStart.hh
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
2
2019-01-25T21:21:07.000Z
2021-04-29T17:24:00.000Z
src/faodel-services/MPISyncStart.hh
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
8
2018-10-09T14:35:30.000Z
2020-09-30T20:09:42.000Z
src/faodel-services/MPISyncStart.hh
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
2
2019-04-23T19:01:36.000Z
2021-05-11T07:44:55.000Z
// Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC // (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. #ifndef FAODEL_MPISYNCHSTART_HH #define FAODEL_MPISYNCHSTART_HH #include <string> #include "faodel-common/BootstrapInterface.hh" #include "faodel-common/LoggingInterface.hh" namespace faodel { namespace mpisyncstart { std::string bootstrap(); class MPISyncStart : public faodel::bootstrap::BootstrapInterface, public faodel::LoggingInterface { public: MPISyncStart(); ~MPISyncStart() override; //Bootstrap API void Init(const faodel::Configuration &config) override {} void InitAndModifyConfiguration(faodel::Configuration *config) override; void Start() override; void Finish() override {}; void GetBootstrapDependencies(std::string &name, std::vector<std::string> &requires, std::vector<std::string> &optional) const override; private: bool needs_patch; //True when detected a change in config }; } // namespace mpisyncstart } // namespace faodel #endif //FAODEL_MPISYNCHSTART_HH
25.73913
76
0.727196
691a7ea5b06c5bdcd19fb807d06fcd2fa90ae730
1,241
cpp
C++
tests/expected/loop.cpp
div72/py2many
60277bc13597bd32d078b88a7390715568115fc6
[ "MIT" ]
345
2021-01-28T17:33:08.000Z
2022-03-25T16:07:56.000Z
tests/expected/loop.cpp
mkos11/py2many
be6cfaad5af32c43eb24f182cb20ad63b979d4ef
[ "MIT" ]
291
2021-01-31T13:15:06.000Z
2022-03-23T21:28:49.000Z
tests/expected/loop.cpp
mkos11/py2many
be6cfaad5af32c43eb24f182cb20ad63b979d4ef
[ "MIT" ]
23
2021-02-09T17:15:03.000Z
2022-02-03T05:57:44.000Z
#include <iostream> // NOLINT(build/include_order) #include "pycpp/runtime/builtins.h" // NOLINT(build/include_order) #include "pycpp/runtime/range.hpp" // NOLINT(build/include_order) #include "pycpp/runtime/sys.h" // NOLINT(build/include_order) inline void for_with_break() { for (auto i : rangepp::xrange(4)) { if (i == 2) { break; } std::cout << i; std::cout << std::endl; } } inline void for_with_continue() { for (auto i : rangepp::xrange(4)) { if (i == 2) { continue; } std::cout << i; std::cout << std::endl; } } inline void for_with_else() { for (auto i : rangepp::xrange(4)) { std::cout << i; std::cout << std::endl; } } inline void while_with_break() { int i = 0; while (true) { if (i == 2) { break; } std::cout << i; std::cout << std::endl; i += 1; } } inline void while_with_continue() { int i = 0; while (i < 5) { i += 1; if (i == 2) { continue; } std::cout << i; std::cout << std::endl; } } int main(int argc, char** argv) { pycpp::sys::argv = std::vector<std::string>(argv, argv + argc); for_with_break(); for_with_continue(); while_with_break(); while_with_continue(); }
19.390625
67
0.560838
691f3da4fe34e71105d8ef6c466dda11b7e4c9ad
5,935
cpp
C++
handwritten/q12.cpp
khalefa-phd/tpch-benches-handwritten
1d37f43f32eb9e78066d553f4082fc07495895f1
[ "MIT" ]
null
null
null
handwritten/q12.cpp
khalefa-phd/tpch-benches-handwritten
1d37f43f32eb9e78066d553f4082fc07495895f1
[ "MIT" ]
null
null
null
handwritten/q12.cpp
khalefa-phd/tpch-benches-handwritten
1d37f43f32eb9e78066d553f4082fc07495895f1
[ "MIT" ]
null
null
null
/** * TPCH Query 12 EXPLAIN select l_shipmode, sum(case when o_orderpriority = '1-URGENT' or o_orderpriority = '2-HIGH' then 1 else 0 end) as high_line_count, sum(case when o_orderpriority <> '1-URGENT' and o_orderpriority <> '2-HIGH' then 1 else 0 end) as low_line_count from orders, lineitem where o_orderkey = l_orderkey and l_shipmode in ('MAIL', 'AIR') and l_commitdate < l_receiptdate and l_shipdate < l_commitdate and l_receiptdate >= date '1994-01-01' and l_receiptdate < date '1994-01-01' + interval '1' year group by l_shipmode order by l_shipmode; where rownum <= -1; */ #include <cstdio> #include <cstdlib> #include <iostream> #include <map> #include <omp.h> #include <string> #include <sys/time.h> #include <unordered_map> #include <unordered_set> #include <vector> #include "utils.h" using namespace std; #define NUM_PARALLEL_THREADS 24 // Global variables. // Number of rows in the lineitems table. int num_lineitems; // Scale factor. int SF; void partition_withsync(Order *o, Lineitem *l, int partition, int results[2][2]) { struct timeval before, after, diff; gettimeofday(&before, 0); int local_results[2][2] = {{0}}; int start = (partition * num_lineitems) / NUM_PARALLEL_THREADS; int end = ((partition + 1) * num_lineitems) / NUM_PARALLEL_THREADS; for (int i = start; i < end; i++) { if (l->commitdate[i] >= l->recieptdate[i] || !(l->recieptdate[i] >= 19940101 and l->recieptdate[i] < 19950101) || l->shipdate[i] >= l->commitdate[i]) { continue; } int shipmode = l->shipmode[i]; if (shipmode == 0 || shipmode == 1) { int orderpriority = o->orderpriority[l->orderindex[i]]; if (orderpriority == 1 || orderpriority == 2) { local_results[shipmode][0] += 1; } else { local_results[shipmode][1] += 1; } } } #pragma omp critical(merge) { results[0][0] += local_results[0][0]; results[0][1] += local_results[0][1]; results[1][0] += local_results[1][0]; results[1][1] += local_results[1][1]; } gettimeofday(&after, 0); timersub(&after, &before, &diff); printf("Parititon %d - %ld.%06ld\n", partition, (long)diff.tv_sec, (long)diff.tv_usec); } void partition_nosync(Order *o, Lineitem *l, int partition, int results[2][2]) { int start = (partition * num_lineitems) / NUM_PARALLEL_THREADS; int end = ((partition + 1) * num_lineitems) / NUM_PARALLEL_THREADS; int order_index = binary_search(o->orderkey, ORDERS_PER_SF * SF, l->orderkey[start]); for (int i = start; i < end; i++) { if (l->commitdate[i] >= l->recieptdate[i]) continue; if (!(l->recieptdate[i] >= 19940101 and l->recieptdate[i] < 19950101)) continue; if (l->shipdate[i] >= l->commitdate[i]) continue; int shipmode = l->shipmode[i]; if (shipmode == 0 || shipmode == 1) { int orderkey = l->orderkey[i]; while (o->orderkey[order_index] != orderkey) order_index++; int orderpriority = o->orderpriority[order_index]; if (orderpriority == 1 || orderpriority == 2) { results[shipmode][0] += 1; } else { results[shipmode][1] += 1; } } } } void with_sync(Order *orders, Lineitem *lineitems) { struct timeval before, after, diff; gettimeofday(&before, 0); int result[2][2] = {{0}}; #pragma omp parallel for for (int i = 0; i < NUM_PARALLEL_THREADS; i++) { partition_withsync(orders, lineitems, i, result); } gettimeofday(&after, 0); timersub(&after, &before, &diff); for (int j = 0; j < 2; j++) { printf("%d: %d | %d\n", j, result[j][0], result[j][1]); } printf("Q12 withsync: %ld.%06ld\n", (long)diff.tv_sec, (long)diff.tv_usec); } void without_sync(Order *orders, Lineitem *lineitems) { struct timeval before, after, diff; gettimeofday(&before, 0); int partitioned_results[4][2][2] = {{{0}}}; #pragma omp parallel for for (int i = 0; i < NUM_PARALLEL_THREADS; i++) { partition_nosync(orders, lineitems, i, partitioned_results[i]); } int result[2][2] = {{0}}; for (int i = 0; i < 4; i++) { for (int j = 0; j < 2; j++) { for (int k = 0; k < 2; k++) { result[j][k] += partitioned_results[i][j][k]; } } } gettimeofday(&after, 0); timersub(&after, &before, &diff); for (int j = 0; j < 2; j++) { printf("%d: %d | %d\n", j, result[j][0], result[j][1]); } printf("Q12 withoutsync: %ld.%06ld\n", (long)diff.tv_sec, (long)diff.tv_usec); } void load_data_q12(string data_dir, Order *orders, Lineitem *lineitems) { string fpath = data_dir + "/orders.tbl"; FILE *order_tbl = fopen(fpath.c_str(), "r"); load_orders(orders, order_tbl, 0, 1, SF); fclose(order_tbl); fpath = data_dir + "/lineitem.tbl"; FILE *lineitem_tbl = fopen(fpath.c_str(), "r"); num_lineitems = load_lineitems(lineitems, lineitem_tbl, 0); fclose(lineitem_tbl); } int main(int argc, char **argv) { string dir = ""; if (!load_sf(argc, argv, SF, dir)) { printf("Run as ./q12 -dir <dir> -sf <sf>\n"); return 0; } string data_dir = dir; //"../tpch/sf" + std::to_string(SF); Order *orders = new Order(ORDERS_PER_SF * SF); Lineitem *lineitems = new Lineitem(6002000 * SF); load_data_q12(data_dir, orders, lineitems); int order_index = 0; for (int i = 0; i < num_lineitems; i++) { int orderkey = lineitems->orderkey[i]; while (orders->orderkey[order_index] != orderkey) order_index++; lineitems->orderindex[i] = order_index; } for (int i = 0; i < 5; i++) { with_sync(orders, lineitems); } // without_sync(orders, lineitems); delete lineitems; delete orders; return 0; }
27.604651
80
0.594608
6925bfa6d418c2725a6e7538337347caf2d38bbb
977
cpp
C++
Sources/libosp/test/array_bench.cpp
nihospr01/OpenSpeechPlatform
799fb5baa5b8cdfad0f5387dd48b394adc583ede
[ "BSD-2-Clause" ]
null
null
null
Sources/libosp/test/array_bench.cpp
nihospr01/OpenSpeechPlatform
799fb5baa5b8cdfad0f5387dd48b394adc583ede
[ "BSD-2-Clause" ]
null
null
null
Sources/libosp/test/array_bench.cpp
nihospr01/OpenSpeechPlatform
799fb5baa5b8cdfad0f5387dd48b394adc583ede
[ "BSD-2-Clause" ]
null
null
null
#include <benchmark/benchmark.h> #include <OSP/array_utilities/array_utilities.hpp> #include <cassert> #include <iostream> #include <string> using namespace std; void array_sum_bench(benchmark::State &state) { int num = state.range(0); float *arr1 = new float[num]; float total; for (auto i = 0; i < num; i++) arr1[i] = (float)i; for (auto _ : state) { benchmark::DoNotOptimize(total = array_sum(arr1, num)); benchmark::ClobberMemory(); } delete[] arr1; } void array_multiply_const_bench(benchmark::State &state) { unsigned num = (unsigned)state.range(0); float *arr1 = new float[num]; for (unsigned i = 0; i < num; i++) arr1[i] = (float)i; for (auto _ : state) { array_multiply_const(arr1, 2.0, num); benchmark::ClobberMemory(); } delete[] arr1; } BENCHMARK(array_sum_bench)->Arg(32)->Arg(48); BENCHMARK(array_multiply_const_bench)->Arg(32)->Arg(48); BENCHMARK_MAIN();
24.425
63
0.635619
6926473b43e569d52091c06c3d4d9dfa004429e6
2,103
hpp
C++
test/core/point_comparisons.hpp
cynodelic/tesela
3b86a7b9501c7136d5168c7e314740fa7f72f7a7
[ "BSL-1.0" ]
null
null
null
test/core/point_comparisons.hpp
cynodelic/tesela
3b86a7b9501c7136d5168c7e314740fa7f72f7a7
[ "BSL-1.0" ]
null
null
null
test/core/point_comparisons.hpp
cynodelic/tesela
3b86a7b9501c7136d5168c7e314740fa7f72f7a7
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2019 Álvaro Ceballos // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt #ifndef CYNODELIC_TESELA_TEST_CORE_POINT_COMPARISONS_HPP #define CYNODELIC_TESELA_TEST_CORE_POINT_COMPARISONS_HPP CYNODELIC_TESTER_TEST_CASE(point_equals); CYNODELIC_TESTER_SECTION(point_equals,main) { tsl::point pt1(439,115); tsl::point pt2(439,115); tsl::point pt3(600,412); CYNODELIC_TESTER_MESSAGE << "Values for pt1:" << tst::newline << " pt1.x = " << pt1.x << tst::newline << " pt1.y = " << pt1.y; CYNODELIC_TESTER_MESSAGE << "Values for pt2:" << tst::newline << " pt2.x = " << pt2.x << tst::newline << " pt2.y = " << pt2.y; CYNODELIC_TESTER_MESSAGE << "Values for pt3:" << tst::newline << " pt3.x = " << pt3.x << tst::newline << " pt3.y = " << pt3.y; CYNODELIC_TESTER_CHECK_EQUALS(pt1.x,pt2.x); CYNODELIC_TESTER_CHECK_EQUALS(pt1.y,pt2.y); CYNODELIC_TESTER_CHECK_TRUE(pt1 == pt2); CYNODELIC_TESTER_CHECK_NOT_EQUALS(pt1.x,pt3.x); CYNODELIC_TESTER_CHECK_NOT_EQUALS(pt1.y,pt3.y); CYNODELIC_TESTER_CHECK_FALSE(pt1 == pt3); } CYNODELIC_TESTER_TEST_CASE(point_not_equals); CYNODELIC_TESTER_SECTION(point_not_equals,main) { tsl::point pt1(556,120); tsl::point pt2(901,396); tsl::point pt3(556,120); CYNODELIC_TESTER_MESSAGE << "Values for pt1:" << tst::newline << " pt1.x = " << pt1.x << tst::newline << " pt1.y = " << pt1.y; CYNODELIC_TESTER_MESSAGE << "Values for pt2:" << tst::newline << " pt2.x = " << pt2.x << tst::newline << " pt2.y = " << pt2.y; CYNODELIC_TESTER_MESSAGE << "Values for pt3:" << tst::newline << " pt3.x = " << pt3.x << tst::newline << " pt3.y = " << pt3.y; CYNODELIC_TESTER_CHECK_NOT_EQUALS(pt1.x,pt2.x); CYNODELIC_TESTER_CHECK_NOT_EQUALS(pt1.y,pt2.y); CYNODELIC_TESTER_CHECK_TRUE(pt1 != pt2); CYNODELIC_TESTER_CHECK_EQUALS(pt1.x,pt3.x); CYNODELIC_TESTER_CHECK_EQUALS(pt1.y,pt3.y); CYNODELIC_TESTER_CHECK_FALSE(pt1 != pt3); } #endif // CYNODELIC_TESELA_TEST_CORE_POINT_COMPARISONS_HPP
27.671053
80
0.686638
692c6e26f56afdf089586a6efad5c6577d8200f6
223
cpp
C++
src/filesystem/tempfile.cpp
bunsanorg/testing
2532858878628c9925ddd0e58436bba53e4b6cb9
[ "Apache-2.0" ]
null
null
null
src/filesystem/tempfile.cpp
bunsanorg/testing
2532858878628c9925ddd0e58436bba53e4b6cb9
[ "Apache-2.0" ]
null
null
null
src/filesystem/tempfile.cpp
bunsanorg/testing
2532858878628c9925ddd0e58436bba53e4b6cb9
[ "Apache-2.0" ]
null
null
null
#include <bunsan/test/filesystem/tempfile.hpp> namespace bunsan { namespace test { namespace filesystem { tempfile::tempfile() : path(allocate()) {} } // namespace filesystem } // namespace test } // namespace bunsan
18.583333
46
0.717489
692dd779f0ef60917299d863b1636a27f2793641
9,551
cpp
C++
runtime/test/dnp3s/test_dnp3_publisher.cpp
kinsamanka/OpenPLC_v3
fc1afcf702eebaf518971b304acf487809c804d4
[ "Apache-2.0" ]
null
null
null
runtime/test/dnp3s/test_dnp3_publisher.cpp
kinsamanka/OpenPLC_v3
fc1afcf702eebaf518971b304acf487809c804d4
[ "Apache-2.0" ]
null
null
null
runtime/test/dnp3s/test_dnp3_publisher.cpp
kinsamanka/OpenPLC_v3
fc1afcf702eebaf518971b304acf487809c804d4
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Smarter Grid Solutions // // 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 permissionsand // limitations under the License. #ifdef OPLC_DNP3_OUTSTATION #include <cstdint> #include <utility> #include <vector> #include <asiodnp3/IOutstation.h> #include "catch.hpp" #include "fakeit.hpp" #include "glue.h" #include "dnp3s/dnp3.h" #include "dnp3s/dnp3_publisher.h" using namespace std; using namespace fakeit; using namespace opendnp3; /// An implementation of the update handler that caches the updates that were /// requested. This implementation allows us to spy on the behaviour and to know /// during the tests whether the correct updates were called. class UpdateCaptureHandler : public opendnp3::IUpdateHandler { public: vector<pair<bool, uint16_t>> binary; vector<pair<bool, uint16_t>> binary_output; vector<pair<double, uint16_t>> analog; vector<pair<double, uint16_t>> analog_output; virtual ~UpdateCaptureHandler() {} virtual bool Update(const Binary& meas, uint16_t index, EventMode mode) { binary.push_back(std::make_pair(meas.value, index)); return true; } /// Simple mocked implementation. /// @copydoc virtual bool Update(const DoubleBitBinary& meas, uint16_t index, EventMode mode) { return true; } /// Simple mocked implementation. /// @copydoc virtual bool Update(const Analog& meas, uint16_t index, EventMode mode) { analog.push_back(std::make_pair(meas.value, index)); return true; } /// Simple mocked implementation. /// @copydoc virtual bool Update(const Counter& meas, uint16_t index, EventMode mode) { return true; } /// Simple mocked implementation. /// @copydoc virtual bool Update(const FrozenCounter& meas, uint16_t index, EventMode mode) { return true; } /// Simple mocked implementation. /// @copydoc virtual bool Update(const BinaryOutputStatus& meas, uint16_t index, EventMode mode) { binary_output.push_back(std::make_pair(meas.value, index)); return true; } /// Simple mocked implementation. /// @copydoc virtual bool Update(const AnalogOutputStatus& meas, uint16_t index, EventMode mode) { analog_output.push_back(std::make_pair(meas.value, index)); return true; } /// Simple mocked implementation. /// @copydoc virtual bool Update(const TimeAndInterval& meas, uint16_t index) { return true; } /// Simple mocked implementation. /// @copydoc virtual bool Modify(FlagsType type, uint16_t start, uint16_t stop, uint8_t flags) { return true; } }; SCENARIO("dnp3 publisher", "ExchangeGlue") { Mock<asiodnp3::IOutstation> mock_outstation; UpdateCaptureHandler update_handler; When(Method(mock_outstation, Apply)).AlwaysDo([&](const asiodnp3::Updates& updates) { updates.Apply(update_handler); }); auto outstation = std::shared_ptr<asiodnp3::IOutstation>(&mock_outstation.get(), [](asiodnp3::IOutstation*) {}); Dnp3MappedGroup measurements = {0}; Dnp3Publisher publisher(outstation, measurements); GIVEN("No glued measurements") { auto num_writes = publisher.ExchangeGlue(); THEN("Writes nothing") { REQUIRE(num_writes == 0); } } GIVEN("Boolean input variable at offset 0") { IEC_BOOL bool_val(0); auto group = GlueBoolGroup { .index = 0, .values = { &bool_val, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr } }; const GlueVariable glue_var = { IECLDT_OUT, IECLST_BIT, 0, 0, IECVT_BOOL, &group }; DNP3MappedGlueVariable mapped_vars[] = { { .group = 1, .point_index_number = 0, .variable = &glue_var } }; Dnp3MappedGroup measurements; measurements.size = 1; measurements.items = mapped_vars; Dnp3Publisher publisher(outstation, measurements); WHEN("value is false") { bool_val = false; auto num_writes = publisher.ExchangeGlue(); THEN("Writes binary input false") { REQUIRE(num_writes == 1); Verify(Method(mock_outstation, Apply)).Exactly(Once); REQUIRE(update_handler.binary.size() == 1); REQUIRE(update_handler.binary[0].first == false); REQUIRE(update_handler.binary[0].second == 0); } } WHEN("value is true") { bool_val = true; auto num_writes = publisher.ExchangeGlue(); THEN("Writes binary input true") { REQUIRE(num_writes == 1); Verify(Method(mock_outstation, Apply)).Exactly(Once); REQUIRE(update_handler.binary.size() == 1); REQUIRE(update_handler.binary[0].first == true); REQUIRE(update_handler.binary[0].second == 0); } } } GIVEN("Boolean output status variable at offset 0") { IEC_BOOL bool_val(0); auto group = GlueBoolGroup { .index = 0, .values = { &bool_val, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr } }; const GlueVariable glue_var = { IECLDT_OUT, IECLST_BIT, 0, 0, IECVT_BOOL, &group }; DNP3MappedGlueVariable mapped_vars[] = { { .group = 10, .point_index_number = 0, .variable = &glue_var } }; Dnp3MappedGroup measurements; measurements.size = 1; measurements.items = mapped_vars; Dnp3Publisher publisher(outstation, measurements); WHEN("value is false") { bool_val = false; auto num_writes = publisher.ExchangeGlue(); THEN("Writes binary input false") { REQUIRE(num_writes == 1); Verify(Method(mock_outstation, Apply)).Exactly(Once); REQUIRE(update_handler.binary_output.size() == 1); REQUIRE(update_handler.binary_output[0].first == false); REQUIRE(update_handler.binary_output[0].second == 0); } } WHEN("value is true") { bool_val = true; auto num_writes = publisher.ExchangeGlue(); THEN("Writes binary input true") { REQUIRE(num_writes == 1); Verify(Method(mock_outstation, Apply)).Exactly(Once); REQUIRE(update_handler.binary_output.size() == 1); REQUIRE(update_handler.binary_output[0].first == true); REQUIRE(update_handler.binary_output[0].second == 0); } } } GIVEN("Real variable at offset 0") { IEC_REAL real_val(9); const GlueVariable glue_var = { IECLDT_OUT, IECLST_DOUBLEWORD, 0, 0, IECVT_REAL, &real_val }; DNP3MappedGlueVariable mapped_vars[] = { { .group = 30, .point_index_number = 0, .variable = &glue_var } }; Dnp3MappedGroup measurements; measurements.size = 1; measurements.items = mapped_vars; Dnp3Publisher publisher(outstation, measurements); WHEN("value is 9") { auto num_writes = publisher.ExchangeGlue(); THEN("Writes binary input false") { REQUIRE(num_writes == 1); Verify(Method(mock_outstation, Apply)).Exactly(Once); REQUIRE(update_handler.analog.size() == 1); REQUIRE(update_handler.analog[0].first == 9); REQUIRE(update_handler.analog[0].second == 0); } } } GIVEN("Real status variable at offset 0") { IEC_REAL real_val(9); const GlueVariable glue_var = { IECLDT_OUT, IECLST_DOUBLEWORD, 0, 0, IECVT_REAL, &real_val }; DNP3MappedGlueVariable mapped_vars[] = { { .group = 40, .point_index_number = 0, .variable = &glue_var } }; Dnp3MappedGroup measurements; measurements.size = 1; measurements.items = mapped_vars; Dnp3Publisher publisher(outstation, measurements); WHEN("value is 9") { auto num_writes = publisher.ExchangeGlue(); THEN("Writes binary input false") { REQUIRE(num_writes == 1); Verify(Method(mock_outstation, Apply)).Exactly(Once); REQUIRE(update_handler.analog_output.size() == 1); REQUIRE(update_handler.analog_output[0].first == 9); REQUIRE(update_handler.analog_output[0].second == 0); } } } } #endif // OPLC_DNP3_OUTSTATION
32.266892
116
0.587373
692fae95fbbad4c60a0e638f73eea0e614ffc732
5,711
cpp
C++
src/gui/gl/slicerenderer.cpp
mhough/braingl
53e2078adc10731ee62feec11dcb767c4c6c0d35
[ "MIT" ]
5
2016-03-17T07:02:11.000Z
2021-12-12T14:43:58.000Z
src/gui/gl/slicerenderer.cpp
mhough/braingl
53e2078adc10731ee62feec11dcb767c4c6c0d35
[ "MIT" ]
null
null
null
src/gui/gl/slicerenderer.cpp
mhough/braingl
53e2078adc10731ee62feec11dcb767c4c6c0d35
[ "MIT" ]
3
2015-10-29T15:21:01.000Z
2020-11-25T09:41:21.000Z
/* * slicerenderer.cpp * * Created on: 09.05.2012 * @author Ralph Schurade */ #include "slicerenderer.h" #include "glfunctions.h" #include "../../data/enums.h" #include "../../data/models.h" #include "../../data/datasets/dataset.h" #include <QtOpenGL/QGLShaderProgram> #include <QVector3D> #include <QMatrix4x4> SliceRenderer::SliceRenderer() : vbo0( 0 ), vbo1( 0 ), vbo2( 0 ) { } SliceRenderer::~SliceRenderer() { glDeleteBuffers( 1, &vbo0 ); glDeleteBuffers( 1, &vbo1 ); glDeleteBuffers( 1, &vbo2 ); } void SliceRenderer::init() { initializeOpenGLFunctions(); glGenBuffers( 1, &vbo0 ); glGenBuffers( 1, &vbo1 ); glGenBuffers( 1, &vbo2 ); initGeometry(); } void SliceRenderer::initGeometry() { float maxDim = GLFunctions::maxDim; QList< int > tl = GLFunctions::getTextureIndexes( "maingl" ); float x = Models::getGlobal( Fn::Property::G_SAGITTAL ).toFloat(); float y = Models::getGlobal( Fn::Property::G_CORONAL ).toFloat(); float z = Models::getGlobal( Fn::Property::G_AXIAL ).toFloat(); float lx = -maxDim; float ly = -maxDim; float lz = -maxDim; float xb = maxDim; float yb = maxDim; float zb = maxDim; float verticesAxial[] = { lx, ly, z, xb, ly, z, lx, yb, z, xb, yb, z }; // Transfer vertex data to VBO 1 glBindBuffer( GL_ARRAY_BUFFER, vbo0 ); glBufferData( GL_ARRAY_BUFFER, 12 * sizeof(float), verticesAxial, GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); float verticesCoronal[] = { lx, y, lz, xb, y, lz, lx, y, zb, xb, y, zb }; // Transfer vertex data to VBO 2 glBindBuffer( GL_ARRAY_BUFFER, vbo1 ); glBufferData( GL_ARRAY_BUFFER, 12 * sizeof(float), verticesCoronal, GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); float verticesSagittal[] = { x, ly, lz, x, yb, lz, x, ly, zb, x, yb, zb }; // Transfer vertex data to VBO 3 glBindBuffer( GL_ARRAY_BUFFER, vbo2 ); glBufferData( GL_ARRAY_BUFFER, 12 * sizeof(float), verticesSagittal, GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); } void SliceRenderer::setupTextures() { GLFunctions::setupTextures(); } void SliceRenderer::setShaderVars( QString target ) { QGLShaderProgram* program = GLFunctions::getShader( "slice" ); int vertexLocation = program->attributeLocation( "a_position" ); program->enableAttributeArray( vertexLocation ); glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 3, 0 ); GLFunctions::setTextureUniforms( program, target ); } void SliceRenderer::draw( QMatrix4x4 p_matrix, QMatrix4x4 mv_matrix, int width, int height, int renderMode, QString target ) { float alpha = GLFunctions::sliceAlpha[target]; switch ( renderMode ) { case 0: break; case 1: { if ( alpha < 1.0 ) // obviously not opaque { return; } break; } default: { if ( alpha == 1.0 ) // not transparent { return; } break; } } if ( !GLFunctions::setupTextures() ) { return; } QGLShaderProgram* program = GLFunctions::getShader( "slice" ); program->bind(); // Set modelview-projection matrix program->setUniformValue( "mvp_matrix", p_matrix * mv_matrix ); program->setUniformValue( "u_alpha", alpha ); program->setUniformValue( "u_renderMode", renderMode ); program->setUniformValue( "u_canvasSize", width, height ); program->setUniformValue( "D0", 9 ); program->setUniformValue( "D1", 10 ); program->setUniformValue( "D2", 11 ); program->setUniformValue( "P0", 12 ); float pAlpha = 1.0; float green = 0.0f; float red = 0.0f; initGeometry(); if ( Models::getGlobal( Fn::Property::G_SHOW_AXIAL ).toBool() ) { float blue = (float)(( 1 ) & 0xFF) / 255.f; GLFunctions::getShader( "slice" )->setUniformValue( "u_pickColor", red, green , blue, pAlpha ); drawAxial( target ); } if ( Models::getGlobal( Fn::Property::G_SHOW_CORONAL ).toBool() ) { float blue = (float)(( 2 ) & 0xFF) / 255.f; GLFunctions::getShader( "slice" )->setUniformValue( "u_pickColor", red, green , blue, pAlpha ); drawCoronal( target ); } if ( Models::getGlobal( Fn::Property::G_SHOW_SAGITTAL ).toBool() ) { float blue = (float)(( 3 ) & 0xFF) / 255.f; GLFunctions::getShader( "slice" )->setUniformValue( "u_pickColor", red, green , blue, pAlpha ); drawSagittal( target ); } } void SliceRenderer::drawAxial( QString target ) { // Tell OpenGL which VBOs to use glBindBuffer( GL_ARRAY_BUFFER, vbo0 ); setShaderVars( target ); glDrawArrays( GL_TRIANGLE_STRIP, 0, 4 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); } void SliceRenderer::drawCoronal( QString target ) { // Tell OpenGL which VBOs to use glBindBuffer( GL_ARRAY_BUFFER, vbo1 ); setShaderVars( target ); glDrawArrays( GL_TRIANGLE_STRIP, 0, 4 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); } void SliceRenderer::drawSagittal( QString target ) { // Tell OpenGL which VBOs to use glBindBuffer( GL_ARRAY_BUFFER, vbo2 ); setShaderVars( target ); glDrawArrays( GL_TRIANGLE_STRIP, 0, 4 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); }
27.195238
125
0.589914
6934eaefe20865b2b3239dd4f802593eece13dfc
4,816
cpp
C++
depthavgpooling/depthavgpooling_cuda.cpp
francescotonini/depthconv
3488ba1e76d379717ca6a674cf54b719d968dcb4
[ "MIT" ]
null
null
null
depthavgpooling/depthavgpooling_cuda.cpp
francescotonini/depthconv
3488ba1e76d379717ca6a674cf54b719d968dcb4
[ "MIT" ]
null
null
null
depthavgpooling/depthavgpooling_cuda.cpp
francescotonini/depthconv
3488ba1e76d379717ca6a674cf54b719d968dcb4
[ "MIT" ]
null
null
null
#include <torch/extension.h> #include <torch/types.h> // CUDA declarations void avgpool_forward(int count, torch::Tensor input_data, torch::Tensor input_depth_data, int channels, int height, int width, int pooled_height, int pooled_width, int kernel_h, int kernel_w, int stride_h, int stride_w, int pad_h, int pad_w, torch::Tensor top_data, torch::Tensor depth_weight_count); void avgpool_backward(int count, torch::Tensor gradOutput, torch::Tensor input_depth, torch::Tensor depth_weight_count, int channels, int height, int width, int pooled_height, int pooled_width, int kernel_h, int kernel_w, int stride_h, int stride_w, int pad_h, int pad_w, torch::Tensor bottom_diff); // C++ interface #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x " must be a CUDA tensor") #define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) torch::Tensor depthavgpooling_forward(torch::Tensor input, torch::Tensor depth, torch::Tensor depth_weight_count, int kernel_height, int kernel_width, int stride_height, int stride_width, int padding_height, int padding_width) { CHECK_INPUT(input); CHECK_INPUT(depth); CHECK_INPUT(depth_weight_count); int batch_size = input.size(0); int input_channels = input.size(1); int input_rows = input.size(2); int input_cols = input.size(3); int output_rows = floor(float(input_rows - kernel_height + 2 * padding_height) / float(stride_height)) + 1; int output_cols = floor(float(input_cols - kernel_width + 2 * padding_width) / float(stride_width)) + 1; if (padding_width || padding_height) { // ensure that the last pooling starts inside the image // needed to avoid problems in ceil mode if ((output_rows - 1) * stride_height >= input_rows + padding_height) { --output_rows; } if ((output_cols - 1) * stride_width >= input_cols + padding_width) { --output_cols; } } torch::Tensor output = torch::zeros(torch::IntArrayRef({batch_size, input_channels, output_rows, output_cols})).cuda(); for (int i = 0; i < batch_size; i++) { torch::Tensor this_input = input[i]; torch::Tensor this_depth = depth[i]; torch::Tensor this_depth_weight_count = depth_weight_count[i]; torch::Tensor this_output = output[i]; int count = this_output.numel(); avgpool_forward(count, this_input, this_depth, input_channels, input_rows, input_cols, output_rows, output_cols, kernel_height, kernel_width, stride_height, stride_width, padding_height, padding_width, this_output, this_depth_weight_count); } return output; } torch::Tensor depthavgpooling_backward(torch::Tensor input, torch::Tensor depth, torch::Tensor depth_weight_count, torch::Tensor grad_output, int kernel_height, int kernel_width, int stride_height, int stride_width, int padding_width, int padding_height) { CHECK_INPUT(input); CHECK_INPUT(depth); CHECK_INPUT(depth_weight_count); CHECK_INPUT(grad_output); int batch_size = input.size(0); int input_channels = input.size(1); int input_rows = input.size(2); int input_cols = input.size(3); int output_rows = floor(float(input_rows - kernel_height + 2 * padding_height) / float(stride_height)) + 1; int output_cols = floor(float(input_cols - kernel_width + 2 * padding_width) / float(stride_width)) + 1; if (padding_width || padding_height) { // ensure that the last pooling starts inside the image // needed to avoid problems in ceil mode if ((output_rows - 1) * stride_height >= input_rows + padding_height) { --output_rows; } if ((output_cols - 1) * stride_width >= input_cols + padding_width) { --output_cols; } } torch::Tensor grad_input = torch::zeros(torch::IntArrayRef({batch_size, input_channels, input_rows, input_cols})).cuda(); for (int i = 0; i < batch_size; i++) { torch::Tensor this_grad_input = grad_input[i]; torch::Tensor this_depth = depth[i]; torch::Tensor this_depth_weight_count = depth_weight_count[i]; torch::Tensor this_grad_output = grad_output[i]; int count = this_grad_input.numel(); avgpool_backward(count, this_grad_output, this_depth, this_depth_weight_count, input_channels, input_rows, input_cols, output_rows, output_cols, kernel_height, kernel_width, stride_height, stride_width, padding_height, padding_width, this_grad_output); } return grad_input; } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &depthavgpooling_forward, "depthavgpooling forward (CUDA)"); m.def("backward", &depthavgpooling_backward, "depthavgpooling backward (CUDA)"); }
47.215686
300
0.708472
69366e3f8e83342a45fdecb6fea9106253de68aa
5,349
hh
C++
hackt_docker/hackt/src/Object/lang/RTE_base.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/Object/lang/RTE_base.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/Object/lang/RTE_base.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
/** \file "Object/lang/RTE_base.hh" Structures for production assignments. $Id: RTE_base.hh,v 1.12 2010/07/09 02:14:13 fang Exp $ */ #ifndef __HAC_OBJECT_LANG_RTE_BASE_HH__ #define __HAC_OBJECT_LANG_RTE_BASE_HH__ #include <list> #include "util/memory/excl_ptr.hh" #include "util/memory/count_ptr.hh" #include "util/persistent.hh" #include "util/boolean_types.hh" #include "Object/inst/instance_pool_fwd.hh" #include "Object/lang/PRS_dump_context.hh" namespace HAC { namespace entity { class unroll_context; class scopespace; struct bool_tag; template <class> class state_instance; /** Namespace for RTE objects. There are classes that are stored in process definitions, but not the final result of unroll-creation. */ namespace PRS { struct rule_dump_context; struct expr_dump_context; } namespace RTE { class footprint; // defined in "Object/lang/RTE_footprint.h" using std::list; using std::istream; using std::ostream; using util::good_bool; using util::memory::never_ptr; using util::memory::excl_ptr; using util::memory::count_ptr; using util::memory::sticky_ptr; using util::persistent; using util::persistent_object_manager; //============================================================================= class atomic_assignment; class rte_expr; typedef count_ptr<rte_expr> rte_expr_ptr_type; typedef count_ptr<const rte_expr> const_rte_expr_ptr_type; typedef state_instance<bool_tag> bool_instance_type; typedef instance_pool<bool_instance_type> node_pool_type; typedef size_t node_index_type; //============================================================================= /** Dump modifier for RTE assignments. */ typedef PRS::rule_dump_context assignment_dump_context; /** Helper class for controlling RTE and expression dumps. Reuse from PRS. */ typedef PRS::expr_dump_context expr_dump_context; //============================================================================= /** Abstract base class for a production atomic_assignment. TODO: parent link for upward structure? */ class atomic_assignment : public persistent { public: atomic_assignment() { } virtual ~atomic_assignment() { } virtual ostream& dump(ostream&, const assignment_dump_context&) const = 0; /** Prototype for unroll visiting. */ #define RTE_UNROLL_ASSIGN_PROTO \ good_bool \ unroll(const unroll_context&) const virtual RTE_UNROLL_ASSIGN_PROTO = 0; #define RTE_CHECK_ASSIGN_PROTO \ void check(void) const virtual RTE_CHECK_ASSIGN_PROTO = 0; struct checker; struct dumper; }; // end class atomic_assignment //============================================================================= /** A collection or production assignments. This class wants to be pure-virtual, except that it is instantiated non-dynamically by process_definition. */ class assignment_set_base : public list<sticky_ptr<atomic_assignment> > { protected: typedef list<sticky_ptr<atomic_assignment> > parent_type; public: typedef parent_type::value_type value_type; public: assignment_set_base(); // dtor needs to be polymorphic to dynamic_cast to assignment_set virtual ~assignment_set_base(); #if 0 private: // not copy-constructible, or should be restricted with run-time check explicit assignment_set(_baseconst this_type&); #endif public: ostream& dump(ostream&, const assignment_dump_context& = assignment_dump_context()) const; void append_assignment(excl_ptr<atomic_assignment>&); template <class R> void append_assignment(excl_ptr<R>& r) { excl_ptr<atomic_assignment> tr = r.template as_a_xfer<atomic_assignment>(); this->append_assignment(tr); } // supply these for derived classes RTE_UNROLL_ASSIGN_PROTO; RTE_CHECK_ASSIGN_PROTO; void collect_transient_info_base(persistent_object_manager&) const; void write_object_base(const persistent_object_manager&, ostream&) const; void load_object_base(const persistent_object_manager&, istream&); private: // hide this from user using parent_type::push_back; }; // end class assignment_set_base typedef assignment_set_base nested_assignments; //============================================================================= /** Abstract class of atomic assignment expressions. These expressions are not unrolled. */ class rte_expr : public persistent { public: /** Worry about implementation efficiency later... (Vector of raw pointers or excl_ptr with copy-constructor.) */ typedef list<rte_expr_ptr_type> expr_sequence_type; public: rte_expr() { } virtual ~rte_expr() { } virtual ostream& dump(ostream&, const expr_dump_context&) const = 0; ostream& dump(ostream& o) const { return dump(o, expr_dump_context()); } virtual void check(void) const = 0; // accumulate set of used node indices #define RTE_UNROLL_EXPR_PROTO \ size_t \ unroll(const unroll_context&) const virtual RTE_UNROLL_EXPR_PROTO = 0; #define RTE_UNROLL_COPY_PROTO \ rte_expr_ptr_type \ unroll_copy(const unroll_context&, const rte_expr_ptr_type&) const virtual RTE_UNROLL_COPY_PROTO = 0; protected: struct checker; struct unroller; struct unroll_copier; }; // end class rte_expr //============================================================================= } // end namespace RTE } // end namespace entity } // end namespace HAC #endif // __HAC_OBJECT_LANG_RTE_BASE_HH__
25.112676
82
0.699944
693aeabc53dcfc994d0188e2eb63a1f5a1f21dab
707
cc
C++
tools/asm.cc
nlewycky/x64asm
66dcdef5dba596cb0a51edde1910194d079e704c
[ "Apache-2.0" ]
453
2015-04-24T13:57:43.000Z
2022-03-16T16:38:53.000Z
tools/asm.cc
nlewycky/x64asm
66dcdef5dba596cb0a51edde1910194d079e704c
[ "Apache-2.0" ]
71
2015-04-15T20:52:13.000Z
2018-07-29T18:08:22.000Z
tools/asm.cc
nlewycky/x64asm
66dcdef5dba596cb0a51edde1910194d079e704c
[ "Apache-2.0" ]
67
2015-05-07T06:44:47.000Z
2022-02-25T03:46:24.000Z
#include <iostream> #include <string> #include "include/x64asm.h" using namespace std; using namespace x64asm; using namespace cpputil; /** A simple test program. Reads att syntax and prints human readable hex. */ int main(int argc, char** argv) { Code c; cin >> c; if(failed(cin)) { cerr << endl << "Parse error encountered." << endl; cerr << fail_msg(cin); return 1; } cout << endl; cout << "Assembling..." << endl << c << endl << endl << endl; auto result = Assembler().assemble(c); if(!result.first) { cout << "Could not assemble; 8-bit jump offset was given but target was further away." << endl; } else { cout << result.second << endl; } return 0; }
21.424242
99
0.623762
693e2dceeaa7ce9a1e380914e119a2923fabe70c
5,311
cc
C++
headless/lib/headless_web_contents_browsertest.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
headless/lib/headless_web_contents_browsertest.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
headless/lib/headless_web_contents_browsertest.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2016 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. #include <memory> #include <string> #include <vector> #include "base/base64.h" #include "content/public/test/browser_test.h" #include "headless/public/devtools/domains/page.h" #include "headless/public/devtools/domains/runtime.h" #include "headless/public/devtools/domains/security.h" #include "headless/public/headless_browser.h" #include "headless/public/headless_devtools_client.h" #include "headless/public/headless_web_contents.h" #include "headless/test/headless_browser_test.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/geometry/size.h" #include "url/gurl.h" using testing::UnorderedElementsAre; namespace headless { class HeadlessWebContentsTest : public HeadlessBrowserTest {}; IN_PROC_BROWSER_TEST_F(HeadlessWebContentsTest, Navigation) { EXPECT_TRUE(embedded_test_server()->Start()); HeadlessBrowserContext* browser_context = browser()->CreateBrowserContextBuilder().Build(); HeadlessWebContents* web_contents = browser_context->CreateWebContentsBuilder() .SetInitialURL(embedded_test_server()->GetURL("/hello.html")) .Build(); EXPECT_TRUE(WaitForLoad(web_contents)); EXPECT_THAT(browser_context->GetAllWebContents(), UnorderedElementsAre(web_contents)); } IN_PROC_BROWSER_TEST_F(HeadlessWebContentsTest, WindowOpen) { EXPECT_TRUE(embedded_test_server()->Start()); HeadlessBrowserContext* browser_context = browser()->CreateBrowserContextBuilder().Build(); HeadlessWebContents* web_contents = browser_context->CreateWebContentsBuilder() .SetInitialURL(embedded_test_server()->GetURL("/window_open.html")) .Build(); EXPECT_TRUE(WaitForLoad(web_contents)); EXPECT_EQ(static_cast<size_t>(2), browser_context->GetAllWebContents().size()); } namespace { bool DecodePNG(std::string base64_data, SkBitmap* bitmap) { std::string png_data; if (!base::Base64Decode(base64_data, &png_data)) return false; return gfx::PNGCodec::Decode( reinterpret_cast<unsigned const char*>(png_data.data()), png_data.size(), bitmap); } } // namespace // Parameter specifies whether --disable-gpu should be used. class HeadlessWebContentsScreenshotTest : public HeadlessAsyncDevTooledBrowserTest, public ::testing::WithParamInterface<bool> { public: void SetUp() override { EnablePixelOutput(); if (GetParam()) UseSoftwareCompositing(); HeadlessAsyncDevTooledBrowserTest::SetUp(); } void RunDevTooledTest() override { std::unique_ptr<runtime::EvaluateParams> params = runtime::EvaluateParams::Builder() .SetExpression("document.body.style.background = '#0000ff'") .Build(); devtools_client_->GetRuntime()->Evaluate( std::move(params), base::Bind(&HeadlessWebContentsScreenshotTest::OnPageSetupCompleted, base::Unretained(this))); } void OnPageSetupCompleted(std::unique_ptr<runtime::EvaluateResult> result) { devtools_client_->GetPage()->GetExperimental()->CaptureScreenshot( page::CaptureScreenshotParams::Builder().Build(), base::Bind(&HeadlessWebContentsScreenshotTest::OnScreenshotCaptured, base::Unretained(this))); } void OnScreenshotCaptured( std::unique_ptr<page::CaptureScreenshotResult> result) { std::string base64 = result->GetData(); EXPECT_LT(0U, base64.length()); SkBitmap result_bitmap; EXPECT_TRUE(DecodePNG(base64, &result_bitmap)); EXPECT_EQ(800, result_bitmap.width()); EXPECT_EQ(600, result_bitmap.height()); SkColor actual_color = result_bitmap.getColor(400, 300); SkColor expected_color = SkColorSetRGB(0x00, 0x00, 0xff); EXPECT_EQ(expected_color, actual_color); FinishAsynchronousTest(); } }; HEADLESS_ASYNC_DEVTOOLED_TEST_P(HeadlessWebContentsScreenshotTest); // Instantiate test case for both software and gpu compositing modes. INSTANTIATE_TEST_CASE_P(HeadlessWebContentsScreenshotTests, HeadlessWebContentsScreenshotTest, ::testing::Bool()); class HeadlessWebContentsSecurityTest : public HeadlessAsyncDevTooledBrowserTest, public security::ExperimentalObserver { public: void RunDevTooledTest() override { devtools_client_->GetSecurity()->GetExperimental()->AddObserver(this); devtools_client_->GetSecurity()->GetExperimental()->Enable( security::EnableParams::Builder().Build()); } void OnSecurityStateChanged( const security::SecurityStateChangedParams& params) override { EXPECT_EQ(security::SecurityState::NEUTRAL, params.GetSecurityState()); devtools_client_->GetSecurity()->GetExperimental()->Disable( security::DisableParams::Builder().Build()); devtools_client_->GetSecurity()->GetExperimental()->RemoveObserver(this); FinishAsynchronousTest(); } }; HEADLESS_ASYNC_DEVTOOLED_TEST_F(HeadlessWebContentsSecurityTest); } // namespace headless
34.940789
79
0.73489
6940386d648a434dc6e8ac461aa5ab1d701f969e
5,024
hpp
C++
vot.hpp
Lee-Kevin/kcf_simple
15434ce885b8dad27ade2171920def2264abb5ec
[ "Unlicense" ]
425
2015-12-17T13:05:53.000Z
2022-03-29T01:10:19.000Z
vot.hpp
Lee-Kevin/kcf_simple
15434ce885b8dad27ade2171920def2264abb5ec
[ "Unlicense" ]
27
2016-08-16T11:25:49.000Z
2021-06-28T12:04:54.000Z
vot.hpp
Lee-Kevin/kcf_simple
15434ce885b8dad27ade2171920def2264abb5ec
[ "Unlicense" ]
205
2016-01-22T06:20:59.000Z
2022-03-02T02:53:09.000Z
/* * Author : Tomas Vojir * Date : 2013-06-05 * Desc : Simple class for parsing VOT inputs and providing * interface for image loading and storing output. */ #ifndef CPP_VOT_H #define CPP_VOT_H #include <string> #include <fstream> #include <iostream> #include <opencv2/opencv.hpp> // Bounding box type /* format: 2 3 1 4 */ typedef struct { float x1; //bottom left float y1; float x2; //top left float y2; float x3; //top right float y3; float x4; //bottom right float y4; } VOTPolygon; class VOT { public: VOT(const std::string & region_file, const std::string & images, const std::string & ouput) { _images = images; p_region_stream.open(region_file.c_str()); VOTPolygon p; if (p_region_stream.is_open()){ std::string line; std::getline(p_region_stream, line); std::vector<float> numbers; std::istringstream s( line ); float x; char ch; while (s >> x){ numbers.push_back(x); s >> ch; } if (numbers.size() == 4) { float x = numbers[0], y = numbers[1], w = numbers[2], h = numbers[3]; p.x1 = x; p.y1 = y + h; p.x2 = x; p.y2 = y; p.x3 = x + w; p.y3 = y; p.x4 = x + w; p.y4 = y + h; } else if (numbers.size() == 8) { p.x1 = numbers[0]; p.y1 = numbers[1]; p.x2 = numbers[2]; p.y2 = numbers[3]; p.x3 = numbers[4]; p.y3 = numbers[5]; p.x4 = numbers[6]; p.y4 = numbers[7]; } else { std::cerr << "Error loading initial region in file - unknow format " << region_file << "!" << std::endl; p.x1=0; p.y1=0; p.x2=0; p.y2=0; p.x3=0; p.y3=0; p.x4=0; p.y4=0; } }else{ std::cerr << "Error loading initial region in file " << region_file << "!" << std::endl; p.x1=0; p.y1=0; p.x2=0; p.y2=0; p.x3=0; p.y3=0; p.x4=0; p.y4=0; } p_init_polygon = p; p_images_stream.open(images.c_str()); if (!p_images_stream.is_open()) std::cerr << "Error loading image file " << images << "!" << std::endl; p_output_stream.open(ouput.c_str()); if (!p_output_stream.is_open()) std::cerr << "Error opening output file " << ouput << "!" << std::endl; } ~VOT() { p_region_stream.close(); p_images_stream.close(); p_output_stream.close(); } inline cv::Rect getInitRectangle() const { // read init box from ground truth file VOTPolygon initPolygon = getInitPolygon(); float x1 = std::min(initPolygon.x1, std::min(initPolygon.x2, std::min(initPolygon.x3, initPolygon.x4))); float x2 = std::max(initPolygon.x1, std::max(initPolygon.x2, std::max(initPolygon.x3, initPolygon.x4))); float y1 = std::min(initPolygon.y1, std::min(initPolygon.y2, std::min(initPolygon.y3, initPolygon.y4))); float y2 = std::max(initPolygon.y1, std::max(initPolygon.y2, std::max(initPolygon.y3, initPolygon.y4))); return cv::Rect(x1, y1, x2-x1, y2-y1); } inline VOTPolygon getInitPolygon() const { return p_init_polygon; } inline void outputBoundingBox(const cv::Rect & bbox) { p_output_stream << bbox.x << "," << bbox.y << ","; p_output_stream << bbox.width << "," << bbox.height << std::endl; } inline void outputPolygon(const VOTPolygon & poly) { p_output_stream << poly.x1 << "," << poly.y1 << ","; p_output_stream << poly.x2 << "," << poly.y2 << ","; p_output_stream << poly.x3 << "," << poly.y3 << ","; p_output_stream << poly.x4 << "," << poly.y4 << std::endl; } inline int getNextFileName(char * fName) { if (p_images_stream.eof() || !p_images_stream.is_open()) return -1; std::string line; std::getline (p_images_stream, line); strcpy(fName, line.c_str()); return 1; } inline int getNextImage(cv::Mat & img) { if (p_images_stream.eof() || !p_images_stream.is_open()) return -1; std::string line; std::getline (p_images_stream, line); if (line.empty() && p_images_stream.eof()) return -1; img = cv::imread(line, CV_LOAD_IMAGE_COLOR); return 1; } private: std::string _images; VOTPolygon p_init_polygon; std::ifstream p_region_stream; std::ifstream p_images_stream; std::ofstream p_output_stream; }; #endif //CPP_VOT_H
28.873563
120
0.50418
6945c9c8b7810e43e61f71f5df408da0daf7cb31
356
cc
C++
src/ios_tools/web/test/test_url_constants.cc
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
src/ios_tools/web/test/test_url_constants.cc
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
src/ios_tools/web/test/test_url_constants.cc
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2016 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. #include "ios/web/test/test_url_constants.h" namespace web { const char kTestWebUIScheme[] = "testwebui"; const char kTestNativeContentScheme[] = "testnativecontent"; } // namespace web
27.384615
73
0.755618
69464a87b068e235a75daed0aabf2f5a7d1594e0
3,466
cpp
C++
CA7-Source/userspace/netlink_tester.cpp
dimtass/stm32mp1-rpmsg-netlink-example
998f61db13fa434e97119c751c6958c1eee43727
[ "MIT" ]
7
2020-10-07T12:12:45.000Z
2022-01-27T10:51:48.000Z
CA7-Source/userspace/netlink_tester.cpp
dimtass/stm32mp1-rpmsg-netlink-example
998f61db13fa434e97119c751c6958c1eee43727
[ "MIT" ]
null
null
null
CA7-Source/userspace/netlink_tester.cpp
dimtass/stm32mp1-rpmsg-netlink-example
998f61db13fa434e97119c751c6958c1eee43727
[ "MIT" ]
null
null
null
#include <string> #include <time.h> #include "netlink_tester.h" enum { COM_BUFFER_SIZE=32768, }; enum { CRC16_INIT_VAL=0x8006, }; static uint8_t tx_buffer[COM_BUFFER_SIZE] = {0}; static uint8_t rx_buffer[COM_BUFFER_SIZE] = {0}; /* Function prototypes */ NetlinkTester::NetlinkTester() { L_(linfo) << "Initialized netlink client."; init_buffer(tx_buffer, COM_BUFFER_SIZE); } NetlinkTester::~NetlinkTester() { } void NetlinkTester::init_buffer(uint8_t * buffer, size_t buffer_size) { for (int i=0; i<buffer_size; i++) { buffer[i] = 0xff & i; } // Calculate CRC uint16_t crc = crc16(buffer, buffer_size); L_(linfo) << "Initialized buffer with CRC16: 0x" << std::hex << crc; } void NetlinkTester::add_test(size_t n_bytes) { struct test_item item = {n_bytes, 0}; m_tests.push_back(item); L_(linfo) << "-> Add test: size=" << n_bytes; } size_t NetlinkTester::get_num_of_tests() { return(m_tests.size()); } int NetlinkTester::run_test(size_t index, struct test_item & item) { if (m_tests.size() > index) { item = m_tests.at(index); NetlinkClient nlc; /* prepare packet */ struct packet * out = (struct packet *) &tx_buffer[0]; out->preamble = PREAMBLE; out->length = item.n_bytes; // + sizeof(struct packet); // Nah, nevermind out->crc16 = crc16(&tx_buffer[sizeof(out) - 1], out->length); struct timespec start_time = get_time_ns(); size_t tx_len = nlc.send(tx_buffer, item.n_bytes, rx_buffer); struct timespec stop_time = get_time_ns(); item.time = timespec_diff(start_time, stop_time); L_(linfo) << "-> b: " << item.n_bytes << ", nsec: " << item.time << ", bytes sent: " << std::dec << tx_len; return(0); } return -1; } struct timespec NetlinkTester::get_time_ns() { struct timespec t; clock_gettime(CLOCK_REALTIME, &t); return(t); } long NetlinkTester::timespec_diff (struct timespec t1, struct timespec t2) { struct timespec diff; if (t2.tv_nsec-t1.tv_nsec < 0) { diff.tv_sec = t2.tv_sec - t1.tv_sec - 1; diff.tv_nsec = t2.tv_nsec - t1.tv_nsec + 1000000000; } else { diff.tv_sec = t2.tv_sec - t1.tv_sec; diff.tv_nsec = t2.tv_nsec - t1.tv_nsec; } return (diff.tv_sec * 1000000000.0 + diff.tv_nsec); } uint16_t NetlinkTester::crc16(const uint8_t * buffer, uint16_t len) { unsigned short out = 0; int bits_read = 0, bit_flag; /* Sanity check: */ if( buffer == NULL ) return 0; while( len > 0 ) { bit_flag = out >> 15; /* Get next bit: */ out <<= 1; out |= ( *buffer >> bits_read ) & 1; // item a) work from the least significant bits /* Increment bit counter: */ bits_read++; if( bits_read > 7 ) { bits_read = 0; buffer++; len--; } /* Cycle check: */ if( bit_flag ) out ^= CRC16_INIT_VAL; } // item b) "push out" the last 16 bits int i; for( i = 0; i < 16; ++i ) { bit_flag = out >> 15; out <<= 1; if( bit_flag ) out ^= CRC16_INIT_VAL; } // item c) reverse the bits unsigned short crc = 0; i = 0x8000; int j = 0x0001; for( ; i != 0; i >>= 1, j <<= 1 ) { if( i & out ) crc |= j; } return crc; }
22.653595
92
0.566359
69468e507e7a5d9ca905811719512c5c7eb23e8a
2,018
cpp
C++
src/cmd_vel_sub.cpp
Aung-xiao/hero_chassis_controller
be9295b5f19bbbb02eff66fc5927c786e7bfdc0b
[ "BSD-3-Clause" ]
null
null
null
src/cmd_vel_sub.cpp
Aung-xiao/hero_chassis_controller
be9295b5f19bbbb02eff66fc5927c786e7bfdc0b
[ "BSD-3-Clause" ]
null
null
null
src/cmd_vel_sub.cpp
Aung-xiao/hero_chassis_controller
be9295b5f19bbbb02eff66fc5927c786e7bfdc0b
[ "BSD-3-Clause" ]
null
null
null
#include<ros/ros.h> #include<geometry_msgs/Twist.h> #include<iostream> #include <effort_controllers/joint_velocity_controller.h> #include <dynamic_tutorial/tutorialConfig.h> #include <dynamic_reconfigure/client.h> hardware_interface::JointHandle front_left_joint_,back_left_joint_,front_right_joint_,back_right_joint_; double front_left_command_,front_right_command_,back_right_command_,back_left_command_,base,track,vx,vy,vth; void callback(const geometry_msgs::Twist &cmd_vel) { ROS_INFO("Received a /cmd_vel message!"); vx=cmd_vel.linear.x; vy=cmd_vel.linear.y; vth=cmd_vel.angular.z; ROS_INFO("wheel_track=%f,wheel_base=%f",track,base); ROS_INFO("vx=:[%f],vy=:[%f],vth=:[%f]", vx,vy,vth); front_left_command_ = vx-vy-vth*(track+base)/2; front_right_command_ =vx+vy+vth*(track+base)/2; back_left_command_ = vx-vy+vth*(track+base)/2; back_right_command_ =vx+vy-vth*(track+base)/2; ROS_INFO("v1=%f,v2=%f,v3=%f,v4=%f",front_left_command_,front_right_command_,back_right_command_,back_left_command_); // front_left_joint_.setCommand(front_left_command_); // front_right_joint_.setCommand(front_right_command_); // back_left_joint_.setCommand(back_left_command_ ); // back_right_joint_.setCommand(back_right_command_); // This function cam not work properly } void dynCallBack(const dynamic_tutorial::tutorialConfig &config) { ROS_INFO("wheel_track=%f,wheel_base=%f",config.wheel_track,config.wheel_base); } int main(int argc, char** argv) { ros::init(argc, argv, "cmd_vel_listener"); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("cmd_vel", 1000, callback); dynamic_reconfigure::Client<dynamic_tutorial::tutorialConfig> dynamic_client("dynamic_tutorial_node", dynCallBack); dynamic_tutorial::tutorialConfig cmd_dynamic_client; cmd_dynamic_client.wheel_track=0.500; cmd_dynamic_client.wheel_base=0.475; base=cmd_dynamic_client.wheel_base; track=cmd_dynamic_client.wheel_track; ros::spin(); return 1; }
38.807692
120
0.763132
6946c8189c7d3aef9aabf1177b4665e1c55b54cf
54,121
cpp
C++
src/sparse_spectral_approximation/txssa.cpp
cjhurani/txssa
473bb4ec650cb7164d80fc531ac38a6c28226dd8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-06-04T01:00:14.000Z
2022-03-25T23:40:57.000Z
src/sparse_spectral_approximation/txssa.cpp
cjhurani/txssa
473bb4ec650cb7164d80fc531ac38a6c28226dd8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2017-08-28T09:08:53.000Z
2021-06-08T14:17:48.000Z
src/sparse_spectral_approximation/txssa.cpp
cjhurani/txssa
473bb4ec650cb7164d80fc531ac38a6c28226dd8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
/* TxSSA: Tech-X Sparse Spectral Approximation Copyright (C) 2012 Tech-X Corporation, 5621 Arapahoe Ave, Boulder CO 80303 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 Tech-X Corporation 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. */ /* Authors: 1. Chetan Jhurani (chetan.jhurani@gmail.com, jhurani@txcorp.com) For more information and relevant publications, visit http://www.ices.utexas.edu/~chetan/ 2. Travis M. Austin (austin@txcorp.com) Contact address: Tech-X Corporation 5621 Arapahoe Ave Boulder, CO 80303 http://www.txcorp.com */ // ----------------------------------------------------------------------------- #include "txssa.h" #include "sparse_spectral_approximation/ssa_matrix_type.h" #include "sparse_spectral_approximation/ssa_matrix_type_pinv_transpose.h" #include "sparse_spectral_approximation/sparse_spectral_minimization.h" #include "sparse_spectral_approximation/sparse_spectral_misfit_lhs_matrices.h" #include "sparse_spectral_approximation/sparse_spectral_binning.h" #include "sparse_vectors/sparse_vectors.h" #include "p_norm_sparsity_matrix/p_norm_sparsity_dense_matrix.h" #include "dense_algorithms/dense_matrix_utils.h" #include "dense_vectors/dense_vectors.h" #include "math/precision_traits.h" #include "internal_api_error/internal_api_error.h" #include <algorithm> // std::copy #include <vector> #include <stdexcept> #include <complex> #include <cassert> #include <new> // ----------------------------------------------------------------------------- #ifdef _MSC_VER #pragma warning( disable : 4514 ) // unreferenced inline function has been removed #pragma warning( disable : 4710 ) // function not inlined #endif // ----------------------------------------------------------------------------- const unsigned int ssa_impl_version = 0; // ----------------------------------------------------------------------------- namespace { // ----------------------------------------------------------------------------- template<typename T> void delete_catch(T* ptr, const char* func_name) { try { delete ptr; } catch(...) { assert(false); internal_api_error_set_last( std::string(func_name) + ": Exception in deleting a pointer."); } } // ----------------------------------------------------------------------------- template<typename index_type, typename value_type> bool ssa_matrix_type_compute_AAT_from_ATA( index_type size, const value_type* ATA_col_values, index_type ATA_col_leading_dim, value_type* AAT_col_values, index_type AAT_col_leading_dim, ssa_matrix_type type) { bool success = false; // This is the only one implemented/needed now. if(type == ssa_matrix_type_complex_symmetric) { success = dense_matrix_utils_complex_sym_compute_AAT_from_ATA( size, ATA_col_values, ATA_col_leading_dim, AAT_col_values, AAT_col_leading_dim); } if(!success) { assert(false); internal_api_error_set_last( "ssa_matrix_type_compute_AAT_from_ATA: Error"); } return success; } // ----------------------------------------------------------------------------- template<typename index_type, typename value_type> void ssa_B2TB2_chooser( const dense_vectors<index_type, value_type>& B1TB1, const dense_vectors<index_type, value_type>& B2TB2, ssa_matrix_type matrix_type, bool is_binned, const value_type*& tmp_B2TB2_col_values, typename precision_traits<value_type>::scalar& mult_factor) { // The reason we compute B1B1T and then compute B2TB2 from it instead of // the other way around (this is when such the two matrices are related), // is that on some Intel MKL versions X'*X is slightly faster than X*X', // say, 5-10%. // hermitian implies normal, so only 6 combinations. // hermitian binned normal b2 mult_factor // 0 0 0 pass b2 2 // 0 0 1 pass b1 2 // 0 1 0 pass b2 2 // 0 1 1 pass b1 2 // 1 0 1 pass b1 2 // 1 1 1 pass 0 1 tmp_B2TB2_col_values = 0; const int is_hermitian = ssa_matrix_type_is_hermitian(matrix_type); const int is_normal = ssa_matrix_type_is_normal(matrix_type); if(is_normal) { if(!is_hermitian || !is_binned) { tmp_B2TB2_col_values = B1TB1.vec_values(); } } else { tmp_B2TB2_col_values = B2TB2.vec_values(); } typedef typename precision_traits<value_type>::scalar scalar_type; mult_factor = tmp_B2TB2_col_values ? scalar_type(2) : scalar_type(1); } // ----------------------------------------------------------------------------- // User-given parameters for computing L_p norm based pattern. template < typename index_type, typename offset_type, typename value_type > bool ssa_lpn_internal( index_type num_rows, index_type num_cols, const value_type* col_values, index_type col_leading_dim, typename precision_traits<value_type>::scalar sparsity_ratio, typename precision_traits<value_type>::scalar sparsity_norm_p, offset_type max_num_bins, bool impose_null_spaces, enum ssa_matrix_type matrix_type, ssa_csr<index_type, offset_type, value_type>& out_matrix) { ssa_error_clear(); const int is_abs_sym = ssa_matrix_type_is_abs_sym(matrix_type); bool success = ssa_matrix_type_undefined < matrix_type && matrix_type < ssa_matrix_type_num_types && (num_rows == num_cols || !is_abs_sym) && col_values; if(!success) { assert(false); internal_api_error_set_last( "ssa_lpn_internal: Unacceptable input argument(s)."); return false; } dense_vectors<index_type, value_type> pinv_AT, left_null_space, right_null_space; dense_vectors<index_type, value_type>* left_null_space_ptr = 0; dense_vectors<index_type, value_type>* right_null_space_ptr = 0; if(impose_null_spaces) { left_null_space_ptr = &left_null_space; right_null_space_ptr = &right_null_space; } success = pinv_AT.allocate( num_cols, num_rows) && dense_vectors_utils_copy( num_cols, num_rows, col_values, col_leading_dim, pinv_AT.vec_values(), pinv_AT.leading_dimension()) && ssa_matrix_type_pinv_transpose( num_rows, num_cols, pinv_AT.vec_values(), pinv_AT.leading_dimension(), matrix_type, left_null_space_ptr, right_null_space_ptr); if(success) { // ISSUE: Ideally, we should be using an equivalent of the near_zero_row_col // function written in the MATLAB code to compute min_num_nnz_per_row // and min_num_nnz_per_col. We skip that step. const index_type min_num_nnz_per_row = right_null_space.num_vecs(); const index_type min_num_nnz_per_col = left_null_space.num_vecs(); std::vector< std::vector<index_type> > row_oriented_sparse_pat; if(is_abs_sym) { const int left_right_nullity_equal = ssa_matrix_type_is_left_right_nullity_equal(matrix_type); if(left_right_nullity_equal && min_num_nnz_per_row != min_num_nnz_per_col) { assert(false); internal_api_error_set_last( "ssa_lpn_internal: Left and right nullity should be equal" " because of matrix type, but not computed to be equal."); return false; } success = p_norm_sparsity_dense_matrix_abs_sym( sparsity_ratio, sparsity_norm_p, min_num_nnz_per_row, num_rows, col_values, col_leading_dim, row_oriented_sparse_pat); } else { success = p_norm_sparsity_dense_matrix_col_oriented( sparsity_ratio, sparsity_norm_p, min_num_nnz_per_row, min_num_nnz_per_col, num_rows, num_cols, col_values, col_leading_dim, row_oriented_sparse_pat); } if(success) { std::vector<index_type> size_per_row(num_rows); for(index_type row = 0; row < num_rows; ++row) size_per_row[row] = index_type(row_oriented_sparse_pat[row].size()); sparse_vectors<index_type, offset_type, value_type>* out_mat_ptr = new (std::nothrow) sparse_vectors<index_type, offset_type, value_type>(); if(!out_mat_ptr) { assert(false); internal_api_error_set_last( "ssa_lpn_internal: Error in allocating matrix."); return false; } if(num_rows > 0) { success = out_mat_ptr->allocate(num_rows, num_cols, &size_per_row.front()); } else { index_type tmp_size_per_row = 0; success = out_mat_ptr->allocate(num_rows, num_cols, &tmp_size_per_row); } if(success) { for(index_type row = 0; row < num_rows; ++row) std::copy( row_oriented_sparse_pat[row].begin(), row_oriented_sparse_pat[row].end(), out_mat_ptr->vec_ids_begin(row)); success = ssa_internal( num_rows, num_cols, col_values, col_leading_dim, out_mat_ptr->vec_offsets(), out_mat_ptr->vec_ids(), max_num_bins, impose_null_spaces, pinv_AT, left_null_space, right_null_space, matrix_type, out_mat_ptr->vec_values()); if(success) { out_matrix.row_offsets = out_mat_ptr->vec_offsets(); out_matrix.column_ids = out_mat_ptr->vec_ids(); out_matrix.values = out_mat_ptr->vec_values(); out_matrix.reserved = out_mat_ptr; } } } } if(!success) { assert(false); internal_api_error_set_last( "ssa_lpn_internal: Error"); } return success; } // ----------------------------------------------------------------------------- template < typename index_type, typename offset_type, typename value_type > bool ssa_ids_internal( index_type num_rows, index_type num_cols, const value_type* col_values, index_type col_leading_dim, typename precision_traits<value_type>::scalar sparsity_ratio, typename precision_traits<value_type>::scalar sparsity_norm_p, index_type min_num_nnz_per_row, index_type min_num_nnz_per_col, enum ssa_matrix_type matrix_type, ssa_csr<index_type, offset_type, value_type>& out_matrix) { ssa_error_clear(); const int is_abs_sym = ssa_matrix_type_is_abs_sym(matrix_type); bool success = ssa_matrix_type_undefined < matrix_type && matrix_type < ssa_matrix_type_num_types && (num_rows == num_cols || !is_abs_sym) && (min_num_nnz_per_row == min_num_nnz_per_col || !is_abs_sym) && col_values; if(!success) { assert(false); internal_api_error_set_last( "ssa_ids_internal: Unacceptable input argument(s)."); return false; } std::vector< std::vector<index_type> > row_oriented_sparse_pat; if(is_abs_sym) { success = p_norm_sparsity_dense_matrix_abs_sym( sparsity_ratio, sparsity_norm_p, min_num_nnz_per_row, num_rows, col_values, col_leading_dim, row_oriented_sparse_pat); } else { success = p_norm_sparsity_dense_matrix_col_oriented( sparsity_ratio, sparsity_norm_p, min_num_nnz_per_row, min_num_nnz_per_col, num_rows, num_cols, col_values, col_leading_dim, row_oriented_sparse_pat); } if(success) { std::vector<index_type> size_per_row(num_rows); for(index_type row = 0; row < num_rows; ++row) size_per_row[row] = index_type(row_oriented_sparse_pat[row].size()); sparse_vectors<index_type, offset_type, value_type>* out_mat_ptr = new (std::nothrow) sparse_vectors<index_type, offset_type, value_type>(); if(!out_mat_ptr) { assert(false); internal_api_error_set_last( "ssa_ids_internal: Error in allocating matrix."); return false; } success = out_mat_ptr->allocate(num_rows, num_cols, &size_per_row.front()); if(success) { for(index_type row = 0; row < num_rows; ++row) std::copy( row_oriented_sparse_pat[row].begin(), row_oriented_sparse_pat[row].end(), out_mat_ptr->vec_ids_begin(row)); out_matrix.row_offsets = out_mat_ptr->vec_offsets(); out_matrix.column_ids = out_mat_ptr->vec_ids(); out_matrix.values = out_mat_ptr->vec_values(); out_matrix.reserved = out_mat_ptr; } } if(!success) { assert(false); internal_api_error_set_last( "ssa_ids_internal: Error"); } return success; } // ----------------------------------------------------------------------------- // For real matrices template < typename index_type, typename offset_type, typename value_type > bool ssa_internal( index_type num_rows, index_type num_cols, const value_type* col_values, // num_rows x num_cols index_type col_leading_dim, const offset_type* row_offsets, // num_rows + 1 const index_type* column_ids, // row_offsets[num_rows] offset_type max_num_bins, bool impose_null_spaces, const dense_vectors<index_type, value_type>& pinv_AT, const dense_vectors<index_type, value_type>& left_null_space, const dense_vectors<index_type, value_type>& right_null_space, ssa_matrix_type matrix_type, value_type* out_row_values) // row_offsets[num_rows] { const int is_square = (num_rows == num_cols); const int is_hermitian = ssa_matrix_type_is_hermitian(matrix_type); const int is_normal = ssa_matrix_type_is_normal(matrix_type); bool success = !( is_hermitian || is_normal ) || is_square; if(!success) { assert(false); internal_api_error_set_last( "ssa_internal: Unacceptable input argument(s) in real version."); return false; } std::vector<offset_type> row_bin_ids; try { row_bin_ids.resize(row_offsets[num_rows]); } catch(const std::exception& exc) { assert(false); internal_api_error_set_last( (std::string("ssa_internal: Exception in the real version. ") + exc.what())); return false; } dense_vectors<index_type, value_type> B1TB1, B2TB2; offset_type actual_num_bins; dense_vectors<offset_type, sparse_vectors_ids<index_type, offset_type> > row_split_pattern, col_split_pattern; success = sparse_spectral_binning_row( num_rows, num_cols, col_values, col_leading_dim, row_offsets, column_ids, max_num_bins, actual_num_bins, row_split_pattern, row_bin_ids.size() ? &row_bin_ids.front() : 0) && // If hermitian, don't have to compute col_split_pattern (is_hermitian ? true : sparse_spectral_binning_to_col( num_rows, num_cols, row_offsets, column_ids, row_bin_ids.size() ? &row_bin_ids.front() : 0, actual_num_bins, col_split_pattern)) && B1TB1.allocate( num_cols, num_cols) && // If normal, don't have to allocate or compute B2TB2 (is_normal ? true : B2TB2.allocate( num_rows, num_rows)) && sparse_spectral_misfit_lhs_matrices( num_rows, num_cols, pinv_AT.vec_values(), pinv_AT.leading_dimension(), B2TB2.vec_values(), B2TB2.leading_dimension(), B1TB1.vec_values(), B1TB1.leading_dimension()); if(success) { const value_type* tmp_B2TB2_col_values = 0; value_type mult_factor; const bool is_binned = max_num_bins != 0; ssa_B2TB2_chooser<index_type, value_type>( B1TB1, B2TB2, matrix_type, is_binned, tmp_B2TB2_col_values, mult_factor); success = sparse_spectral_minimization( num_rows, num_cols, row_offsets, column_ids, actual_num_bins, row_bin_ids.size() ? &row_bin_ids.front() : 0, row_split_pattern.vec_values(), // If hermitian, reuse row_split_pattern as col_split_pattern is_hermitian ? row_split_pattern.vec_values() : col_split_pattern.vec_values(), impose_null_spaces, tmp_B2TB2_col_values, num_rows, B1TB1.vec_values(), B1TB1.leading_dimension(), pinv_AT.vec_values(), pinv_AT.leading_dimension(), left_null_space, right_null_space, out_row_values, mult_factor); } if(!success) { assert(false); internal_api_error_set_last( "ssa_internal: Error in real version."); } return success; } // ----------------------------------------------------------------------------- // For complex matrices template < typename index_type, typename offset_type, typename scalar_type > bool ssa_internal( index_type num_rows, index_type num_cols, const std::complex<scalar_type>* col_values, // num_rows x num_cols index_type col_leading_dim, const offset_type* row_offsets, // num_rows + 1 const index_type* column_ids, // row_offsets[num_rows] offset_type max_num_bins, bool impose_null_spaces, const dense_vectors<index_type, std::complex<scalar_type> >& pinv_AT, const dense_vectors<index_type, std::complex<scalar_type> >& left_null_space, const dense_vectors<index_type, std::complex<scalar_type> >& right_null_space, ssa_matrix_type matrix_type, std::complex<scalar_type>* out_row_values) // row_offsets[num_rows] { const int is_square = (num_rows == num_cols); const int is_hermitian = ssa_matrix_type_is_hermitian(matrix_type); const int is_normal = ssa_matrix_type_is_normal(matrix_type); const int is_real_part_symmetric = ssa_matrix_type_is_real_part_symmetric(matrix_type); const int is_imag_part_symmetric = ssa_matrix_type_is_imag_part_symmetric(matrix_type); const int is_AAT_computable_from_ATA = ssa_matrix_type_is_AAT_computable_from_ATA(matrix_type); bool success = !( is_hermitian || is_normal || is_real_part_symmetric || is_imag_part_symmetric || is_AAT_computable_from_ATA ) || is_square; if(!success) { assert(false); internal_api_error_set_last( "ssa_internal: Unacceptable input argument(s) in complex version."); return false; } std::vector<offset_type> real_row_bin_ids, imag_row_bin_ids; try { real_row_bin_ids.resize(row_offsets[num_rows]); imag_row_bin_ids.resize(row_offsets[num_rows]); } catch(const std::exception& exc) { assert(false); internal_api_error_set_last( (std::string("ssa_internal: Exception in complex version. ") + exc.what())); return false; } dense_vectors<index_type, std::complex<scalar_type> > B1TB1, B2TB2; offset_type real_actual_num_bins, imag_actual_num_bins; dense_vectors<offset_type, sparse_vectors_ids<index_type, offset_type> > real_row_split_pattern, real_col_split_pattern, imag_row_split_pattern, imag_col_split_pattern; success = sparse_spectral_binning_row( num_rows, num_cols, col_values, col_leading_dim, row_offsets, column_ids, max_num_bins, real_actual_num_bins, imag_actual_num_bins, real_row_split_pattern, imag_row_split_pattern, real_row_bin_ids.size() ? &real_row_bin_ids.front() : 0, imag_row_bin_ids.size() ? &imag_row_bin_ids.front() : 0) && // If real part hermitian, don't have to compute real_col_split_pattern (is_real_part_symmetric ? true : sparse_spectral_binning_to_col( num_rows, num_cols, row_offsets, column_ids, real_row_bin_ids.size() ? &real_row_bin_ids.front() : 0, real_actual_num_bins, real_col_split_pattern)) && // If imag part hermitian, don't have to compute imag_col_split_pattern (is_imag_part_symmetric ? true : sparse_spectral_binning_to_col( num_rows, num_cols, row_offsets, column_ids, imag_row_bin_ids.size() ? &imag_row_bin_ids.front() : 0, imag_actual_num_bins, imag_col_split_pattern)) && B1TB1.allocate( num_cols, num_cols) && // If normal, don't have to allocate or compute B2TB2 (is_normal ? true : B2TB2.allocate( num_rows, num_rows)); if(success) { if(is_AAT_computable_from_ATA) { success = sparse_spectral_misfit_lhs_matrices( num_rows, num_cols, pinv_AT.vec_values(), pinv_AT.leading_dimension(), reinterpret_cast<std::complex<scalar_type>*>(0), num_rows, B1TB1.vec_values(), B1TB1.leading_dimension()) && ssa_matrix_type_compute_AAT_from_ATA( num_rows, B1TB1.vec_values(), B1TB1.leading_dimension(), B2TB2.vec_values(), B2TB2.leading_dimension(), matrix_type); } else { success = sparse_spectral_misfit_lhs_matrices( num_rows, num_cols, pinv_AT.vec_values(), pinv_AT.leading_dimension(), B2TB2.vec_values(), B2TB2.leading_dimension(), B1TB1.vec_values(), B1TB1.leading_dimension()); } if(success) { const std::complex<scalar_type>* tmp_B2TB2_col_values = 0; scalar_type mult_factor; const bool is_binned = max_num_bins != 0; ssa_B2TB2_chooser<index_type, std::complex<scalar_type> >( B1TB1, B2TB2, matrix_type, is_binned, tmp_B2TB2_col_values, mult_factor); success = sparse_spectral_minimization( num_rows, num_cols, row_offsets, column_ids, real_actual_num_bins, imag_actual_num_bins, real_row_bin_ids.size() ? &real_row_bin_ids.front() : 0, imag_row_bin_ids.size() ? &imag_row_bin_ids.front() : 0, real_row_split_pattern.vec_values(), imag_row_split_pattern.vec_values(), is_real_part_symmetric ? real_row_split_pattern.vec_values() : real_col_split_pattern.vec_values(), is_imag_part_symmetric ? imag_row_split_pattern.vec_values() : imag_col_split_pattern.vec_values(), impose_null_spaces, tmp_B2TB2_col_values, num_rows, B1TB1.vec_values(), B1TB1.leading_dimension(), pinv_AT.vec_values(), pinv_AT.leading_dimension(), left_null_space, right_null_space, out_row_values, mult_factor); } } if(!success) { assert(false); internal_api_error_set_last( "ssa_internal: Error in complex version."); } return success; } // ----------------------------------------------------------------------------- } // namespace // ----------------------------------------------------------------------------- template < typename index_type, typename offset_type, typename value_type > ssa_csr<index_type, offset_type, value_type>::ssa_csr() : row_offsets(0), column_ids(0), values(0), reserved(0) { } template < typename index_type, typename offset_type, typename value_type > ssa_csr<index_type, offset_type, value_type>::~ssa_csr() { delete_catch(reinterpret_cast <const sparse_vectors<index_type, offset_type, value_type>*>( reserved), "ssa_csr::~ssa_csr()"); reserved = 0; } // ----------------------------------------------------------------------------- // User-given pattern. template < typename index_type, typename offset_type, typename value_type > int ssa_pat( index_type num_rows, index_type num_cols, const value_type* col_values, index_type col_leading_dim, const offset_type* row_offsets, const index_type* column_ids, offset_type max_num_bins, bool impose_null_spaces, enum ssa_matrix_type matrix_type, value_type* out_row_values) { ssa_error_clear(); bool success = ssa_matrix_type_undefined < matrix_type && matrix_type < ssa_matrix_type_num_types && (num_rows == num_cols || !ssa_matrix_type_is_abs_sym(matrix_type)) && col_values && row_offsets && column_ids && out_row_values; if(!success) { assert(false); internal_api_error_set_last( "ssa_pat: Unacceptable input argument(s)."); return false; } dense_vectors<index_type, value_type> pinv_AT, left_null_space, right_null_space; dense_vectors<index_type, value_type>* left_null_space_ptr = 0; dense_vectors<index_type, value_type>* right_null_space_ptr = 0; if(impose_null_spaces) { left_null_space_ptr = &left_null_space; right_null_space_ptr = &right_null_space; } success = pinv_AT.allocate( num_cols, num_rows) && dense_vectors_utils_copy( num_cols, num_rows, col_values, col_leading_dim, pinv_AT.vec_values(), pinv_AT.leading_dimension()) && ssa_matrix_type_pinv_transpose( num_rows, num_cols, pinv_AT.vec_values(), pinv_AT.leading_dimension(), matrix_type, left_null_space_ptr, right_null_space_ptr) && ssa_internal( num_rows, num_cols, col_values, col_leading_dim, row_offsets, column_ids, max_num_bins, impose_null_spaces, pinv_AT, left_null_space, right_null_space, matrix_type, out_row_values); if(!success) { assert(false); internal_api_error_set_last( "ssa_pat: Error."); } return success ? 0 : 1; } // ----------------------------------------------------------------------------- template < typename index_type, typename offset_type, typename value_type > int ssa_lpn( index_type num_rows, index_type num_cols, const value_type* col_values, index_type col_leading_dim, value_type sparsity_ratio, value_type sparsity_norm_p, offset_type max_num_bins, bool impose_null_spaces, enum ssa_matrix_type matrix_type, ssa_csr<index_type, offset_type, value_type>& out_matrix) { bool success = ssa_lpn_internal<index_type, offset_type, value_type>( num_rows, num_cols, col_values, col_leading_dim, sparsity_ratio, sparsity_norm_p, max_num_bins, impose_null_spaces, matrix_type, out_matrix); if(!success) { assert(false); internal_api_error_set_last( "ssa_lpn: Error in real version"); } return success ? 0 : 1; } template < typename index_type, typename offset_type, typename scalar_type > int ssa_lpn( index_type num_rows, index_type num_cols, const std::complex<scalar_type>* col_values, index_type col_leading_dim, scalar_type sparsity_ratio, scalar_type sparsity_norm_p, offset_type max_num_bins, bool impose_null_spaces, enum ssa_matrix_type matrix_type, ssa_csr<index_type, offset_type, std::complex<scalar_type> >& out_matrix) { bool success = ssa_lpn_internal<index_type, offset_type, std::complex<scalar_type> >( num_rows, num_cols, col_values, col_leading_dim, sparsity_ratio, sparsity_norm_p, max_num_bins, impose_null_spaces, matrix_type, out_matrix); if(!success) { assert(false); internal_api_error_set_last( "ssa_lpn: Error in complex version"); } return success ? 0 : 1; } // ----------------------------------------------------------------------------- template < typename index_type, typename offset_type, typename value_type > int ssa_ids( index_type num_rows, index_type num_cols, const value_type* col_values, index_type col_leading_dim, value_type sparsity_ratio, value_type sparsity_norm_p, index_type min_num_nnz_per_row, index_type min_num_nnz_per_col, enum ssa_matrix_type matrix_type, ssa_csr<index_type, offset_type, value_type>& out_matrix) { bool success = ssa_ids_internal<index_type, offset_type, value_type>( num_rows, num_cols, col_values, col_leading_dim, sparsity_ratio, sparsity_norm_p, min_num_nnz_per_row, min_num_nnz_per_col, matrix_type, out_matrix); if(!success) { assert(false); internal_api_error_set_last( "ssa_ids: Error in real version"); } return success ? 0 : 1; } template < typename index_type, typename offset_type, typename scalar_type > int ssa_ids( index_type num_rows, index_type num_cols, const std::complex<scalar_type>* col_values, index_type col_leading_dim, scalar_type sparsity_ratio, scalar_type sparsity_norm_p, index_type min_num_nnz_per_row, index_type min_num_nnz_per_col, enum ssa_matrix_type matrix_type, ssa_csr<index_type, offset_type, std::complex<scalar_type> >& out_matrix) { bool success = ssa_ids_internal<index_type, offset_type, std::complex<scalar_type> >( num_rows, num_cols, col_values, col_leading_dim, sparsity_ratio, sparsity_norm_p, min_num_nnz_per_row, min_num_nnz_per_col, matrix_type, out_matrix); if(!success) { assert(false); internal_api_error_set_last( "ssa_ids: Error in complex version"); } return success ? 0 : 1; } // ----------------------------------------------------------------------------- int ssa_error_size() { return internal_api_error_size(); } int ssa_error_string(int i, const char** ptr_to_error_string) { return internal_api_error_string(i, ptr_to_error_string); } int ssa_error_clear() { return internal_api_error_clear(); } // ----------------------------------------------------------------------------- /* User-given pattern */ int ssa_d_pat( int num_rows, int num_cols, const double* col_values, int col_leading_dim, const int* row_offsets, const int* column_ids, int max_num_bins, int impose_null_spaces, enum ssa_matrix_type matrix_type, double* out_row_values) { int ret = ssa_pat( num_rows, num_cols, col_values, col_leading_dim, row_offsets, column_ids, max_num_bins, impose_null_spaces == 0 ? false : true, matrix_type, out_row_values); return ret; } /* User-given parameters for computing L_p norm based pattern. */ int ssa_d_lpn( int num_rows, int num_cols, const double* col_values, int col_leading_dim, double sparsity_ratio, double sparsity_norm_p, int max_num_bins, int impose_null_spaces, enum ssa_matrix_type matrix_type, struct ssa_d_csr* out_matrix) { ssa_csr<int, int, double>* csr = new (std::nothrow) ssa_csr<int, int, double>; if(!csr) { assert(false); internal_api_error_set_last("ssa_d_lpn: Memory allocation failed."); return 1; } int ret = ssa_lpn( num_rows, num_cols, col_values, col_leading_dim, sparsity_ratio, sparsity_norm_p, max_num_bins, impose_null_spaces == 0 ? false : true, matrix_type, *csr); out_matrix->row_offsets = csr->row_offsets; out_matrix->column_ids = csr->column_ids; out_matrix->values = csr->values; out_matrix->reserved = csr; return ret; } int ssa_d_ids( int num_rows, int num_cols, const double* col_values, int col_leading_dim, double sparsity_ratio, double sparsity_norm_p, int min_num_nnz_per_row, int min_num_nnz_per_col, enum ssa_matrix_type matrix_type, struct ssa_d_csr* out_matrix) { ssa_csr<int, int, double>* csr = new (std::nothrow) ssa_csr<int, int, double>; if(!csr) { assert(false); internal_api_error_set_last("ssa_d_ids: Memory allocation failed."); return 1; } int ret = ssa_ids( num_rows, num_cols, col_values, col_leading_dim, sparsity_ratio, sparsity_norm_p, min_num_nnz_per_row, min_num_nnz_per_col, matrix_type, *csr); out_matrix->row_offsets = csr->row_offsets; out_matrix->column_ids = csr->column_ids; out_matrix->values = csr->values; out_matrix->reserved = csr; return ret; } // ----------------------------------------------------------------------------- int ssa_s_pat( int num_rows, int num_cols, const float* col_values, int col_leading_dim, const int* row_offsets, const int* column_ids, int max_num_bins, int impose_null_spaces, enum ssa_matrix_type matrix_type, float* out_row_values) { int ret = ssa_pat( num_rows, num_cols, col_values, col_leading_dim, row_offsets, column_ids, max_num_bins, impose_null_spaces == 0 ? false : true, matrix_type, out_row_values); return ret; } int ssa_s_lpn( int num_rows, int num_cols, const float* col_values, int col_leading_dim, float sparsity_ratio, float sparsity_norm_p, int max_num_bins, int impose_null_spaces, enum ssa_matrix_type matrix_type, struct ssa_s_csr* out_matrix) { ssa_csr<int, int, float>* csr = new (std::nothrow) ssa_csr<int, int, float>; if(!csr) { assert(false); internal_api_error_set_last("ssa_s_lpn: Memory allocation failed."); return 1; } int ret = ssa_lpn( num_rows, num_cols, col_values, col_leading_dim, sparsity_ratio, sparsity_norm_p, max_num_bins, impose_null_spaces == 0 ? false : true, matrix_type, *csr); out_matrix->row_offsets = csr->row_offsets; out_matrix->column_ids = csr->column_ids; out_matrix->values = csr->values; out_matrix->reserved = csr; return ret; } int ssa_s_ids( int num_rows, int num_cols, const float* col_values, int col_leading_dim, float sparsity_ratio, float sparsity_norm_p, int min_num_nnz_per_row, int min_num_nnz_per_col, enum ssa_matrix_type matrix_type, struct ssa_s_csr* out_matrix) { ssa_csr<int, int, float>* csr = new (std::nothrow) ssa_csr<int, int, float>; if(!csr) { assert(false); internal_api_error_set_last("ssa_s_ids: Memory allocation failed."); return 1; } int ret = ssa_ids( num_rows, num_cols, col_values, col_leading_dim, sparsity_ratio, sparsity_norm_p, min_num_nnz_per_row, min_num_nnz_per_col, matrix_type, *csr); out_matrix->row_offsets = csr->row_offsets; out_matrix->column_ids = csr->column_ids; out_matrix->values = csr->values; out_matrix->reserved = csr; return ret; } // ----------------------------------------------------------------------------- int ssa_z_pat( int num_rows, int num_cols, const double* col_values, int col_leading_dim, const int* row_offsets, const int* column_ids, int max_num_bins, int impose_null_spaces, enum ssa_matrix_type matrix_type, double* out_row_values) { int ret = ssa_pat<int,int,std::complex<double> >( num_rows, num_cols, reinterpret_cast<const std::complex<double>*>(col_values), col_leading_dim, row_offsets, column_ids, max_num_bins, impose_null_spaces == 0 ? false : true, matrix_type, reinterpret_cast<std::complex<double>*>(out_row_values)); return ret; } int ssa_z_lpn( int num_rows, int num_cols, const double* col_values, int col_leading_dim, double sparsity_ratio, double sparsity_norm_p, int max_num_bins, int impose_null_spaces, enum ssa_matrix_type matrix_type, struct ssa_z_csr* out_matrix) { ssa_csr<int, int, std::complex<double> >* csr = new (std::nothrow) ssa_csr<int, int, std::complex<double> >; if(!csr) { assert(false); internal_api_error_set_last("ssa_z_lpn: Memory allocation failed."); return 1; } int ret = ssa_lpn( num_rows, num_cols, reinterpret_cast<const std::complex<double>*>(col_values), col_leading_dim, sparsity_ratio, sparsity_norm_p, max_num_bins, impose_null_spaces == 0 ? false : true, matrix_type, *csr); out_matrix->row_offsets = csr->row_offsets; out_matrix->column_ids = csr->column_ids; out_matrix->values = reinterpret_cast<double*>(csr->values); out_matrix->reserved = csr; return ret; } int ssa_z_ids( int num_rows, int num_cols, const double* col_values, int col_leading_dim, double sparsity_ratio, double sparsity_norm_p, int min_num_nnz_per_row, int min_num_nnz_per_col, enum ssa_matrix_type matrix_type, struct ssa_z_csr* out_matrix) { ssa_csr<int, int, std::complex<double> >* csr = new (std::nothrow) ssa_csr<int, int, std::complex<double> >; if(!csr) { assert(false); internal_api_error_set_last("ssa_z_ids: Memory allocation failed."); return 1; } int ret = ssa_ids( num_rows, num_cols, reinterpret_cast<const std::complex<double>*>(col_values), col_leading_dim, sparsity_ratio, sparsity_norm_p, min_num_nnz_per_row, min_num_nnz_per_col, matrix_type, *csr); out_matrix->row_offsets = csr->row_offsets; out_matrix->column_ids = csr->column_ids; out_matrix->values = reinterpret_cast<double*>(csr->values); out_matrix->reserved = csr; return ret; } // ----------------------------------------------------------------------------- int ssa_c_pat( int num_rows, int num_cols, const float* col_values, int col_leading_dim, const int* row_offsets, const int* column_ids, int max_num_bins, int impose_null_spaces, enum ssa_matrix_type matrix_type, float* out_row_values) { int ret = ssa_pat<int,int,std::complex<float> >( num_rows, num_cols, reinterpret_cast<const std::complex<float>*>(col_values), col_leading_dim, row_offsets, column_ids, max_num_bins, impose_null_spaces == 0 ? false : true, matrix_type, reinterpret_cast<std::complex<float>*>(out_row_values)); return ret; } int ssa_c_lpn( int num_rows, int num_cols, const float* col_values, int col_leading_dim, float sparsity_ratio, float sparsity_norm_p, int max_num_bins, int impose_null_spaces, enum ssa_matrix_type matrix_type, struct ssa_c_csr* out_matrix) { ssa_csr<int, int, std::complex<float> >* csr = new (std::nothrow) ssa_csr<int, int, std::complex<float> >; if(!csr) { assert(false); internal_api_error_set_last("ssa_c_lpn: Memory allocation failed."); return 1; } int ret = ssa_lpn( num_rows, num_cols, reinterpret_cast<const std::complex<float>*>(col_values), col_leading_dim, sparsity_ratio, sparsity_norm_p, max_num_bins, impose_null_spaces == 0 ? false : true, matrix_type, *csr); out_matrix->row_offsets = csr->row_offsets; out_matrix->column_ids = csr->column_ids; out_matrix->values = reinterpret_cast<float*>(csr->values); out_matrix->reserved = csr; return ret; } int ssa_c_ids( int num_rows, int num_cols, const float* col_values, int col_leading_dim, float sparsity_ratio, float sparsity_norm_p, int min_num_nnz_per_row, int min_num_nnz_per_col, enum ssa_matrix_type matrix_type, struct ssa_c_csr* out_matrix) { ssa_csr<int, int, std::complex<float> >* csr = new (std::nothrow) ssa_csr<int, int, std::complex<float> >; if(!csr) { assert(false); internal_api_error_set_last("ssa_c_ids: Memory allocation failed."); return 1; } int ret = ssa_ids( num_rows, num_cols, reinterpret_cast<const std::complex<float>*>(col_values), col_leading_dim, sparsity_ratio, sparsity_norm_p, min_num_nnz_per_row, min_num_nnz_per_col, matrix_type, *csr); out_matrix->row_offsets = csr->row_offsets; out_matrix->column_ids = csr->column_ids; out_matrix->values = reinterpret_cast<float*>(csr->values); out_matrix->reserved = csr; return ret; } // ----------------------------------------------------------------------------- void ssa_d_csr_deallocate(struct ssa_d_csr* matrix) { if(matrix) { matrix->row_offsets = 0; matrix->column_ids = 0; matrix->values = 0; delete_catch( reinterpret_cast< const ssa_csr<int, int, double>*>( matrix->reserved), "ssa_d_csr_deallocate"); matrix->reserved = 0; } } void ssa_s_csr_deallocate(struct ssa_s_csr* matrix) { if(matrix) { matrix->row_offsets = 0; matrix->column_ids = 0; matrix->values = 0; delete_catch( reinterpret_cast< const ssa_csr<int, int, float>*>( matrix->reserved), "ssa_s_csr_deallocate"); matrix->reserved = 0; } } void ssa_z_csr_deallocate(struct ssa_z_csr* matrix) { if(matrix) { matrix->row_offsets = 0; matrix->column_ids = 0; matrix->values = 0; delete_catch( reinterpret_cast< const ssa_csr<int, int, std::complex<double> >*>( matrix->reserved), "ssa_z_csr_deallocate"); matrix->reserved = 0; } } void ssa_c_csr_deallocate(struct ssa_c_csr* matrix) { if(matrix) { matrix->row_offsets = 0; matrix->column_ids = 0; matrix->values = 0; delete_catch( reinterpret_cast< const ssa_csr<int, int, std::complex<float> >*>( matrix->reserved), "ssa_c_csr_deallocate"); matrix->reserved = 0; } } // ----------------------------------------------------------------------------- // instantiate the template functions explicitly. #define SSA_INSTANTIATE_PAT_LPN(index, offset, scalar) \ \ template TXSSA_API int ssa_pat<index, offset, scalar>( \ index num_rows, \ index num_cols, \ const scalar* col_values, \ index col_leading_dim, \ const offset* row_offsets, \ const index* column_ids, \ offset max_num_bins, \ bool impose_null_spaces, \ enum ssa_matrix_type matrix_type, \ scalar* out_row_values); \ \ template TXSSA_API int ssa_lpn<index, offset, scalar>( \ index num_rows, \ index num_cols, \ const scalar* col_values, \ index col_leading_dim, \ scalar sparsity_ratio, \ scalar sparsity_norm_p, \ offset max_num_bins, \ bool impose_null_spaces, \ enum ssa_matrix_type matrix_type, \ ssa_csr<index, offset, scalar>& out_matrix); \ \ template TXSSA_API int ssa_pat<index, offset, std::complex<scalar> >( \ index num_rows, \ index num_cols, \ const std::complex<scalar>* col_values, \ index col_leading_dim, \ const offset* row_offsets, \ const index* column_ids, \ offset max_num_bins, \ bool impose_null_spaces, \ enum ssa_matrix_type matrix_type, \ std::complex<scalar>* out_row_values); \ \ template TXSSA_API int ssa_lpn<index, offset, scalar>( \ index num_rows, \ index num_cols, \ const std::complex<scalar>* col_values, \ index col_leading_dim, \ scalar sparsity_ratio, \ scalar sparsity_norm_p, \ offset max_num_bins, \ bool impose_null_spaces, \ enum ssa_matrix_type matrix_type, \ ssa_csr<index, offset, std::complex<scalar> >& out_matrix) #define SSA_INSTANTIATE_IDS(index, offset, scalar) \ template TXSSA_API int ssa_ids<index, offset, scalar>( \ index num_rows, \ index num_cols, \ const scalar* col_values, \ index col_leading_dim, \ scalar sparsity_ratio, \ scalar sparsity_norm_p, \ index min_num_nnz_per_row, \ index min_num_nnz_per_col, \ enum ssa_matrix_type matrix_type, \ ssa_csr<index, offset, scalar>& out_matrix); \ template TXSSA_API int ssa_ids<index, offset, scalar>( \ index num_rows, \ index num_cols, \ const std::complex<scalar>* col_values, \ index col_leading_dim, \ scalar sparsity_ratio, \ scalar sparsity_norm_p, \ index min_num_nnz_per_row, \ index min_num_nnz_per_col, \ enum ssa_matrix_type matrix_type, \ ssa_csr<index, offset, std::complex<scalar> >& out_matrix) #define SSA_INSTANTIATE_CSR(index, offset, scalar) \ template ssa_csr<index, offset, scalar>::ssa_csr(); \ template ssa_csr<index, offset, scalar>::~ssa_csr(); \ template ssa_csr<index, offset, std::complex<scalar> >::ssa_csr(); \ template ssa_csr<index, offset, std::complex<scalar> >::~ssa_csr() #define SSA_INSTANTIATE_PAT_LPN_IDS_CSR(index, offset, scalar) \ SSA_INSTANTIATE_PAT_LPN(index, offset, scalar); \ SSA_INSTANTIATE_PAT_LPN(unsigned index, unsigned offset, scalar); \ SSA_INSTANTIATE_IDS(index, offset, scalar); \ SSA_INSTANTIATE_IDS(unsigned index, unsigned offset, scalar); \ SSA_INSTANTIATE_CSR(index, offset, scalar); \ SSA_INSTANTIATE_CSR(unsigned index, unsigned offset, scalar) #define SSA_INSTANTIATE_PAT_LPN_IDS_CSR_all_float(index, offset) \ SSA_INSTANTIATE_PAT_LPN_IDS_CSR(index, offset, float); \ SSA_INSTANTIATE_PAT_LPN_IDS_CSR(index, offset, double) // Commenting out the less used ones. //SSA_INSTANTIATE_PAT_LPN_IDS_CSR_all_float(char, char); //SSA_INSTANTIATE_PAT_LPN_IDS_CSR_all_float(char, short); //SSA_INSTANTIATE_PAT_LPN_IDS_CSR_all_float(char, int); //SSA_INSTANTIATE_PAT_LPN_IDS_CSR_all_float(char, long); //SSA_INSTANTIATE_PAT_LPN_IDS_CSR_all_float(short, short); //SSA_INSTANTIATE_PAT_LPN_IDS_CSR_all_float(short, int); //SSA_INSTANTIATE_PAT_LPN_IDS_CSR_all_float(short, long); SSA_INSTANTIATE_PAT_LPN_IDS_CSR_all_float(int, int); //SSA_INSTANTIATE_PAT_LPN_IDS_CSR_all_float(int, long); #if defined(__x86_64__) SSA_INSTANTIATE_PAT_LPN_IDS_CSR_all_float(long, long); #endif #if defined(_WIN64) SSA_INSTANTIATE_PAT_LPN_IDS_CSR_all_float(long long, long long); #endif
32.062204
115
0.570998
69487bfe15f2bd11008fa77ab7d09fc840276e09
616
cpp
C++
5_Classes_Objects/5_7_Using_this.cpp
YinHk-Forks/CPP-Notes
7dd1895d44cd3773e5f2603cbc3b02d174285b05
[ "MIT" ]
4
2020-12-30T15:16:39.000Z
2021-11-07T17:17:02.000Z
5_Classes_Objects/5_7_Using_this.cpp
YinHk-Forks/CPP-Notes
7dd1895d44cd3773e5f2603cbc3b02d174285b05
[ "MIT" ]
null
null
null
5_Classes_Objects/5_7_Using_this.cpp
YinHk-Forks/CPP-Notes
7dd1895d44cd3773e5f2603cbc3b02d174285b05
[ "MIT" ]
3
2021-04-03T08:00:36.000Z
2022-01-01T06:19:58.000Z
// // CPP-Notes // // Created by Akshay Raj Gollahalli on 23/05/16. // Copyright © 2016 Akshay Raj Gollahalli. All rights reserved. // #include <cstdio> class Some_class { int _s = 0; public: void setter(int i) {_s = i;} int getter(); }; int Some_class::getter() { printf("%p\n", this); // pointing to this object return _s; } int main(int argc, char ** argv){ int aa = 10; Some_class a; a.setter(aa); printf("%d\n", a.getter()); printf("%p\n", &a); // pointing to `a` object // The address of `a` should be equal to Some_class return 0; }
17.111111
64
0.573052
694aa5ea782be07cf443d4709085a47bb79d561b
1,106
cpp
C++
Bus/MessageBus.cpp
ngrande/Banshee
4109b546c305a45de3675ddf149dbe64af934940
[ "MIT" ]
null
null
null
Bus/MessageBus.cpp
ngrande/Banshee
4109b546c305a45de3675ddf149dbe64af934940
[ "MIT" ]
null
null
null
Bus/MessageBus.cpp
ngrande/Banshee
4109b546c305a45de3675ddf149dbe64af934940
[ "MIT" ]
null
null
null
// // Copyright (c) 2016 by Niclas Grande. All Rights Reserved. // #include "MessageBus.h" #include <algorithm> MessageBus::MessageBus(void) { this->pStopped = false; this->pMsgThread = std::thread(&MessageBus::processMsgQueue, this); this->pMsgThread.detach(); } void MessageBus::processMsgQueue() { while (!pStopped) { std::unique_lock<std::mutex> lck(cv_m); cv.wait(lck); while (!this->pMsgQueue.empty()) { auto queuedMsg = this->pMsgQueue.front(); this->pMsgQueue.pop(); // process queuedItem here auto msgCode = queuedMsg.getCode(); switch (msgCode) { case Code::PLAY_SOUND: // handle play sound message std::cout << "PLAY_SOUND message received!" << std::endl; break; case Code::STOP_SOUND: std::cout << "STOP_SOUND message receieved!" << std::endl; break; case Code::FLUSH_BUFFER: std::cout << "FLUSH_BUFFER message received!" << std::endl; break; } } } } void MessageBus::sendMessage(Message &msg) { this->pMsgQueue.push(msg); this->cv.notify_all(); }
24.577778
69
0.621157